langchain 0.3.22 → 0.3.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat_models/universal.cjs +16 -9
- package/dist/chat_models/universal.d.ts +10 -5
- package/dist/chat_models/universal.js +14 -8
- package/dist/experimental/chrome_ai/app/dist/bundle.cjs +1250 -0
- package/dist/experimental/chrome_ai/app/dist/bundle.d.ts +1 -0
- package/dist/experimental/chrome_ai/app/dist/bundle.js +1249 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1249 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
|
|
3
|
+
* This devtool is neither made for production nor for readable output files.
|
|
4
|
+
* It uses "eval()" calls to create a separate source file in the browser devtools.
|
|
5
|
+
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
|
|
6
|
+
* or disable the default devtool with "devtool: false".
|
|
7
|
+
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
|
|
8
|
+
*/
|
|
9
|
+
/******/ (() => {
|
|
10
|
+
// webpackBootstrap
|
|
11
|
+
/******/ var __webpack_modules__ = {
|
|
12
|
+
/***/ "./node_modules/ansi-styles/index.js":
|
|
13
|
+
/*!*******************************************!*\
|
|
14
|
+
!*** ./node_modules/ansi-styles/index.js ***!
|
|
15
|
+
\*******************************************/
|
|
16
|
+
/***/ (module, __unused_webpack_exports, __webpack_require__) => {
|
|
17
|
+
"use strict";
|
|
18
|
+
eval("/* module decorator */ module = __webpack_require__.nmd(module);\n\n\nconst ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\toverline: [53, 55],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\n\t\t\t// Bright color\n\t\t\tblackBright: [90, 39],\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Alias bright black as gray (and grey)\n\tstyles.color.gray = styles.color.blackBright;\n\tstyles.bgColor.bgGray = styles.bgColor.bgBlackBright;\n\tstyles.color.grey = styles.color.blackBright;\n\tstyles.bgColor.bgGrey = styles.bgColor.bgBlackBright;\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue: (red, green, blue) => {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16 +\n\t\t\t\t\t(36 * Math.round(red / 255 * 5)) +\n\t\t\t\t\t(6 * Math.round(green / 255 * 5)) +\n\t\t\t\t\tMath.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue: hex => {\n\t\t\t\tconst matches = /(?<colorString>[a-f\\d]{6}|[a-f\\d]{3})/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet {colorString} = matches.groups;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = colorString.split('').map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false\n\t\t}\n\t});\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/ansi-styles/index.js?");
|
|
19
|
+
/***/
|
|
20
|
+
},
|
|
21
|
+
/***/ "./node_modules/base64-js/index.js":
|
|
22
|
+
/*!*****************************************!*\
|
|
23
|
+
!*** ./node_modules/base64-js/index.js ***!
|
|
24
|
+
\*****************************************/
|
|
25
|
+
/***/ (__unused_webpack_module, exports) => {
|
|
26
|
+
"use strict";
|
|
27
|
+
eval("\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/base64-js/index.js?");
|
|
28
|
+
/***/
|
|
29
|
+
},
|
|
30
|
+
/***/ "./node_modules/camelcase/index.js":
|
|
31
|
+
/*!*****************************************!*\
|
|
32
|
+
!*** ./node_modules/camelcase/index.js ***!
|
|
33
|
+
\*****************************************/
|
|
34
|
+
/***/ (module) => {
|
|
35
|
+
"use strict";
|
|
36
|
+
eval("\n\nconst UPPERCASE = /[\\p{Lu}]/u;\nconst LOWERCASE = /[\\p{Ll}]/u;\nconst LEADING_CAPITAL = /^[\\p{Lu}](?![\\p{Lu}])/gu;\nconst IDENTIFIER = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst SEPARATORS = /[_.\\- ]+/;\n\nconst LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);\nconst SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');\nconst NUMBERS_AND_IDENTIFIER = new RegExp('\\\\d+' + IDENTIFIER.source, 'gu');\n\nconst preserveCamelCase = (string, toLowerCase, toUpperCase) => {\n\tlet isLastCharLower = false;\n\tlet isLastCharUpper = false;\n\tlet isLastLastCharUpper = false;\n\n\tfor (let i = 0; i < string.length; i++) {\n\t\tconst character = string[i];\n\n\t\tif (isLastCharLower && UPPERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i) + '-' + string.slice(i);\n\t\t\tisLastCharLower = false;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = true;\n\t\t\ti++;\n\t\t} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i - 1) + '-' + string.slice(i - 1);\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = false;\n\t\t\tisLastCharLower = true;\n\t\t} else {\n\t\t\tisLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;\n\t\t}\n\t}\n\n\treturn string;\n};\n\nconst preserveConsecutiveUppercase = (input, toLowerCase) => {\n\tLEADING_CAPITAL.lastIndex = 0;\n\n\treturn input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1));\n};\n\nconst postProcess = (input, toUpperCase) => {\n\tSEPARATORS_AND_IDENTIFIER.lastIndex = 0;\n\tNUMBERS_AND_IDENTIFIER.lastIndex = 0;\n\n\treturn input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier))\n\t\t.replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));\n};\n\nconst camelCase = (input, options) => {\n\tif (!(typeof input === 'string' || Array.isArray(input))) {\n\t\tthrow new TypeError('Expected the input to be `string | string[]`');\n\t}\n\n\toptions = {\n\t\tpascalCase: false,\n\t\tpreserveConsecutiveUppercase: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(input)) {\n\t\tinput = input.map(x => x.trim())\n\t\t\t.filter(x => x.length)\n\t\t\t.join('-');\n\t} else {\n\t\tinput = input.trim();\n\t}\n\n\tif (input.length === 0) {\n\t\treturn '';\n\t}\n\n\tconst toLowerCase = options.locale === false ?\n\t\tstring => string.toLowerCase() :\n\t\tstring => string.toLocaleLowerCase(options.locale);\n\tconst toUpperCase = options.locale === false ?\n\t\tstring => string.toUpperCase() :\n\t\tstring => string.toLocaleUpperCase(options.locale);\n\n\tif (input.length === 1) {\n\t\treturn options.pascalCase ? toUpperCase(input) : toLowerCase(input);\n\t}\n\n\tconst hasUpperCase = input !== toLowerCase(input);\n\n\tif (hasUpperCase) {\n\t\tinput = preserveCamelCase(input, toLowerCase, toUpperCase);\n\t}\n\n\tinput = input.replace(LEADING_SEPARATORS, '');\n\n\tif (options.preserveConsecutiveUppercase) {\n\t\tinput = preserveConsecutiveUppercase(input, toLowerCase);\n\t} else {\n\t\tinput = toLowerCase(input);\n\t}\n\n\tif (options.pascalCase) {\n\t\tinput = toUpperCase(input.charAt(0)) + input.slice(1);\n\t}\n\n\treturn postProcess(input, toUpperCase);\n};\n\nmodule.exports = camelCase;\n// TODO: Remove this for the next major release\nmodule.exports[\"default\"] = camelCase;\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/camelcase/index.js?");
|
|
37
|
+
/***/
|
|
38
|
+
},
|
|
39
|
+
/***/ "./node_modules/decamelize/index.js":
|
|
40
|
+
/*!******************************************!*\
|
|
41
|
+
!*** ./node_modules/decamelize/index.js ***!
|
|
42
|
+
\******************************************/
|
|
43
|
+
/***/ (module) => {
|
|
44
|
+
"use strict";
|
|
45
|
+
eval("\nmodule.exports = function (str, sep) {\n\tif (typeof str !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\tsep = typeof sep === 'undefined' ? '_' : sep;\n\n\treturn str\n\t\t.replace(/([a-z\\d])([A-Z])/g, '$1' + sep + '$2')\n\t\t.replace(/([A-Z]+)([A-Z][a-z\\d]+)/g, '$1' + sep + '$2')\n\t\t.toLowerCase();\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/decamelize/index.js?");
|
|
46
|
+
/***/
|
|
47
|
+
},
|
|
48
|
+
/***/ "./node_modules/eventemitter3/index.js":
|
|
49
|
+
/*!*********************************************!*\
|
|
50
|
+
!*** ./node_modules/eventemitter3/index.js ***!
|
|
51
|
+
\*********************************************/
|
|
52
|
+
/***/ (module) => {
|
|
53
|
+
"use strict";
|
|
54
|
+
eval("\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif (true) {\n module.exports = EventEmitter;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/eventemitter3/index.js?");
|
|
55
|
+
/***/
|
|
56
|
+
},
|
|
57
|
+
/***/ "./node_modules/p-finally/index.js":
|
|
58
|
+
/*!*****************************************!*\
|
|
59
|
+
!*** ./node_modules/p-finally/index.js ***!
|
|
60
|
+
\*****************************************/
|
|
61
|
+
/***/ (module) => {
|
|
62
|
+
"use strict";
|
|
63
|
+
eval("\nmodule.exports = (promise, onFinally) => {\n\tonFinally = onFinally || (() => {});\n\n\treturn promise.then(\n\t\tval => new Promise(resolve => {\n\t\t\tresolve(onFinally());\n\t\t}).then(() => val),\n\t\terr => new Promise(resolve => {\n\t\t\tresolve(onFinally());\n\t\t}).then(() => {\n\t\t\tthrow err;\n\t\t})\n\t);\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/p-finally/index.js?");
|
|
64
|
+
/***/
|
|
65
|
+
},
|
|
66
|
+
/***/ "./node_modules/p-queue/dist/index.js":
|
|
67
|
+
/*!********************************************!*\
|
|
68
|
+
!*** ./node_modules/p-queue/dist/index.js ***!
|
|
69
|
+
\********************************************/
|
|
70
|
+
/***/ (__unused_webpack_module, exports, __webpack_require__) => {
|
|
71
|
+
"use strict";
|
|
72
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst EventEmitter = __webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.js\");\nconst p_timeout_1 = __webpack_require__(/*! p-timeout */ \"./node_modules/p-timeout/index.js\");\nconst priority_queue_1 = __webpack_require__(/*! ./priority-queue */ \"./node_modules/p-queue/dist/priority-queue.js\");\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst empty = () => { };\nconst timeoutError = new p_timeout_1.TimeoutError();\n/**\nPromise queue with concurrency control.\n*/\nclass PQueue extends EventEmitter {\n constructor(options) {\n var _a, _b, _c, _d;\n super();\n this._intervalCount = 0;\n this._intervalEnd = 0;\n this._pendingCount = 0;\n this._resolveEmpty = empty;\n this._resolveIdle = empty;\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options);\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n 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})`);\n }\n this._carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0;\n this._intervalCap = options.intervalCap;\n this._interval = options.interval;\n this._queue = new options.queueClass();\n this._queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this._timeout = options.timeout;\n this._throwOnTimeout = options.throwOnTimeout === true;\n this._isPaused = options.autoStart === false;\n }\n get _doesIntervalAllowAnother() {\n return this._isIntervalIgnored || this._intervalCount < this._intervalCap;\n }\n get _doesConcurrentAllowAnother() {\n return this._pendingCount < this._concurrency;\n }\n _next() {\n this._pendingCount--;\n this._tryToStartAnother();\n this.emit('next');\n }\n _resolvePromises() {\n this._resolveEmpty();\n this._resolveEmpty = empty;\n if (this._pendingCount === 0) {\n this._resolveIdle();\n this._resolveIdle = empty;\n this.emit('idle');\n }\n }\n _onResumeInterval() {\n this._onInterval();\n this._initializeIntervalIfNeeded();\n this._timeoutId = undefined;\n }\n _isIntervalPaused() {\n const now = Date.now();\n if (this._intervalId === undefined) {\n const delay = this._intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0;\n }\n else {\n // Act as the interval is pending\n if (this._timeoutId === undefined) {\n this._timeoutId = setTimeout(() => {\n this._onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n _tryToStartAnother() {\n if (this._queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this._intervalId) {\n clearInterval(this._intervalId);\n }\n this._intervalId = undefined;\n this._resolvePromises();\n return false;\n }\n if (!this._isPaused) {\n const canInitializeInterval = !this._isIntervalPaused();\n if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) {\n const job = this._queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this._initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n _initializeIntervalIfNeeded() {\n if (this._isIntervalIgnored || this._intervalId !== undefined) {\n return;\n }\n this._intervalId = setInterval(() => {\n this._onInterval();\n }, this._interval);\n this._intervalEnd = Date.now() + this._interval;\n }\n _onInterval() {\n if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) {\n clearInterval(this._intervalId);\n this._intervalId = undefined;\n }\n this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0;\n this._processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n _processQueue() {\n // eslint-disable-next-line no-empty\n while (this._tryToStartAnother()) { }\n }\n get concurrency() {\n return this._concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this._concurrency = newConcurrency;\n this._processQueue();\n }\n /**\n Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options = {}) {\n return new Promise((resolve, reject) => {\n const run = async () => {\n this._pendingCount++;\n this._intervalCount++;\n try {\n const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => {\n if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) {\n reject(timeoutError);\n }\n return undefined;\n });\n resolve(await operation);\n }\n catch (error) {\n reject(error);\n }\n this._next();\n };\n this._queue.enqueue(run, options);\n this._tryToStartAnother();\n this.emit('add');\n });\n }\n /**\n Same as `.add()`, but accepts an array of sync or async functions.\n\n @returns A promise that resolves when all functions are resolved.\n */\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n 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.)\n */\n start() {\n if (!this._isPaused) {\n return this;\n }\n this._isPaused = false;\n this._processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this._isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this._queue = new this._queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this._queue.size === 0) {\n return;\n }\n return new Promise(resolve => {\n const existingResolve = this._resolveEmpty;\n this._resolveEmpty = () => {\n existingResolve();\n resolve();\n };\n });\n }\n /**\n 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.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this._pendingCount === 0 && this._queue.size === 0) {\n return;\n }\n return new Promise(resolve => {\n const existingResolve = this._resolveIdle;\n this._resolveIdle = () => {\n existingResolve();\n resolve();\n };\n });\n }\n /**\n Size of the queue.\n */\n get size() {\n return this._queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-fn-reference-in-iterator\n return this._queue.filter(options).length;\n }\n /**\n Number of pending promises.\n */\n get pending() {\n return this._pendingCount;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this._isPaused;\n }\n get timeout() {\n return this._timeout;\n }\n /**\n Set the timeout for future operations.\n */\n set timeout(milliseconds) {\n this._timeout = milliseconds;\n }\n}\nexports[\"default\"] = PQueue;\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/p-queue/dist/index.js?");
|
|
73
|
+
/***/
|
|
74
|
+
},
|
|
75
|
+
/***/ "./node_modules/p-queue/dist/lower-bound.js":
|
|
76
|
+
/*!**************************************************!*\
|
|
77
|
+
!*** ./node_modules/p-queue/dist/lower-bound.js ***!
|
|
78
|
+
\**************************************************/
|
|
79
|
+
/***/ (__unused_webpack_module, exports) => {
|
|
80
|
+
"use strict";
|
|
81
|
+
eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\n// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nfunction lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = (count / 2) | 0;\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\nexports["default"] = lowerBound;\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/p-queue/dist/lower-bound.js?');
|
|
82
|
+
/***/
|
|
83
|
+
},
|
|
84
|
+
/***/ "./node_modules/p-queue/dist/priority-queue.js":
|
|
85
|
+
/*!*****************************************************!*\
|
|
86
|
+
!*** ./node_modules/p-queue/dist/priority-queue.js ***!
|
|
87
|
+
\*****************************************************/
|
|
88
|
+
/***/ (__unused_webpack_module, exports, __webpack_require__) => {
|
|
89
|
+
"use strict";
|
|
90
|
+
eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nconst lower_bound_1 = __webpack_require__(/*! ./lower-bound */ "./node_modules/p-queue/dist/lower-bound.js");\nclass PriorityQueue {\n constructor() {\n this._queue = [];\n }\n enqueue(run, options) {\n options = Object.assign({ priority: 0 }, options);\n const element = {\n priority: options.priority,\n run\n };\n if (this.size && this._queue[this.size - 1].priority >= options.priority) {\n this._queue.push(element);\n return;\n }\n const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority);\n this._queue.splice(index, 0, element);\n }\n dequeue() {\n const item = this._queue.shift();\n return item === null || item === void 0 ? void 0 : item.run;\n }\n filter(options) {\n return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this._queue.length;\n }\n}\nexports["default"] = PriorityQueue;\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/p-queue/dist/priority-queue.js?');
|
|
91
|
+
/***/
|
|
92
|
+
},
|
|
93
|
+
/***/ "./node_modules/p-retry/index.js":
|
|
94
|
+
/*!***************************************!*\
|
|
95
|
+
!*** ./node_modules/p-retry/index.js ***!
|
|
96
|
+
\***************************************/
|
|
97
|
+
/***/ (module, __unused_webpack_exports, __webpack_require__) => {
|
|
98
|
+
"use strict";
|
|
99
|
+
eval("\nconst retry = __webpack_require__(/*! retry */ \"./node_modules/retry/index.js\");\n\nconst networkErrorMsgs = [\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari\n\t'Network request failed' // `cross-fetch`\n];\n\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nconst isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);\n\nconst pRetry = (input, options) => new Promise((resolve, reject) => {\n\toptions = {\n\t\tonFailedAttempt: () => {},\n\t\tretries: 10,\n\t\t...options\n\t};\n\n\tconst operation = retry.operation(options);\n\n\toperation.attempt(async attemptNumber => {\n\t\ttry {\n\t\t\tresolve(await input(attemptNumber));\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\treject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (error instanceof AbortError) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error.originalError);\n\t\t\t} else if (error instanceof TypeError && !isNetworkError(error.message)) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error);\n\t\t\t} else {\n\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\treject(operation.mainError());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n});\n\nmodule.exports = pRetry;\n// TODO: remove this in the next major version\nmodule.exports[\"default\"] = pRetry;\n\nmodule.exports.AbortError = AbortError;\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/p-retry/index.js?");
|
|
100
|
+
/***/
|
|
101
|
+
},
|
|
102
|
+
/***/ "./node_modules/p-timeout/index.js":
|
|
103
|
+
/*!*****************************************!*\
|
|
104
|
+
!*** ./node_modules/p-timeout/index.js ***!
|
|
105
|
+
\*****************************************/
|
|
106
|
+
/***/ (module, __unused_webpack_exports, __webpack_require__) => {
|
|
107
|
+
"use strict";
|
|
108
|
+
eval("\n\nconst pFinally = __webpack_require__(/*! p-finally */ \"./node_modules/p-finally/index.js\");\n\nclass TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\nconst pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => {\n\tif (typeof milliseconds !== 'number' || milliseconds < 0) {\n\t\tthrow new TypeError('Expected `milliseconds` to be a positive number');\n\t}\n\n\tif (milliseconds === Infinity) {\n\t\tresolve(promise);\n\t\treturn;\n\t}\n\n\tconst timer = setTimeout(() => {\n\t\tif (typeof fallback === 'function') {\n\t\t\ttry {\n\t\t\t\tresolve(fallback());\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;\n\t\tconst timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);\n\n\t\tif (typeof promise.cancel === 'function') {\n\t\t\tpromise.cancel();\n\t\t}\n\n\t\treject(timeoutError);\n\t}, milliseconds);\n\n\t// TODO: Use native `finally` keyword when targeting Node.js 10\n\tpFinally(\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\tpromise.then(resolve, reject),\n\t\t() => {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t);\n});\n\nmodule.exports = pTimeout;\n// TODO: Remove this for the next major release\nmodule.exports[\"default\"] = pTimeout;\n\nmodule.exports.TimeoutError = TimeoutError;\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/p-timeout/index.js?");
|
|
109
|
+
/***/
|
|
110
|
+
},
|
|
111
|
+
/***/ "./node_modules/retry/index.js":
|
|
112
|
+
/*!*************************************!*\
|
|
113
|
+
!*** ./node_modules/retry/index.js ***!
|
|
114
|
+
\*************************************/
|
|
115
|
+
/***/ (module, __unused_webpack_exports, __webpack_require__) => {
|
|
116
|
+
eval('module.exports = __webpack_require__(/*! ./lib/retry */ "./node_modules/retry/lib/retry.js");\n\n//# sourceURL=webpack://chrome_ai/./node_modules/retry/index.js?');
|
|
117
|
+
/***/
|
|
118
|
+
},
|
|
119
|
+
/***/ "./node_modules/retry/lib/retry.js":
|
|
120
|
+
/*!*****************************************!*\
|
|
121
|
+
!*** ./node_modules/retry/lib/retry.js ***!
|
|
122
|
+
\*****************************************/
|
|
123
|
+
/***/ (__unused_webpack_module, exports, __webpack_require__) => {
|
|
124
|
+
eval("var RetryOperation = __webpack_require__(/*! ./retry_operation */ \"./node_modules/retry/lib/retry_operation.js\");\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/retry/lib/retry.js?");
|
|
125
|
+
/***/
|
|
126
|
+
},
|
|
127
|
+
/***/ "./node_modules/retry/lib/retry_operation.js":
|
|
128
|
+
/*!***************************************************!*\
|
|
129
|
+
!*** ./node_modules/retry/lib/retry_operation.js ***!
|
|
130
|
+
\***************************************************/
|
|
131
|
+
/***/ (module) => {
|
|
132
|
+
eval("function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/retry/lib/retry_operation.js?");
|
|
133
|
+
/***/
|
|
134
|
+
},
|
|
135
|
+
/***/ "./node_modules/uuid/dist/esm-browser/native.js":
|
|
136
|
+
/*!******************************************************!*\
|
|
137
|
+
!*** ./node_modules/uuid/dist/esm-browser/native.js ***!
|
|
138
|
+
\******************************************************/
|
|
139
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
140
|
+
"use strict";
|
|
141
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\nconst randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n randomUUID\n});\n\n//# sourceURL=webpack://chrome_ai/./node_modules/uuid/dist/esm-browser/native.js?");
|
|
142
|
+
/***/
|
|
143
|
+
},
|
|
144
|
+
/***/ "./node_modules/uuid/dist/esm-browser/regex.js":
|
|
145
|
+
/*!*****************************************************!*\
|
|
146
|
+
!*** ./node_modules/uuid/dist/esm-browser/regex.js ***!
|
|
147
|
+
\*****************************************************/
|
|
148
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
149
|
+
"use strict";
|
|
150
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);\n\n//# sourceURL=webpack://chrome_ai/./node_modules/uuid/dist/esm-browser/regex.js?');
|
|
151
|
+
/***/
|
|
152
|
+
},
|
|
153
|
+
/***/ "./node_modules/uuid/dist/esm-browser/rng.js":
|
|
154
|
+
/*!***************************************************!*\
|
|
155
|
+
!*** ./node_modules/uuid/dist/esm-browser/rng.js ***!
|
|
156
|
+
\***************************************************/
|
|
157
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
158
|
+
"use strict";
|
|
159
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ rng)\n/* harmony export */ });\n// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nfunction rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}\n\n//# sourceURL=webpack://chrome_ai/./node_modules/uuid/dist/esm-browser/rng.js?");
|
|
160
|
+
/***/
|
|
161
|
+
},
|
|
162
|
+
/***/ "./node_modules/uuid/dist/esm-browser/stringify.js":
|
|
163
|
+
/*!*********************************************************!*\
|
|
164
|
+
!*** ./node_modules/uuid/dist/esm-browser/stringify.js ***!
|
|
165
|
+
\*********************************************************/
|
|
166
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
167
|
+
"use strict";
|
|
168
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ unsafeStringify: () => (/* binding */ unsafeStringify)\n/* harmony export */ });\n/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./validate.js */ \"./node_modules/uuid/dist/esm-browser/validate.js\");\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0,_validate_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (stringify);\n\n//# sourceURL=webpack://chrome_ai/./node_modules/uuid/dist/esm-browser/stringify.js?");
|
|
169
|
+
/***/
|
|
170
|
+
},
|
|
171
|
+
/***/ "./node_modules/uuid/dist/esm-browser/v4.js":
|
|
172
|
+
/*!**************************************************!*\
|
|
173
|
+
!*** ./node_modules/uuid/dist/esm-browser/v4.js ***!
|
|
174
|
+
\**************************************************/
|
|
175
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
176
|
+
"use strict";
|
|
177
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _native_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./native.js */ "./node_modules/uuid/dist/esm-browser/native.js");\n/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rng.js */ "./node_modules/uuid/dist/esm-browser/rng.js");\n/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./stringify.js */ "./node_modules/uuid/dist/esm-browser/stringify.js");\n\n\n\n\nfunction v4(options, buf, offset) {\n if (_native_js__WEBPACK_IMPORTED_MODULE_0__["default"].randomUUID && !buf && !options) {\n return _native_js__WEBPACK_IMPORTED_MODULE_0__["default"].randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_1__["default"])(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0,_stringify_js__WEBPACK_IMPORTED_MODULE_2__.unsafeStringify)(rnds);\n}\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (v4);\n\n//# sourceURL=webpack://chrome_ai/./node_modules/uuid/dist/esm-browser/v4.js?');
|
|
178
|
+
/***/
|
|
179
|
+
},
|
|
180
|
+
/***/ "./node_modules/uuid/dist/esm-browser/validate.js":
|
|
181
|
+
/*!********************************************************!*\
|
|
182
|
+
!*** ./node_modules/uuid/dist/esm-browser/validate.js ***!
|
|
183
|
+
\********************************************************/
|
|
184
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
185
|
+
"use strict";
|
|
186
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _regex_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./regex.js */ "./node_modules/uuid/dist/esm-browser/regex.js");\n\n\nfunction validate(uuid) {\n return typeof uuid === \'string\' && _regex_js__WEBPACK_IMPORTED_MODULE_0__["default"].test(uuid);\n}\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (validate);\n\n//# sourceURL=webpack://chrome_ai/./node_modules/uuid/dist/esm-browser/validate.js?');
|
|
187
|
+
/***/
|
|
188
|
+
},
|
|
189
|
+
/***/ "./src/index.js":
|
|
190
|
+
/*!**********************!*\
|
|
191
|
+
!*** ./src/index.js ***!
|
|
192
|
+
\**********************/
|
|
193
|
+
/***/ (__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
|
|
194
|
+
"use strict";
|
|
195
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var langchain_experimental_chat_models_chrome_ai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! langchain/experimental/chat_models/chrome_ai */ "./node_modules/langchain/experimental/chat_models/chrome_ai.js");\n/* harmony import */ var _langchain_core_utils_tiktoken__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @langchain/core/utils/tiktoken */ "./node_modules/@langchain/core/utils/tiktoken.js");\n\n\n\nconst model = new langchain_experimental_chat_models_chrome_ai__WEBPACK_IMPORTED_MODULE_0__.ChatChromeAI();\nconst destroyButton = document.getElementById("destroyButton");\nconst inputForm = document.getElementById("inputForm");\nconst submitButton = inputForm.querySelector("button[type=\'submit\']");\n\n// Initialize the model when the page loads\nwindow.addEventListener("load", async () => {\n try {\n await model.initialize();\n destroyButton.disabled = false;\n submitButton.disabled = false;\n } catch (error) {\n console.error("Failed to initialize model:", error);\n alert("Failed to initialize model. Please try refreshing the page.");\n }\n});\n\ndestroyButton.addEventListener("click", () => {\n model.destroy();\n destroyButton.disabled = true;\n submitButton.disabled = true;\n});\n\ninputForm.addEventListener("submit", async (event) => {\n event.preventDefault();\n const input = document.getElementById("inputField").value;\n const humanMessage = ["human", input];\n\n // Clear previous response\n const responseTextElement = document.getElementById("responseText");\n responseTextElement.textContent = "";\n\n let fullMsg = "";\n let timeToFirstTokenMs = 0;\n let totalTimeMs = 0;\n try {\n const startTime = performance.now();\n for await (const chunk of await model.stream(humanMessage)) {\n if (timeToFirstTokenMs === 0) {\n timeToFirstTokenMs = performance.now() - startTime;\n }\n fullMsg += chunk.content;\n // Update the response element with the new content\n responseTextElement.textContent = fullMsg;\n }\n totalTimeMs = performance.now() - startTime;\n } catch (error) {\n console.error("An error occurred:", error);\n responseTextElement.textContent = "An error occurred: " + error.message;\n }\n\n const encoding = await (0,_langchain_core_utils_tiktoken__WEBPACK_IMPORTED_MODULE_1__.encodingForModel)("gpt2");\n const numTokens = encoding.encode(fullMsg).length;\n\n // Update the stat pills\n document.getElementById(\n "firstTokenTime"\n ).textContent = `First Token: ${Math.round(timeToFirstTokenMs)} ms`;\n document.getElementById("totalTime").textContent = `Total Time: ${Math.round(\n totalTimeMs\n )} ms`;\n document.getElementById(\n "totalTokens"\n ).textContent = `Total Tokens: ${numTokens}`;\n});\n\n\n//# sourceURL=webpack://chrome_ai/./src/index.js?');
|
|
196
|
+
/***/
|
|
197
|
+
},
|
|
198
|
+
/***/ "./node_modules/@langchain/core/dist/caches.js":
|
|
199
|
+
/*!*****************************************************!*\
|
|
200
|
+
!*** ./node_modules/@langchain/core/dist/caches.js ***!
|
|
201
|
+
\*****************************************************/
|
|
202
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
203
|
+
"use strict";
|
|
204
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseCache: () => (/* binding */ BaseCache),\n/* harmony export */ InMemoryCache: () => (/* binding */ InMemoryCache),\n/* harmony export */ deserializeStoredGeneration: () => (/* binding */ deserializeStoredGeneration),\n/* harmony export */ getCacheKey: () => (/* binding */ getCacheKey),\n/* harmony export */ serializeGeneration: () => (/* binding */ serializeGeneration)\n/* harmony export */ });\n/* harmony import */ var _utils_hash_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/hash.js */ "./node_modules/@langchain/core/dist/utils/hash.js");\n/* harmony import */ var _messages_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./messages/utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n\n\n/**\n * This cache key should be consistent across all versions of langchain.\n * It is currently NOT consistent across versions of langchain.\n *\n * A huge benefit of having a remote cache (like redis) is that you can\n * access the cache from different processes/machines. The allows you to\n * seperate concerns and scale horizontally.\n *\n * TODO: Make cache key consistent across versions of langchain.\n */\nconst getCacheKey = (...strings) => (0,_utils_hash_js__WEBPACK_IMPORTED_MODULE_0__.insecureHash)(strings.join("_"));\nfunction deserializeStoredGeneration(storedGeneration) {\n if (storedGeneration.message !== undefined) {\n return {\n text: storedGeneration.text,\n message: (0,_messages_utils_js__WEBPACK_IMPORTED_MODULE_1__.mapStoredMessageToChatMessage)(storedGeneration.message),\n };\n }\n else {\n return { text: storedGeneration.text };\n }\n}\nfunction serializeGeneration(generation) {\n const serializedValue = {\n text: generation.text,\n };\n if (generation.message !== undefined) {\n serializedValue.message = generation.message.toDict();\n }\n return serializedValue;\n}\n/**\n * Base class for all caches. All caches should extend this class.\n */\nclass BaseCache {\n}\nconst GLOBAL_MAP = new Map();\n/**\n * A cache for storing LLM generations that stores data in memory.\n */\nclass InMemoryCache extends BaseCache {\n constructor(map) {\n super();\n Object.defineProperty(this, "cache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.cache = map ?? new Map();\n }\n /**\n * Retrieves data from the cache using a prompt and an LLM key. If the\n * data is not found, it returns null.\n * @param prompt The prompt used to find the data.\n * @param llmKey The LLM key used to find the data.\n * @returns The data corresponding to the prompt and LLM key, or null if not found.\n */\n lookup(prompt, llmKey) {\n return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null);\n }\n /**\n * Updates the cache with new data using a prompt and an LLM key.\n * @param prompt The prompt used to store the data.\n * @param llmKey The LLM key used to store the data.\n * @param value The data to be stored.\n */\n async update(prompt, llmKey, value) {\n this.cache.set(getCacheKey(prompt, llmKey), value);\n }\n /**\n * Returns a global instance of InMemoryCache using a predefined global\n * map as the initial cache.\n * @returns A global instance of InMemoryCache.\n */\n static global() {\n return new InMemoryCache(GLOBAL_MAP);\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/caches.js?');
|
|
205
|
+
/***/
|
|
206
|
+
},
|
|
207
|
+
/***/ "./node_modules/@langchain/core/dist/callbacks/base.js":
|
|
208
|
+
/*!*************************************************************!*\
|
|
209
|
+
!*** ./node_modules/@langchain/core/dist/callbacks/base.js ***!
|
|
210
|
+
\*************************************************************/
|
|
211
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
212
|
+
"use strict";
|
|
213
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseCallbackHandler: () => (/* binding */ BaseCallbackHandler)\n/* harmony export */ });\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");\n/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../load/serializable.js */ "./node_modules/@langchain/core/dist/load/serializable.js");\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/env.js */ "./node_modules/@langchain/core/dist/utils/env.js");\n\n\n\n/**\n * Abstract class that provides a set of optional methods that can be\n * overridden in derived classes to handle various events during the\n * execution of a LangChain application.\n */\nclass BaseCallbackHandlerMethodsClass {\n}\n/**\n * Abstract base class for creating callback handlers in the LangChain\n * framework. It provides a set of optional methods that can be overridden\n * in derived classes to handle various events during the execution of a\n * LangChain application.\n */\nclass BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {\n get lc_namespace() {\n return ["langchain_core", "callbacks", this.name];\n }\n get lc_secrets() {\n return undefined;\n }\n get lc_attributes() {\n return undefined;\n }\n get lc_aliases() {\n return undefined;\n }\n /**\n * The name of the serializable. Override to provide an alias or\n * to preserve the serialized module name in minified environments.\n *\n * Implemented as a static method to support loading logic.\n */\n static lc_name() {\n return this.name;\n }\n /**\n * The final serialized identifier for the module.\n */\n get lc_id() {\n return [\n ...this.lc_namespace,\n (0,_load_serializable_js__WEBPACK_IMPORTED_MODULE_0__.get_lc_unique_name)(this.constructor),\n ];\n }\n constructor(input) {\n super();\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "lc_kwargs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "ignoreLLM", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "ignoreChain", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "ignoreAgent", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "ignoreRetriever", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "raiseError", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "awaitHandlers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_1__.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND") !== "true"\n });\n this.lc_kwargs = input || {};\n if (input) {\n this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM;\n this.ignoreChain = input.ignoreChain ?? this.ignoreChain;\n this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;\n this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;\n this.raiseError = input.raiseError ?? this.raiseError;\n this.awaitHandlers =\n this.raiseError || (input._awaitHandler ?? this.awaitHandlers);\n }\n }\n copy() {\n return new this.constructor(this);\n }\n toJSON() {\n return _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__.Serializable.prototype.toJSON.call(this);\n }\n toJSONNotImplemented() {\n return _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__.Serializable.prototype.toJSONNotImplemented.call(this);\n }\n static fromMethods(methods) {\n class Handler extends BaseCallbackHandler {\n constructor() {\n super();\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: uuid__WEBPACK_IMPORTED_MODULE_2__["default"]()\n });\n Object.assign(this, methods);\n }\n }\n return new Handler();\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/callbacks/base.js?');
|
|
214
|
+
/***/
|
|
215
|
+
},
|
|
216
|
+
/***/ "./node_modules/@langchain/core/dist/callbacks/manager.js":
|
|
217
|
+
/*!****************************************************************!*\
|
|
218
|
+
!*** ./node_modules/@langchain/core/dist/callbacks/manager.js ***!
|
|
219
|
+
\****************************************************************/
|
|
220
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
221
|
+
"use strict";
|
|
222
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseCallbackManager: () => (/* binding */ BaseCallbackManager),\n/* harmony export */ CallbackManager: () => (/* binding */ CallbackManager),\n/* harmony export */ CallbackManagerForChainRun: () => (/* binding */ CallbackManagerForChainRun),\n/* harmony export */ CallbackManagerForLLMRun: () => (/* binding */ CallbackManagerForLLMRun),\n/* harmony export */ CallbackManagerForRetrieverRun: () => (/* binding */ CallbackManagerForRetrieverRun),\n/* harmony export */ CallbackManagerForToolRun: () => (/* binding */ CallbackManagerForToolRun),\n/* harmony export */ TraceGroup: () => (/* binding */ TraceGroup),\n/* harmony export */ ensureHandler: () => (/* binding */ ensureHandler),\n/* harmony export */ parseCallbackConfigArg: () => (/* binding */ parseCallbackConfigArg),\n/* harmony export */ traceAsGroup: () => (/* binding */ traceAsGroup)\n/* harmony export */ });\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/callbacks/base.js");\n/* harmony import */ var _tracers_console_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tracers/console.js */ "./node_modules/@langchain/core/dist/tracers/console.js");\n/* harmony import */ var _tracers_initialize_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tracers/initialize.js */ "./node_modules/@langchain/core/dist/tracers/initialize.js");\n/* harmony import */ var _messages_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../messages/utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/env.js */ "./node_modules/@langchain/core/dist/utils/env.js");\n/* harmony import */ var _tracers_tracer_langchain_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../tracers/tracer_langchain.js */ "./node_modules/@langchain/core/dist/tracers/tracer_langchain.js");\n/* harmony import */ var _promises_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./promises.js */ "./node_modules/@langchain/core/dist/callbacks/promises.js");\n\n\n\n\n\n\n\n\nif (\n/* #__PURE__ */ (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_4__.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true" &&\n /* #__PURE__ */ (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_4__.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND") !==\n "true") {\n /* #__PURE__ */ console.warn([\n "[WARN]: You have enabled LangSmith tracing without backgrounding callbacks.",\n "[WARN]: If you are not using a serverless environment where you must wait for tracing calls to finish,",\n `[WARN]: we suggest setting "process.env.LANGCHAIN_CALLBACKS_BACKGROUND=true" to avoid additional latency.`,\n ].join("\\n"));\n}\nfunction parseCallbackConfigArg(arg) {\n if (!arg) {\n return {};\n }\n else if (Array.isArray(arg) || "name" in arg) {\n return { callbacks: arg };\n }\n else {\n return arg;\n }\n}\n/**\n * Manage callbacks from different components of LangChain.\n */\nclass BaseCallbackManager {\n setHandler(handler) {\n return this.setHandlers([handler]);\n }\n}\n/**\n * Base class for run manager in LangChain.\n */\nclass BaseRunManager {\n constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) {\n Object.defineProperty(this, "runId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: runId\n });\n Object.defineProperty(this, "handlers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: handlers\n });\n Object.defineProperty(this, "inheritableHandlers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: inheritableHandlers\n });\n Object.defineProperty(this, "tags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: tags\n });\n Object.defineProperty(this, "inheritableTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: inheritableTags\n });\n Object.defineProperty(this, "metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: metadata\n });\n Object.defineProperty(this, "inheritableMetadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: inheritableMetadata\n });\n Object.defineProperty(this, "_parentRunId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: _parentRunId\n });\n }\n async handleText(text) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n try {\n await handler.handleText?.(text, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleText: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }, handler.awaitHandlers)));\n }\n}\n/**\n * Manages callbacks for retriever runs.\n */\nclass CallbackManagerForRetrieverRun extends BaseRunManager {\n getChild(tag) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const manager = new CallbackManager(this.runId);\n manager.setHandlers(this.inheritableHandlers);\n manager.addTags(this.inheritableTags);\n manager.addMetadata(this.inheritableMetadata);\n if (tag) {\n manager.addTags([tag], false);\n }\n return manager;\n }\n async handleRetrieverEnd(documents) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreRetriever) {\n try {\n await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleRetriever`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleRetrieverError(err) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreRetriever) {\n try {\n await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags);\n }\n catch (error) {\n console.error(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n}\nclass CallbackManagerForLLMRun extends BaseRunManager {\n async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreLLM) {\n try {\n await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleLLMError(err) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreLLM) {\n try {\n await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleLLMEnd(output) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreLLM) {\n try {\n await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n}\nclass CallbackManagerForChainRun extends BaseRunManager {\n getChild(tag) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const manager = new CallbackManager(this.runId);\n manager.setHandlers(this.inheritableHandlers);\n manager.addTags(this.inheritableTags);\n manager.addMetadata(this.inheritableMetadata);\n if (tag) {\n manager.addTags([tag], false);\n }\n return manager;\n }\n async handleChainError(err, _runId, _parentRunId, _tags, kwargs) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreChain) {\n try {\n await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreChain) {\n try {\n await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleAgentAction(action) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreAgent) {\n try {\n await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleAgentEnd(action) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreAgent) {\n try {\n await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n}\nclass CallbackManagerForToolRun extends BaseRunManager {\n getChild(tag) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const manager = new CallbackManager(this.runId);\n manager.setHandlers(this.inheritableHandlers);\n manager.addTags(this.inheritableTags);\n manager.addMetadata(this.inheritableMetadata);\n if (tag) {\n manager.addTags([tag], false);\n }\n return manager;\n }\n async handleToolError(err) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreAgent) {\n try {\n await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n async handleToolEnd(output) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreAgent) {\n try {\n await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n }\n}\n/**\n * @example\n * ```typescript\n * const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?");\n *\n * // Example of using LLMChain with OpenAI and a simple prompt\n * const chain = new LLMChain({\n * llm: new ChatOpenAI({ temperature: 0.9 }),\n * prompt,\n * });\n *\n * // Running the chain with a single question\n * const result = await chain.call({\n * question: "What is the airspeed velocity of an unladen swallow?",\n * });\n * console.log("The answer is:", result);\n * ```\n */\nclass CallbackManager extends BaseCallbackManager {\n constructor(parentRunId, options) {\n super();\n Object.defineProperty(this, "handlers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "inheritableHandlers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "tags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "inheritableTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {}\n });\n Object.defineProperty(this, "inheritableMetadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {}\n });\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "callback_manager"\n });\n Object.defineProperty(this, "_parentRunId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.handlers = options?.handlers ?? this.handlers;\n this.inheritableHandlers =\n options?.inheritableHandlers ?? this.inheritableHandlers;\n this.tags = options?.tags ?? this.tags;\n this.inheritableTags = options?.inheritableTags ?? this.inheritableTags;\n this.metadata = options?.metadata ?? this.metadata;\n this.inheritableMetadata =\n options?.inheritableMetadata ?? this.inheritableMetadata;\n this._parentRunId = parentRunId;\n }\n /**\n * Gets the parent run ID, if any.\n *\n * @returns The parent run ID.\n */\n getParentRunId() {\n return this._parentRunId;\n }\n async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {\n return Promise.all(prompts.map(async (prompt, idx) => {\n // Can\'t have duplicate runs with the same run ID (if provided)\n const runId_ = idx === 0 && runId ? runId : (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])();\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreLLM) {\n try {\n await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n }));\n }\n async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {\n return Promise.all(messages.map(async (messageGroup, idx) => {\n // Can\'t have duplicate runs with the same run ID (if provided)\n const runId_ = idx === 0 && runId ? runId : (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])();\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreLLM) {\n try {\n if (handler.handleChatModelStart) {\n await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n }\n else if (handler.handleLLMStart) {\n const messageString = (0,_messages_utils_js__WEBPACK_IMPORTED_MODULE_3__.getBufferString)(messageGroup);\n await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName);\n }\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n }));\n }\n async handleChainStart(chain, inputs, runId = (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreChain) {\n try {\n await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n }\n async handleToolStart(tool, input, runId = (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreAgent) {\n try {\n await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n }\n async handleRetrieverStart(retriever, query, runId = (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {\n await Promise.all(this.handlers.map((handler) => (0,_promises_js__WEBPACK_IMPORTED_MODULE_6__.consumeCallback)(async () => {\n if (!handler.ignoreRetriever) {\n try {\n await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName);\n }\n catch (err) {\n console.error(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`);\n if (handler.raiseError) {\n throw err;\n }\n }\n }\n }, handler.awaitHandlers)));\n return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);\n }\n addHandler(handler, inherit = true) {\n this.handlers.push(handler);\n if (inherit) {\n this.inheritableHandlers.push(handler);\n }\n }\n removeHandler(handler) {\n this.handlers = this.handlers.filter((_handler) => _handler !== handler);\n this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler);\n }\n setHandlers(handlers, inherit = true) {\n this.handlers = [];\n this.inheritableHandlers = [];\n for (const handler of handlers) {\n this.addHandler(handler, inherit);\n }\n }\n addTags(tags, inherit = true) {\n this.removeTags(tags); // Remove duplicates\n this.tags.push(...tags);\n if (inherit) {\n this.inheritableTags.push(...tags);\n }\n }\n removeTags(tags) {\n this.tags = this.tags.filter((tag) => !tags.includes(tag));\n this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag));\n }\n addMetadata(metadata, inherit = true) {\n this.metadata = { ...this.metadata, ...metadata };\n if (inherit) {\n this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata };\n }\n }\n removeMetadata(metadata) {\n for (const key of Object.keys(metadata)) {\n delete this.metadata[key];\n delete this.inheritableMetadata[key];\n }\n }\n copy(additionalHandlers = [], inherit = true) {\n const manager = new CallbackManager(this._parentRunId);\n for (const handler of this.handlers) {\n const inheritable = this.inheritableHandlers.includes(handler);\n manager.addHandler(handler, inheritable);\n }\n for (const tag of this.tags) {\n const inheritable = this.inheritableTags.includes(tag);\n manager.addTags([tag], inheritable);\n }\n for (const key of Object.keys(this.metadata)) {\n const inheritable = Object.keys(this.inheritableMetadata).includes(key);\n manager.addMetadata({ [key]: this.metadata[key] }, inheritable);\n }\n for (const handler of additionalHandlers) {\n if (\n // Prevent multiple copies of console_callback_handler\n manager.handlers\n .filter((h) => h.name === "console_callback_handler")\n .some((h) => h.name === handler.name)) {\n continue;\n }\n manager.addHandler(handler, inherit);\n }\n return manager;\n }\n static fromHandlers(handlers) {\n class Handler extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseCallbackHandler {\n constructor() {\n super();\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: (0,uuid__WEBPACK_IMPORTED_MODULE_7__["default"])()\n });\n Object.assign(this, handlers);\n }\n }\n const manager = new this();\n manager.addHandler(new Handler());\n return manager;\n }\n static async configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) {\n let callbackManager;\n if (inheritableHandlers || localHandlers) {\n if (Array.isArray(inheritableHandlers) || !inheritableHandlers) {\n callbackManager = new CallbackManager();\n callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true);\n }\n else {\n callbackManager = inheritableHandlers;\n }\n callbackManager = callbackManager.copy(Array.isArray(localHandlers)\n ? localHandlers.map(ensureHandler)\n : localHandlers?.handlers, false);\n }\n const verboseEnabled = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_4__.getEnvironmentVariable)("LANGCHAIN_VERBOSE") === "true" ||\n options?.verbose;\n const tracingV2Enabled = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_4__.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true" ||\n (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_4__.getEnvironmentVariable)("LANGSMITH_TRACING") === "true";\n const tracingEnabled = tracingV2Enabled ||\n ((0,_utils_env_js__WEBPACK_IMPORTED_MODULE_4__.getEnvironmentVariable)("LANGCHAIN_TRACING") ?? false);\n if (verboseEnabled || tracingEnabled) {\n if (!callbackManager) {\n callbackManager = new CallbackManager();\n }\n if (verboseEnabled &&\n !callbackManager.handlers.some((handler) => handler.name === _tracers_console_js__WEBPACK_IMPORTED_MODULE_1__.ConsoleCallbackHandler.prototype.name)) {\n const consoleHandler = new _tracers_console_js__WEBPACK_IMPORTED_MODULE_1__.ConsoleCallbackHandler();\n callbackManager.addHandler(consoleHandler, true);\n }\n if (tracingEnabled &&\n !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) {\n if (tracingV2Enabled) {\n const tracerV2 = await (0,_tracers_initialize_js__WEBPACK_IMPORTED_MODULE_2__.getTracingV2CallbackHandler)();\n callbackManager.addHandler(tracerV2, true);\n // handoff between langchain and langsmith/traceable\n // override the parent run ID\n callbackManager._parentRunId =\n tracerV2.getTraceableRunTree()?.id ?? callbackManager._parentRunId;\n }\n }\n }\n if (inheritableTags || localTags) {\n if (callbackManager) {\n callbackManager.addTags(inheritableTags ?? []);\n callbackManager.addTags(localTags ?? [], false);\n }\n }\n if (inheritableMetadata || localMetadata) {\n if (callbackManager) {\n callbackManager.addMetadata(inheritableMetadata ?? {});\n callbackManager.addMetadata(localMetadata ?? {}, false);\n }\n }\n return callbackManager;\n }\n}\nfunction ensureHandler(handler) {\n if ("name" in handler) {\n return handler;\n }\n return _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseCallbackHandler.fromMethods(handler);\n}\n/**\n * @example\n * ```typescript\n * const prompt = PromptTemplate.fromTemplate(`What is the answer to {question}?`);\n *\n * // Example of using LLMChain to process a series of questions\n * const chain = new LLMChain({\n * llm: new ChatOpenAI({ temperature: 0.9 }),\n * prompt,\n * });\n *\n * // Process questions using the chain\n * const processQuestions = async (questions) => {\n * for (const question of questions) {\n * const result = await chain.call({ question });\n * console.log(result);\n * }\n * };\n *\n * // Example questions\n * const questions = [\n * "What is your name?",\n * "What is your quest?",\n * "What is your favorite color?",\n * ];\n *\n * // Run the example\n * processQuestions(questions).catch(console.error);\n *\n * ```\n */\nclass TraceGroup {\n constructor(groupName, options) {\n Object.defineProperty(this, "groupName", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: groupName\n });\n Object.defineProperty(this, "options", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: options\n });\n Object.defineProperty(this, "runManager", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n async getTraceGroupCallbackManager(group_name, inputs, options) {\n const cb = new _tracers_tracer_langchain_js__WEBPACK_IMPORTED_MODULE_5__.LangChainTracer(options);\n const cm = await CallbackManager.configure([cb]);\n const runManager = await cm?.handleChainStart({\n lc: 1,\n type: "not_implemented",\n id: ["langchain", "callbacks", "groups", group_name],\n }, inputs ?? {});\n if (!runManager) {\n throw new Error("Failed to create run group callback manager.");\n }\n return runManager;\n }\n async start(inputs) {\n if (!this.runManager) {\n this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options);\n }\n return this.runManager.getChild();\n }\n async error(err) {\n if (this.runManager) {\n await this.runManager.handleChainError(err);\n this.runManager = undefined;\n }\n }\n async end(output) {\n if (this.runManager) {\n await this.runManager.handleChainEnd(output ?? {});\n this.runManager = undefined;\n }\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _coerceToDict(value, defaultKey) {\n return value && !Array.isArray(value) && typeof value === "object"\n ? value\n : { [defaultKey]: value };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function traceAsGroup(groupOptions, enclosedCode, ...args) {\n const traceGroup = new TraceGroup(groupOptions.name, groupOptions);\n const callbackManager = await traceGroup.start({ ...args });\n try {\n const result = await enclosedCode(callbackManager, ...args);\n await traceGroup.end(_coerceToDict(result, "output"));\n return result;\n }\n catch (err) {\n await traceGroup.error(err);\n throw err;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/callbacks/manager.js?');
|
|
223
|
+
/***/
|
|
224
|
+
},
|
|
225
|
+
/***/ "./node_modules/@langchain/core/dist/callbacks/promises.js":
|
|
226
|
+
/*!*****************************************************************!*\
|
|
227
|
+
!*** ./node_modules/@langchain/core/dist/callbacks/promises.js ***!
|
|
228
|
+
\*****************************************************************/
|
|
229
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
230
|
+
"use strict";
|
|
231
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ awaitAllCallbacks: () => (/* binding */ awaitAllCallbacks),\n/* harmony export */ consumeCallback: () => (/* binding */ consumeCallback)\n/* harmony export */ });\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-queue */ "./node_modules/p-queue/dist/index.js");\n\nlet queue;\n/**\n * Creates a queue using the p-queue library. The queue is configured to\n * auto-start and has a concurrency of 1, meaning it will process tasks\n * one at a time.\n */\nfunction createQueue() {\n const PQueue = true ? p_queue__WEBPACK_IMPORTED_MODULE_0__["default"] : p_queue__WEBPACK_IMPORTED_MODULE_0__;\n return new PQueue({\n autoStart: true,\n concurrency: 1,\n });\n}\n/**\n * Consume a promise, either adding it to the queue or waiting for it to resolve\n * @param promiseFn Promise to consume\n * @param wait Whether to wait for the promise to resolve or resolve immediately\n */\nasync function consumeCallback(promiseFn, wait) {\n if (wait === true) {\n await promiseFn();\n }\n else {\n if (typeof queue === "undefined") {\n queue = createQueue();\n }\n void queue.add(promiseFn);\n }\n}\n/**\n * Waits for all promises in the queue to resolve. If the queue is\n * undefined, it immediately resolves a promise.\n */\nfunction awaitAllCallbacks() {\n return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve();\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/callbacks/promises.js?');
|
|
232
|
+
/***/
|
|
233
|
+
},
|
|
234
|
+
/***/ "./node_modules/@langchain/core/dist/language_models/base.js":
|
|
235
|
+
/*!*******************************************************************!*\
|
|
236
|
+
!*** ./node_modules/@langchain/core/dist/language_models/base.js ***!
|
|
237
|
+
\*******************************************************************/
|
|
238
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
239
|
+
"use strict";
|
|
240
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseLangChain: () => (/* binding */ BaseLangChain),\n/* harmony export */ BaseLanguageModel: () => (/* binding */ BaseLanguageModel),\n/* harmony export */ calculateMaxTokens: () => (/* binding */ calculateMaxTokens),\n/* harmony export */ getEmbeddingContextSize: () => (/* binding */ getEmbeddingContextSize),\n/* harmony export */ getModelContextSize: () => (/* binding */ getModelContextSize),\n/* harmony export */ getModelNameForTiktoken: () => (/* binding */ getModelNameForTiktoken),\n/* harmony export */ isOpenAITool: () => (/* binding */ isOpenAITool)\n/* harmony export */ });\n/* harmony import */ var _caches_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../caches.js */ "./node_modules/@langchain/core/dist/caches.js");\n/* harmony import */ var _prompt_values_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../prompt_values.js */ "./node_modules/@langchain/core/dist/prompt_values.js");\n/* harmony import */ var _messages_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../messages/utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n/* harmony import */ var _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/async_caller.js */ "./node_modules/@langchain/core/dist/utils/async_caller.js");\n/* harmony import */ var _utils_tiktoken_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/tiktoken.js */ "./node_modules/@langchain/core/dist/utils/tiktoken.js");\n/* harmony import */ var _runnables_base_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../runnables/base.js */ "./node_modules/@langchain/core/dist/runnables/base.js");\n\n\n\n\n\n\n// https://www.npmjs.com/package/js-tiktoken\nconst getModelNameForTiktoken = (modelName) => {\n if (modelName.startsWith("gpt-3.5-turbo-16k")) {\n return "gpt-3.5-turbo-16k";\n }\n if (modelName.startsWith("gpt-3.5-turbo-")) {\n return "gpt-3.5-turbo";\n }\n if (modelName.startsWith("gpt-4-32k")) {\n return "gpt-4-32k";\n }\n if (modelName.startsWith("gpt-4-")) {\n return "gpt-4";\n }\n if (modelName.startsWith("gpt-4o")) {\n return "gpt-4o";\n }\n return modelName;\n};\nconst getEmbeddingContextSize = (modelName) => {\n switch (modelName) {\n case "text-embedding-ada-002":\n return 8191;\n default:\n return 2046;\n }\n};\nconst getModelContextSize = (modelName) => {\n switch (getModelNameForTiktoken(modelName)) {\n case "gpt-3.5-turbo-16k":\n return 16384;\n case "gpt-3.5-turbo":\n return 4096;\n case "gpt-4-32k":\n return 32768;\n case "gpt-4":\n return 8192;\n case "text-davinci-003":\n return 4097;\n case "text-curie-001":\n return 2048;\n case "text-babbage-001":\n return 2048;\n case "text-ada-001":\n return 2048;\n case "code-davinci-002":\n return 8000;\n case "code-cushman-001":\n return 2048;\n default:\n return 4097;\n }\n};\n/**\n * Whether or not the input matches the OpenAI tool definition.\n * @param {unknown} tool The input to check.\n * @returns {boolean} Whether the input is an OpenAI tool definition.\n */\nfunction isOpenAITool(tool) {\n if (typeof tool !== "object" || !tool)\n return false;\n if ("type" in tool &&\n tool.type === "function" &&\n "function" in tool &&\n typeof tool.function === "object" &&\n tool.function &&\n "name" in tool.function &&\n "parameters" in tool.function) {\n return true;\n }\n return false;\n}\nconst calculateMaxTokens = async ({ prompt, modelName, }) => {\n let numTokens;\n try {\n numTokens = (await (0,_utils_tiktoken_js__WEBPACK_IMPORTED_MODULE_4__.encodingForModel)(getModelNameForTiktoken(modelName))).encode(prompt).length;\n }\n catch (error) {\n console.warn("Failed to calculate number of tokens, falling back to approximate count");\n // fallback to approximate calculation if tiktoken is not available\n // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them#\n numTokens = Math.ceil(prompt.length / 4);\n }\n const maxTokens = getModelContextSize(modelName);\n return maxTokens - numTokens;\n};\nconst getVerbosity = () => false;\n/**\n * Base class for language models, chains, tools.\n */\nclass BaseLangChain extends _runnables_base_js__WEBPACK_IMPORTED_MODULE_5__.Runnable {\n get lc_attributes() {\n return {\n callbacks: undefined,\n verbose: undefined,\n };\n }\n constructor(params) {\n super(params);\n /**\n * Whether to print out response text.\n */\n Object.defineProperty(this, "verbose", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "callbacks", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "tags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.verbose = params.verbose ?? getVerbosity();\n this.callbacks = params.callbacks;\n this.tags = params.tags ?? [];\n this.metadata = params.metadata ?? {};\n }\n}\n/**\n * Base class for language models.\n */\nclass BaseLanguageModel extends BaseLangChain {\n /**\n * Keys that the language model accepts as call options.\n */\n get callKeys() {\n return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"];\n }\n constructor({ callbacks, callbackManager, ...params }) {\n super({\n callbacks: callbacks ?? callbackManager,\n ...params,\n });\n /**\n * The async caller should be used by subclasses to make any async calls,\n * which will thus benefit from the concurrency and retry logic.\n */\n Object.defineProperty(this, "caller", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "cache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "_encoding", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (typeof params.cache === "object") {\n this.cache = params.cache;\n }\n else if (params.cache) {\n this.cache = _caches_js__WEBPACK_IMPORTED_MODULE_0__.InMemoryCache.global();\n }\n else {\n this.cache = undefined;\n }\n this.caller = new _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_3__.AsyncCaller(params ?? {});\n }\n async getNumTokens(content) {\n // TODO: Figure out correct value.\n if (typeof content !== "string") {\n return 0;\n }\n // fallback to approximate calculation if tiktoken is not available\n let numTokens = Math.ceil(content.length / 4);\n if (!this._encoding) {\n try {\n this._encoding = await (0,_utils_tiktoken_js__WEBPACK_IMPORTED_MODULE_4__.encodingForModel)("modelName" in this\n ? getModelNameForTiktoken(this.modelName)\n : "gpt2");\n }\n catch (error) {\n console.warn("Failed to calculate number of tokens, falling back to approximate count", error);\n }\n }\n if (this._encoding) {\n try {\n numTokens = this._encoding.encode(content).length;\n }\n catch (error) {\n console.warn("Failed to calculate number of tokens, falling back to approximate count", error);\n }\n }\n return numTokens;\n }\n static _convertInputToPromptValue(input) {\n if (typeof input === "string") {\n return new _prompt_values_js__WEBPACK_IMPORTED_MODULE_1__.StringPromptValue(input);\n }\n else if (Array.isArray(input)) {\n return new _prompt_values_js__WEBPACK_IMPORTED_MODULE_1__.ChatPromptValue(input.map(_messages_utils_js__WEBPACK_IMPORTED_MODULE_2__.coerceMessageLikeToMessage));\n }\n else {\n return input;\n }\n }\n /**\n * Get the identifying parameters of the LLM.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _identifyingParams() {\n return {};\n }\n /**\n * Create a unique cache key for a specific call to a specific language model.\n * @param callOptions Call options for the model\n * @returns A unique cache key.\n */\n _getSerializedCacheKeyParametersForCall(\n // TODO: Fix when we remove the RunnableLambda backwards compatibility shim.\n { config, ...callOptions }) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const params = {\n ...this._identifyingParams(),\n ...callOptions,\n _type: this._llmType(),\n _model: this._modelType(),\n };\n const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined);\n const serializedEntries = filteredEntries\n .map(([key, value]) => `${key}:${JSON.stringify(value)}`)\n .sort()\n .join(",");\n return serializedEntries;\n }\n /**\n * @deprecated\n * Return a json-like object representing this LLM.\n */\n serialize() {\n return {\n ...this._identifyingParams(),\n _type: this._llmType(),\n _model: this._modelType(),\n };\n }\n /**\n * @deprecated\n * Load an LLM from a json-like object describing it.\n */\n static async deserialize(_data) {\n throw new Error("Use .toJSON() instead");\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/language_models/base.js?');
|
|
241
|
+
/***/
|
|
242
|
+
},
|
|
243
|
+
/***/ "./node_modules/@langchain/core/dist/language_models/chat_models.js":
|
|
244
|
+
/*!**************************************************************************!*\
|
|
245
|
+
!*** ./node_modules/@langchain/core/dist/language_models/chat_models.js ***!
|
|
246
|
+
\**************************************************************************/
|
|
247
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
248
|
+
"use strict";
|
|
249
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseChatModel: () => (/* binding */ BaseChatModel),\n/* harmony export */ SimpleChatModel: () => (/* binding */ SimpleChatModel),\n/* harmony export */ createChatMessageChunkEncoderStream: () => (/* binding */ createChatMessageChunkEncoderStream)\n/* harmony export */ });\n/* harmony import */ var zod_to_json_schema__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! zod-to-json-schema */ "./node_modules/zod-to-json-schema/dist/esm/index.js");\n/* harmony import */ var _messages_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../messages/index.js */ "./node_modules/@langchain/core/dist/messages/index.js");\n/* harmony import */ var _outputs_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../outputs.js */ "./node_modules/@langchain/core/dist/outputs.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/language_models/base.js");\n/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../callbacks/manager.js */ "./node_modules/@langchain/core/dist/callbacks/manager.js");\n/* harmony import */ var _runnables_base_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../runnables/base.js */ "./node_modules/@langchain/core/dist/runnables/base.js");\n/* harmony import */ var _tracers_event_stream_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../tracers/event_stream.js */ "./node_modules/@langchain/core/dist/tracers/event_stream.js");\n/* harmony import */ var _tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../tracers/log_stream.js */ "./node_modules/@langchain/core/dist/tracers/log_stream.js");\n/* harmony import */ var _utils_stream_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n/* harmony import */ var _runnables_passthrough_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../runnables/passthrough.js */ "./node_modules/@langchain/core/dist/runnables/passthrough.js");\n/* harmony import */ var _utils_types_is_zod_schema_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/types/is_zod_schema.js */ "./node_modules/@langchain/core/dist/utils/types/is_zod_schema.js");\n\n\n\n\n\n\n\n\n\n\n\n/**\n * Creates a transform stream for encoding chat message chunks.\n * @deprecated Use {@link BytesOutputParser} instead\n * @returns A TransformStream instance that encodes chat message chunks.\n */\nfunction createChatMessageChunkEncoderStream() {\n const textEncoder = new TextEncoder();\n return new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(textEncoder.encode(typeof chunk.content === "string"\n ? chunk.content\n : JSON.stringify(chunk.content)));\n },\n });\n}\n/**\n * Base class for chat models. It extends the BaseLanguageModel class and\n * provides methods for generating chat based on input messages.\n */\nclass BaseChatModel extends _base_js__WEBPACK_IMPORTED_MODULE_3__.BaseLanguageModel {\n constructor(fields) {\n super(fields);\n // Only ever instantiated in main LangChain\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain", "chat_models", this._llmType()]\n });\n }\n _separateRunnableConfigFromCallOptions(options) {\n const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options);\n if (callOptions?.timeout && !callOptions.signal) {\n callOptions.signal = AbortSignal.timeout(callOptions.timeout);\n }\n return [runnableConfig, callOptions];\n }\n /**\n * Invokes the chat model with a single input.\n * @param input The input for the language model.\n * @param options The call options.\n * @returns A Promise that resolves to a BaseMessageChunk.\n */\n async invoke(input, options) {\n const promptValue = BaseChatModel._convertInputToPromptValue(input);\n const result = await this.generatePrompt([promptValue], options, options?.callbacks);\n const chatGeneration = result.generations[0][0];\n // TODO: Remove cast after figuring out inheritance\n return chatGeneration.message;\n }\n // eslint-disable-next-line require-yield\n async *_streamResponseChunks(_messages, _options, _runManager) {\n throw new Error("Not implemented.");\n }\n async *_streamIterator(input, options) {\n // Subclass check required to avoid double callbacks with default implementation\n if (this._streamResponseChunks ===\n BaseChatModel.prototype._streamResponseChunks) {\n yield this.invoke(input, options);\n }\n else {\n const prompt = BaseChatModel._convertInputToPromptValue(input);\n const messages = prompt.toChatMessages();\n const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options);\n const inheritableMetadata = {\n ...runnableConfig.metadata,\n ...this.getLsParams(callOptions),\n };\n const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_4__.CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });\n const extra = {\n options: callOptions,\n invocation_params: this?.invocationParams(callOptions),\n batch_size: 1,\n };\n const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [messages], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName);\n let generationChunk;\n try {\n for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) {\n chunk.message.response_metadata = {\n ...chunk.generationInfo,\n ...chunk.message.response_metadata,\n };\n yield chunk.message;\n if (!generationChunk) {\n generationChunk = chunk;\n }\n else {\n generationChunk = generationChunk.concat(chunk);\n }\n }\n }\n catch (err) {\n await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err)));\n throw err;\n }\n await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({\n // TODO: Remove cast after figuring out inheritance\n generations: [[generationChunk]],\n })));\n }\n }\n getLsParams(options) {\n return {\n ls_model_type: "chat",\n ls_stop: options.stop,\n };\n }\n /** @ignore */\n async _generateUncached(messages, parsedOptions, handledOptions) {\n const baseMessages = messages.map((messageList) => messageList.map(_messages_index_js__WEBPACK_IMPORTED_MODULE_1__.coerceMessageLikeToMessage));\n const inheritableMetadata = {\n ...handledOptions.metadata,\n ...this.getLsParams(parsedOptions),\n };\n // create callback manager and start run\n const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_4__.CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });\n const extra = {\n options: parsedOptions,\n invocation_params: this?.invocationParams(parsedOptions),\n batch_size: 1,\n };\n const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName);\n const generations = [];\n const llmOutputs = [];\n // Even if stream is not explicitly called, check if model is implicitly\n // called from streamEvents() or streamLog() to get all streamed events.\n // Bail out if _streamResponseChunks not overridden\n const hasStreamingHandler = !!runManagers?.[0].handlers.find((handler) => {\n return (0,_tracers_event_stream_js__WEBPACK_IMPORTED_MODULE_6__.isStreamEventsHandler)(handler) || (0,_tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_7__.isLogStreamHandler)(handler);\n });\n if (hasStreamingHandler &&\n baseMessages.length === 1 &&\n this._streamResponseChunks !==\n BaseChatModel.prototype._streamResponseChunks) {\n try {\n const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]);\n let aggregated;\n for await (const chunk of stream) {\n if (aggregated === undefined) {\n aggregated = chunk;\n }\n else {\n aggregated = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_8__.concat)(aggregated, chunk);\n }\n }\n if (aggregated === undefined) {\n throw new Error("Received empty response from chat model call.");\n }\n generations.push([aggregated]);\n await runManagers?.[0].handleLLMEnd({\n generations,\n llmOutput: {},\n });\n }\n catch (e) {\n await runManagers?.[0].handleLLMError(e);\n throw e;\n }\n }\n else {\n // generate results\n const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i])));\n // handle results\n await Promise.all(results.map(async (pResult, i) => {\n if (pResult.status === "fulfilled") {\n const result = pResult.value;\n for (const generation of result.generations) {\n generation.message.response_metadata = {\n ...generation.generationInfo,\n ...generation.message.response_metadata,\n };\n }\n if (result.generations.length === 1) {\n result.generations[0].message.response_metadata = {\n ...result.llmOutput,\n ...result.generations[0].message.response_metadata,\n };\n }\n generations[i] = result.generations;\n llmOutputs[i] = result.llmOutput;\n return runManagers?.[i]?.handleLLMEnd({\n generations: [result.generations],\n llmOutput: result.llmOutput,\n });\n }\n else {\n // status === "rejected"\n await runManagers?.[i]?.handleLLMError(pResult.reason);\n return Promise.reject(pResult.reason);\n }\n }));\n }\n // create combined output\n const output = {\n generations,\n llmOutput: llmOutputs.length\n ? this._combineLLMOutput?.(...llmOutputs)\n : undefined,\n };\n Object.defineProperty(output, _outputs_js__WEBPACK_IMPORTED_MODULE_2__.RUN_KEY, {\n value: runManagers\n ? { runIds: runManagers?.map((manager) => manager.runId) }\n : undefined,\n configurable: true,\n });\n return output;\n }\n async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }) {\n const baseMessages = messages.map((messageList) => messageList.map(_messages_index_js__WEBPACK_IMPORTED_MODULE_1__.coerceMessageLikeToMessage));\n const inheritableMetadata = {\n ...handledOptions.metadata,\n ...this.getLsParams(parsedOptions),\n };\n // create callback manager and start run\n const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_4__.CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose });\n const extra = {\n options: parsedOptions,\n invocation_params: this?.invocationParams(parsedOptions),\n batch_size: 1,\n cached: true,\n };\n const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName);\n // generate results\n const missingPromptIndices = [];\n const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => {\n // Join all content into one string for the prompt index\n const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString();\n const result = await cache.lookup(prompt, llmStringKey);\n if (result == null) {\n missingPromptIndices.push(index);\n }\n return result;\n }));\n // Map run managers to the results before filtering out null results\n // Null results are just absent from the cache.\n const cachedResults = results\n .map((result, index) => ({ result, runManager: runManagers?.[index] }))\n .filter(({ result }) => (result.status === "fulfilled" && result.value != null) ||\n result.status === "rejected");\n // Handle results and call run managers\n const generations = [];\n await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => {\n if (promiseResult.status === "fulfilled") {\n const result = promiseResult.value;\n generations[i] = result;\n if (result.length) {\n await runManager?.handleLLMNewToken(result[0].text);\n }\n return runManager?.handleLLMEnd({\n generations: [result],\n });\n }\n else {\n // status === "rejected"\n await runManager?.handleLLMError(promiseResult.reason);\n return Promise.reject(promiseResult.reason);\n }\n }));\n const output = {\n generations,\n missingPromptIndices,\n };\n // This defines RUN_KEY as a non-enumerable property on the output object\n // so that it is not serialized when the output is stringified, and so that\n // it isnt included when listing the keys of the output object.\n Object.defineProperty(output, _outputs_js__WEBPACK_IMPORTED_MODULE_2__.RUN_KEY, {\n value: runManagers\n ? { runIds: runManagers?.map((manager) => manager.runId) }\n : undefined,\n configurable: true,\n });\n return output;\n }\n /**\n * Generates chat based on the input messages.\n * @param messages An array of arrays of BaseMessage instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to an LLMResult.\n */\n async generate(messages, options, callbacks) {\n // parse call options\n let parsedOptions;\n if (Array.isArray(options)) {\n parsedOptions = { stop: options };\n }\n else {\n parsedOptions = options;\n }\n const baseMessages = messages.map((messageList) => messageList.map(_messages_index_js__WEBPACK_IMPORTED_MODULE_1__.coerceMessageLikeToMessage));\n const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions);\n runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks;\n if (!this.cache) {\n return this._generateUncached(baseMessages, callOptions, runnableConfig);\n }\n const { cache } = this;\n const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions);\n const { generations, missingPromptIndices } = await this._generateCached({\n messages: baseMessages,\n cache,\n llmStringKey,\n parsedOptions: callOptions,\n handledOptions: runnableConfig,\n });\n let llmOutput = {};\n if (missingPromptIndices.length > 0) {\n const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig);\n await Promise.all(results.generations.map(async (generation, index) => {\n const promptIndex = missingPromptIndices[index];\n generations[promptIndex] = generation;\n // Join all content into one string for the prompt index\n const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString();\n return cache.update(prompt, llmStringKey, generation);\n }));\n llmOutput = results.llmOutput ?? {};\n }\n return { generations, llmOutput };\n }\n /**\n * Get the parameters used to invoke the model\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invocationParams(_options) {\n return {};\n }\n _modelType() {\n return "base_chat_model";\n }\n /**\n * @deprecated\n * Return a json-like object representing this LLM.\n */\n serialize() {\n return {\n ...this.invocationParams(),\n _type: this._llmType(),\n _model: this._modelType(),\n };\n }\n /**\n * Generates a prompt based on the input prompt values.\n * @param promptValues An array of BasePromptValue instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to an LLMResult.\n */\n async generatePrompt(promptValues, options, callbacks) {\n const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages());\n return this.generate(promptMessages, options, callbacks);\n }\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.2.0.\n *\n * Makes a single call to the chat model.\n * @param messages An array of BaseMessage instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to a BaseMessage.\n */\n async call(messages, options, callbacks) {\n const result = await this.generate([messages.map(_messages_index_js__WEBPACK_IMPORTED_MODULE_1__.coerceMessageLikeToMessage)], options, callbacks);\n const generations = result.generations;\n return generations[0][0].message;\n }\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.2.0.\n *\n * Makes a single call to the chat model with a prompt value.\n * @param promptValue The value of the prompt.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to a BaseMessage.\n */\n async callPrompt(promptValue, options, callbacks) {\n const promptMessages = promptValue.toChatMessages();\n return this.call(promptMessages, options, callbacks);\n }\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.2.0.\n *\n * Predicts the next message based on the input messages.\n * @param messages An array of BaseMessage instances.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to a BaseMessage.\n */\n async predictMessages(messages, options, callbacks) {\n return this.call(messages, options, callbacks);\n }\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.2.0.\n *\n * Predicts the next message based on a text input.\n * @param text The text input.\n * @param options The call options or an array of stop sequences.\n * @param callbacks The callbacks for the language model.\n * @returns A Promise that resolves to a string.\n */\n async predict(text, options, callbacks) {\n const message = new _messages_index_js__WEBPACK_IMPORTED_MODULE_1__.HumanMessage(text);\n const result = await this.call([message], options, callbacks);\n if (typeof result.content !== "string") {\n throw new Error("Cannot use predict when output is not a string.");\n }\n return result.content;\n }\n withStructuredOutput(outputSchema, config) {\n if (typeof this.bindTools !== "function") {\n throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const schema = outputSchema;\n const name = config?.name;\n const description = schema.description ?? "A function available to call.";\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n if (method === "jsonMode") {\n throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`);\n }\n let functionName = name ?? "extract";\n let tools;\n if ((0,_utils_types_is_zod_schema_js__WEBPACK_IMPORTED_MODULE_10__.isZodSchema)(schema)) {\n tools = [\n {\n type: "function",\n function: {\n name: functionName,\n description,\n parameters: (0,zod_to_json_schema__WEBPACK_IMPORTED_MODULE_0__.zodToJsonSchema)(schema),\n },\n },\n ];\n }\n else {\n if ("name" in schema) {\n functionName = schema.name;\n }\n tools = [\n {\n type: "function",\n function: {\n name: functionName,\n description,\n parameters: schema,\n },\n },\n ];\n }\n const llm = this.bindTools(tools);\n const outputParser = _runnables_base_js__WEBPACK_IMPORTED_MODULE_5__.RunnableLambda.from((input) => {\n if (!input.tool_calls || input.tool_calls.length === 0) {\n throw new Error("No tool calls found in the response.");\n }\n const toolCall = input.tool_calls.find((tc) => tc.name === functionName);\n if (!toolCall) {\n throw new Error(`No tool call found with name ${functionName}.`);\n }\n return toolCall.args;\n });\n if (!includeRaw) {\n return llm.pipe(outputParser).withConfig({\n runName: "StructuredOutput",\n });\n }\n const parserAssign = _runnables_passthrough_js__WEBPACK_IMPORTED_MODULE_9__.RunnablePassthrough.assign({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsed: (input, config) => outputParser.invoke(input.raw, config),\n });\n const parserNone = _runnables_passthrough_js__WEBPACK_IMPORTED_MODULE_9__.RunnablePassthrough.assign({\n parsed: () => null,\n });\n const parsedWithFallback = parserAssign.withFallbacks({\n fallbacks: [parserNone],\n });\n return _runnables_base_js__WEBPACK_IMPORTED_MODULE_5__.RunnableSequence.from([\n {\n raw: llm,\n },\n parsedWithFallback,\n ]).withConfig({\n runName: "StructuredOutputRunnable",\n });\n }\n}\n/**\n * An abstract class that extends BaseChatModel and provides a simple\n * implementation of _generate.\n */\nclass SimpleChatModel extends BaseChatModel {\n async _generate(messages, options, runManager) {\n const text = await this._call(messages, options, runManager);\n const message = new _messages_index_js__WEBPACK_IMPORTED_MODULE_1__.AIMessage(text);\n if (typeof message.content !== "string") {\n throw new Error("Cannot generate with a simple chat model when output is not a string.");\n }\n return {\n generations: [\n {\n text: message.content,\n message,\n },\n ],\n };\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/language_models/chat_models.js?');
|
|
250
|
+
/***/
|
|
251
|
+
},
|
|
252
|
+
/***/ "./node_modules/@langchain/core/dist/load/map_keys.js":
|
|
253
|
+
/*!************************************************************!*\
|
|
254
|
+
!*** ./node_modules/@langchain/core/dist/load/map_keys.js ***!
|
|
255
|
+
\************************************************************/
|
|
256
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
257
|
+
"use strict";
|
|
258
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ keyFromJson: () => (/* binding */ keyFromJson),\n/* harmony export */ keyToJson: () => (/* binding */ keyToJson),\n/* harmony export */ mapKeys: () => (/* binding */ mapKeys)\n/* harmony export */ });\n/* harmony import */ var decamelize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! decamelize */ "./node_modules/decamelize/index.js");\n/* harmony import */ var camelcase__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! camelcase */ "./node_modules/camelcase/index.js");\n\n\nfunction keyToJson(key, map) {\n return map?.[key] || decamelize__WEBPACK_IMPORTED_MODULE_0__(key);\n}\nfunction keyFromJson(key, map) {\n return map?.[key] || camelcase__WEBPACK_IMPORTED_MODULE_1__(key);\n}\nfunction mapKeys(fields, mapper, map) {\n const mapped = {};\n for (const key in fields) {\n if (Object.hasOwn(fields, key)) {\n mapped[mapper(key, map)] = fields[key];\n }\n }\n return mapped;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/load/map_keys.js?');
|
|
259
|
+
/***/
|
|
260
|
+
},
|
|
261
|
+
/***/ "./node_modules/@langchain/core/dist/load/serializable.js":
|
|
262
|
+
/*!****************************************************************!*\
|
|
263
|
+
!*** ./node_modules/@langchain/core/dist/load/serializable.js ***!
|
|
264
|
+
\****************************************************************/
|
|
265
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
266
|
+
"use strict";
|
|
267
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Serializable: () => (/* binding */ Serializable),\n/* harmony export */ get_lc_unique_name: () => (/* binding */ get_lc_unique_name)\n/* harmony export */ });\n/* harmony import */ var _map_keys_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./map_keys.js */ "./node_modules/@langchain/core/dist/load/map_keys.js");\n\nfunction shallowCopy(obj) {\n return Array.isArray(obj) ? [...obj] : { ...obj };\n}\nfunction replaceSecrets(root, secretsMap) {\n const result = shallowCopy(root);\n for (const [path, secretId] of Object.entries(secretsMap)) {\n const [last, ...partsReverse] = path.split(".").reverse();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let current = result;\n for (const part of partsReverse.reverse()) {\n if (current[part] === undefined) {\n break;\n }\n current[part] = shallowCopy(current[part]);\n current = current[part];\n }\n if (current[last] !== undefined) {\n current[last] = {\n lc: 1,\n type: "secret",\n id: [secretId],\n };\n }\n }\n return result;\n}\n/**\n * Get a unique name for the module, rather than parent class implementations.\n * Should not be subclassed, subclass lc_name above instead.\n */\nfunction get_lc_unique_name(\n// eslint-disable-next-line @typescript-eslint/no-use-before-define\nserializableClass) {\n // "super" here would refer to the parent class of Serializable,\n // when we want the parent class of the module actually calling this method.\n const parentClass = Object.getPrototypeOf(serializableClass);\n const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" &&\n (typeof parentClass.lc_name !== "function" ||\n serializableClass.lc_name() !== parentClass.lc_name());\n if (lcNameIsSubclassed) {\n return serializableClass.lc_name();\n }\n else {\n return serializableClass.name;\n }\n}\nclass Serializable {\n /**\n * The name of the serializable. Override to provide an alias or\n * to preserve the serialized module name in minified environments.\n *\n * Implemented as a static method to support loading logic.\n */\n static lc_name() {\n return this.name;\n }\n /**\n * The final serialized identifier for the module.\n */\n get lc_id() {\n return [\n ...this.lc_namespace,\n get_lc_unique_name(this.constructor),\n ];\n }\n /**\n * A map of secrets, which will be omitted from serialization.\n * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz".\n * Values are the secret ids, which will be used when deserializing.\n */\n get lc_secrets() {\n return undefined;\n }\n /**\n * A map of additional attributes to merge with constructor args.\n * Keys are the attribute names, e.g. "foo".\n * Values are the attribute values, which will be serialized.\n * These attributes need to be accepted by the constructor as arguments.\n */\n get lc_attributes() {\n return undefined;\n }\n /**\n * A map of aliases for constructor args.\n * Keys are the attribute names, e.g. "foo".\n * Values are the alias that will replace the key in serialization.\n * This is used to eg. make argument names match Python.\n */\n get lc_aliases() {\n return undefined;\n }\n constructor(kwargs, ..._args) {\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "lc_kwargs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.lc_kwargs = kwargs || {};\n }\n toJSON() {\n if (!this.lc_serializable) {\n return this.toJSONNotImplemented();\n }\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n this.lc_kwargs instanceof Serializable ||\n typeof this.lc_kwargs !== "object" ||\n Array.isArray(this.lc_kwargs)) {\n // We do not support serialization of classes with arg not a POJO\n // I\'m aware the check above isn\'t as strict as it could be\n return this.toJSONNotImplemented();\n }\n const aliases = {};\n const secrets = {};\n const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => {\n acc[key] = key in this ? this[key] : this.lc_kwargs[key];\n return acc;\n }, {});\n // get secrets, attributes and aliases from all superclasses\n for (\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) {\n Object.assign(aliases, Reflect.get(current, "lc_aliases", this));\n Object.assign(secrets, Reflect.get(current, "lc_secrets", this));\n Object.assign(kwargs, Reflect.get(current, "lc_attributes", this));\n }\n // include all secrets used, even if not in kwargs,\n // will be replaced with sentinel value in replaceSecrets\n Object.keys(secrets).forEach((keyPath) => {\n // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any\n let read = this;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let write = kwargs;\n const [last, ...partsReverse] = keyPath.split(".").reverse();\n for (const key of partsReverse.reverse()) {\n if (!(key in read) || read[key] === undefined)\n return;\n if (!(key in write) || write[key] === undefined) {\n if (typeof read[key] === "object" && read[key] != null) {\n write[key] = {};\n }\n else if (Array.isArray(read[key])) {\n write[key] = [];\n }\n }\n read = read[key];\n write = write[key];\n }\n if (last in read && read[last] !== undefined) {\n write[last] = write[last] || read[last];\n }\n });\n return {\n lc: 1,\n type: "constructor",\n id: this.lc_id,\n kwargs: (0,_map_keys_js__WEBPACK_IMPORTED_MODULE_0__.mapKeys)(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, _map_keys_js__WEBPACK_IMPORTED_MODULE_0__.keyToJson, aliases),\n };\n }\n toJSONNotImplemented() {\n return {\n lc: 1,\n type: "not_implemented",\n id: this.lc_id,\n };\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/load/serializable.js?');
|
|
268
|
+
/***/
|
|
269
|
+
},
|
|
270
|
+
/***/ "./node_modules/@langchain/core/dist/messages/ai.js":
|
|
271
|
+
/*!**********************************************************!*\
|
|
272
|
+
!*** ./node_modules/@langchain/core/dist/messages/ai.js ***!
|
|
273
|
+
\**********************************************************/
|
|
274
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
275
|
+
"use strict";
|
|
276
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AIMessage: () => (/* binding */ AIMessage),\n/* harmony export */ AIMessageChunk: () => (/* binding */ AIMessageChunk),\n/* harmony export */ isAIMessage: () => (/* binding */ isAIMessage)\n/* harmony export */ });\n/* harmony import */ var _utils_json_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/json.js */ "./node_modules/@langchain/core/dist/utils/json.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n/* harmony import */ var _tool_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./tool.js */ "./node_modules/@langchain/core/dist/messages/tool.js");\n\n\n\n/**\n * Represents an AI message in a conversation.\n */\nclass AIMessage extends _base_js__WEBPACK_IMPORTED_MODULE_1__.BaseMessage {\n get lc_aliases() {\n // exclude snake case conversion to pascal case\n return {\n ...super.lc_aliases,\n tool_calls: "tool_calls",\n invalid_tool_calls: "invalid_tool_calls",\n };\n }\n constructor(fields, \n /** @deprecated */\n kwargs) {\n let initParams;\n if (typeof fields === "string") {\n initParams = {\n content: fields,\n tool_calls: [],\n invalid_tool_calls: [],\n additional_kwargs: kwargs ?? {},\n };\n }\n else {\n initParams = fields;\n const rawToolCalls = initParams.additional_kwargs?.tool_calls;\n const toolCalls = initParams.tool_calls;\n if (!(rawToolCalls == null) &&\n rawToolCalls.length > 0 &&\n (toolCalls === undefined || toolCalls.length === 0)) {\n console.warn([\n "New LangChain packages are available that more efficiently handle",\n "tool calling.\\n\\nPlease upgrade your packages to versions that set",\n "message tool calls. e.g., `yarn add @langchain/anthropic`,",\n "yarn add @langchain/openai`, etc.",\n ].join(" "));\n }\n try {\n if (!(rawToolCalls == null) && toolCalls === undefined) {\n const [toolCalls, invalidToolCalls] = (0,_tool_js__WEBPACK_IMPORTED_MODULE_2__.defaultToolCallParser)(rawToolCalls);\n initParams.tool_calls = toolCalls ?? [];\n initParams.invalid_tool_calls = invalidToolCalls ?? [];\n }\n else {\n initParams.tool_calls = initParams.tool_calls ?? [];\n initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? [];\n }\n }\n catch (e) {\n // Do nothing if parsing fails\n initParams.tool_calls = [];\n initParams.invalid_tool_calls = [];\n }\n }\n // Sadly, TypeScript only allows super() calls at root if the class has\n // properties with initializers, so we have to check types twice.\n super(initParams);\n // These are typed as optional to avoid breaking changes and allow for casting\n // from BaseMessage.\n Object.defineProperty(this, "tool_calls", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "invalid_tool_calls", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n /**\n * If provided, token usage information associated with the message.\n */\n Object.defineProperty(this, "usage_metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (typeof initParams !== "string") {\n this.tool_calls = initParams.tool_calls ?? this.tool_calls;\n this.invalid_tool_calls =\n initParams.invalid_tool_calls ?? this.invalid_tool_calls;\n }\n this.usage_metadata = initParams.usage_metadata;\n }\n static lc_name() {\n return "AIMessage";\n }\n _getType() {\n return "ai";\n }\n}\nfunction isAIMessage(x) {\n return x._getType() === "ai";\n}\n/**\n * Represents a chunk of an AI message, which can be concatenated with\n * other AI message chunks.\n */\nclass AIMessageChunk extends _base_js__WEBPACK_IMPORTED_MODULE_1__.BaseMessageChunk {\n constructor(fields) {\n let initParams;\n if (typeof fields === "string") {\n initParams = {\n content: fields,\n tool_calls: [],\n invalid_tool_calls: [],\n tool_call_chunks: [],\n };\n }\n else if (fields.tool_call_chunks === undefined) {\n initParams = {\n ...fields,\n tool_calls: fields.tool_calls ?? [],\n invalid_tool_calls: [],\n tool_call_chunks: [],\n };\n }\n else {\n const toolCalls = [];\n const invalidToolCalls = [];\n for (const toolCallChunk of fields.tool_call_chunks) {\n let parsedArgs = {};\n try {\n parsedArgs = (0,_utils_json_js__WEBPACK_IMPORTED_MODULE_0__.parsePartialJson)(toolCallChunk.args ?? "{}") ?? {};\n if (typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) {\n throw new Error("Malformed tool call chunk args.");\n }\n toolCalls.push({\n name: toolCallChunk.name ?? "",\n args: parsedArgs,\n id: toolCallChunk.id,\n });\n }\n catch (e) {\n invalidToolCalls.push({\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n id: toolCallChunk.id,\n error: "Malformed args.",\n });\n }\n }\n initParams = {\n ...fields,\n tool_calls: toolCalls,\n invalid_tool_calls: invalidToolCalls,\n };\n }\n // Sadly, TypeScript only allows super() calls at root if the class has\n // properties with initializers, so we have to check types twice.\n super(initParams);\n // Must redeclare tool call fields since there is no multiple inheritance in JS.\n // These are typed as optional to avoid breaking changes and allow for casting\n // from BaseMessage.\n Object.defineProperty(this, "tool_calls", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "invalid_tool_calls", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n Object.defineProperty(this, "tool_call_chunks", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n /**\n * If provided, token usage information associated with the message.\n */\n Object.defineProperty(this, "usage_metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.tool_call_chunks =\n initParams.tool_call_chunks ?? this.tool_call_chunks;\n this.tool_calls = initParams.tool_calls ?? this.tool_calls;\n this.invalid_tool_calls =\n initParams.invalid_tool_calls ?? this.invalid_tool_calls;\n this.usage_metadata = initParams.usage_metadata;\n }\n get lc_aliases() {\n // exclude snake case conversion to pascal case\n return {\n ...super.lc_aliases,\n tool_calls: "tool_calls",\n invalid_tool_calls: "invalid_tool_calls",\n tool_call_chunks: "tool_call_chunks",\n };\n }\n static lc_name() {\n return "AIMessageChunk";\n }\n _getType() {\n return "ai";\n }\n concat(chunk) {\n const combinedFields = {\n content: (0,_base_js__WEBPACK_IMPORTED_MODULE_1__.mergeContent)(this.content, chunk.content),\n additional_kwargs: (0,_base_js__WEBPACK_IMPORTED_MODULE_1__._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),\n response_metadata: (0,_base_js__WEBPACK_IMPORTED_MODULE_1__._mergeDicts)(this.response_metadata, chunk.response_metadata),\n tool_call_chunks: [],\n id: this.id ?? chunk.id,\n };\n if (this.tool_call_chunks !== undefined ||\n chunk.tool_call_chunks !== undefined) {\n const rawToolCalls = (0,_base_js__WEBPACK_IMPORTED_MODULE_1__._mergeLists)(this.tool_call_chunks, chunk.tool_call_chunks);\n if (rawToolCalls !== undefined && rawToolCalls.length > 0) {\n combinedFields.tool_call_chunks = rawToolCalls;\n }\n }\n if (this.usage_metadata !== undefined ||\n chunk.usage_metadata !== undefined) {\n const left = this.usage_metadata ?? {\n input_tokens: 0,\n output_tokens: 0,\n total_tokens: 0,\n };\n const right = chunk.usage_metadata ?? {\n input_tokens: 0,\n output_tokens: 0,\n total_tokens: 0,\n };\n const usage_metadata = {\n input_tokens: left.input_tokens + right.input_tokens,\n output_tokens: left.output_tokens + right.output_tokens,\n total_tokens: left.total_tokens + right.total_tokens,\n };\n combinedFields.usage_metadata = usage_metadata;\n }\n return new AIMessageChunk(combinedFields);\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/ai.js?');
|
|
277
|
+
/***/
|
|
278
|
+
},
|
|
279
|
+
/***/ "./node_modules/@langchain/core/dist/messages/base.js":
|
|
280
|
+
/*!************************************************************!*\
|
|
281
|
+
!*** ./node_modules/@langchain/core/dist/messages/base.js ***!
|
|
282
|
+
\************************************************************/
|
|
283
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
284
|
+
"use strict";
|
|
285
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseMessage: () => (/* binding */ BaseMessage),\n/* harmony export */ BaseMessageChunk: () => (/* binding */ BaseMessageChunk),\n/* harmony export */ _mergeDicts: () => (/* binding */ _mergeDicts),\n/* harmony export */ _mergeLists: () => (/* binding */ _mergeLists),\n/* harmony export */ isBaseMessage: () => (/* binding */ isBaseMessage),\n/* harmony export */ isBaseMessageChunk: () => (/* binding */ isBaseMessageChunk),\n/* harmony export */ isOpenAIToolCallArray: () => (/* binding */ isOpenAIToolCallArray),\n/* harmony export */ mergeContent: () => (/* binding */ mergeContent)\n/* harmony export */ });\n/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../load/serializable.js */ "./node_modules/@langchain/core/dist/load/serializable.js");\n\nfunction mergeContent(firstContent, secondContent) {\n // If first content is a string\n if (typeof firstContent === "string") {\n if (typeof secondContent === "string") {\n return firstContent + secondContent;\n }\n else {\n return [{ type: "text", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n }\n else if (Array.isArray(secondContent)) {\n return [...firstContent, ...secondContent];\n // If the first content is a list and second is a string\n }\n else {\n // Otherwise, add the second content as a new element of the list\n return [...firstContent, { type: "text", text: secondContent }];\n }\n}\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nclass BaseMessage extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__.Serializable {\n get lc_aliases() {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: "additional_kwargs",\n response_metadata: "response_metadata",\n };\n }\n /**\n * @deprecated\n * Use {@link BaseMessage.content} instead.\n */\n get text() {\n return typeof this.content === "string" ? this.content : "";\n }\n constructor(fields, \n /** @deprecated */\n kwargs) {\n if (typeof fields === "string") {\n // eslint-disable-next-line no-param-reassign\n fields = {\n content: fields,\n additional_kwargs: kwargs,\n response_metadata: {},\n };\n }\n // Make sure the default value for additional_kwargs is passed into super() for serialization\n if (!fields.additional_kwargs) {\n // eslint-disable-next-line no-param-reassign\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n // eslint-disable-next-line no-param-reassign\n fields.response_metadata = {};\n }\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "messages"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n /** The content of the message. */\n Object.defineProperty(this, "content", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /** The name of the message sender in a multi-user chat. */\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /** Additional keyword arguments */\n Object.defineProperty(this, "additional_kwargs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /** Response metadata. For example: response headers, logprobs, token counts. */\n Object.defineProperty(this, "response_metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /**\n * An optional unique identifier for the message. This should ideally be\n * provided by the provider/model which created the message.\n */\n Object.defineProperty(this, "id", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = fields.name;\n this.content = fields.content;\n this.additional_kwargs = fields.additional_kwargs;\n this.response_metadata = fields.response_metadata;\n this.id = fields.id;\n }\n toDict() {\n return {\n type: this._getType(),\n data: this.toJSON()\n .kwargs,\n };\n }\n}\nfunction isOpenAIToolCallArray(value) {\n return (Array.isArray(value) &&\n value.every((v) => typeof v.index === "number"));\n}\nfunction _mergeDicts(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nleft, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nright\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n }\n else if (value == null) {\n continue;\n }\n else if (typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)) {\n throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);\n }\n else if (typeof merged[key] === "string") {\n merged[key] = merged[key] + value;\n }\n else if (!Array.isArray(merged[key]) && typeof merged[key] === "object") {\n merged[key] = _mergeDicts(merged[key], value);\n }\n else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value);\n }\n else if (merged[key] === value) {\n continue;\n }\n else {\n console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`);\n }\n }\n return merged;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _mergeLists(left, right) {\n if (left === undefined && right === undefined) {\n return undefined;\n }\n else if (left === undefined || right === undefined) {\n return left || right;\n }\n else {\n const merged = [...left];\n for (const item of right) {\n if (typeof item === "object" &&\n "index" in item &&\n typeof item.index === "number") {\n const toMerge = merged.findIndex((leftItem) => leftItem.index === item.index);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(merged[toMerge], item);\n }\n else {\n merged.push(item);\n }\n }\n else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nclass BaseMessageChunk extends BaseMessage {\n}\nfunction isBaseMessage(messageLike) {\n return typeof messageLike?._getType === "function";\n}\nfunction isBaseMessageChunk(messageLike) {\n return (isBaseMessage(messageLike) &&\n typeof messageLike.concat === "function");\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/base.js?');
|
|
286
|
+
/***/
|
|
287
|
+
},
|
|
288
|
+
/***/ "./node_modules/@langchain/core/dist/messages/chat.js":
|
|
289
|
+
/*!************************************************************!*\
|
|
290
|
+
!*** ./node_modules/@langchain/core/dist/messages/chat.js ***!
|
|
291
|
+
\************************************************************/
|
|
292
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
293
|
+
"use strict";
|
|
294
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ChatMessage: () => (/* binding */ ChatMessage),\n/* harmony export */ ChatMessageChunk: () => (/* binding */ ChatMessageChunk)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n\n/**\n * Represents a chat message in a conversation.\n */\nclass ChatMessage extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessage {\n static lc_name() {\n return "ChatMessage";\n }\n static _chatMessageClass() {\n return ChatMessage;\n }\n constructor(fields, role) {\n if (typeof fields === "string") {\n // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion\n fields = { content: fields, role: role };\n }\n super(fields);\n Object.defineProperty(this, "role", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.role = fields.role;\n }\n _getType() {\n return "generic";\n }\n static isInstance(message) {\n return message._getType() === "generic";\n }\n}\n/**\n * Represents a chunk of a chat message, which can be concatenated with\n * other chat message chunks.\n */\nclass ChatMessageChunk extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessageChunk {\n static lc_name() {\n return "ChatMessageChunk";\n }\n constructor(fields, role) {\n if (typeof fields === "string") {\n // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion\n fields = { content: fields, role: role };\n }\n super(fields);\n Object.defineProperty(this, "role", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.role = fields.role;\n }\n _getType() {\n return "generic";\n }\n concat(chunk) {\n return new ChatMessageChunk({\n content: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.mergeContent)(this.content, chunk.content),\n additional_kwargs: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),\n response_metadata: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.response_metadata, chunk.response_metadata),\n role: this.role,\n id: this.id ?? chunk.id,\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/chat.js?');
|
|
295
|
+
/***/
|
|
296
|
+
},
|
|
297
|
+
/***/ "./node_modules/@langchain/core/dist/messages/function.js":
|
|
298
|
+
/*!****************************************************************!*\
|
|
299
|
+
!*** ./node_modules/@langchain/core/dist/messages/function.js ***!
|
|
300
|
+
\****************************************************************/
|
|
301
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
302
|
+
"use strict";
|
|
303
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ FunctionMessage: () => (/* binding */ FunctionMessage),\n/* harmony export */ FunctionMessageChunk: () => (/* binding */ FunctionMessageChunk)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n\n/**\n * Represents a function message in a conversation.\n */\nclass FunctionMessage extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessage {\n static lc_name() {\n return "FunctionMessage";\n }\n constructor(fields, \n /** @deprecated */\n name) {\n if (typeof fields === "string") {\n // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion\n fields = { content: fields, name: name };\n }\n super(fields);\n }\n _getType() {\n return "function";\n }\n}\n/**\n * Represents a chunk of a function message, which can be concatenated\n * with other function message chunks.\n */\nclass FunctionMessageChunk extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessageChunk {\n static lc_name() {\n return "FunctionMessageChunk";\n }\n _getType() {\n return "function";\n }\n concat(chunk) {\n return new FunctionMessageChunk({\n content: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.mergeContent)(this.content, chunk.content),\n additional_kwargs: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),\n response_metadata: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.response_metadata, chunk.response_metadata),\n name: this.name ?? "",\n id: this.id ?? chunk.id,\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/function.js?');
|
|
304
|
+
/***/
|
|
305
|
+
},
|
|
306
|
+
/***/ "./node_modules/@langchain/core/dist/messages/human.js":
|
|
307
|
+
/*!*************************************************************!*\
|
|
308
|
+
!*** ./node_modules/@langchain/core/dist/messages/human.js ***!
|
|
309
|
+
\*************************************************************/
|
|
310
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
311
|
+
"use strict";
|
|
312
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ HumanMessage: () => (/* binding */ HumanMessage),\n/* harmony export */ HumanMessageChunk: () => (/* binding */ HumanMessageChunk)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n\n/**\n * Represents a human message in a conversation.\n */\nclass HumanMessage extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessage {\n static lc_name() {\n return "HumanMessage";\n }\n _getType() {\n return "human";\n }\n}\n/**\n * Represents a chunk of a human message, which can be concatenated with\n * other human message chunks.\n */\nclass HumanMessageChunk extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessageChunk {\n static lc_name() {\n return "HumanMessageChunk";\n }\n _getType() {\n return "human";\n }\n concat(chunk) {\n return new HumanMessageChunk({\n content: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.mergeContent)(this.content, chunk.content),\n additional_kwargs: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),\n response_metadata: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.response_metadata, chunk.response_metadata),\n id: this.id ?? chunk.id,\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/human.js?');
|
|
313
|
+
/***/
|
|
314
|
+
},
|
|
315
|
+
/***/ "./node_modules/@langchain/core/dist/messages/index.js":
|
|
316
|
+
/*!*************************************************************!*\
|
|
317
|
+
!*** ./node_modules/@langchain/core/dist/messages/index.js ***!
|
|
318
|
+
\*************************************************************/
|
|
319
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
320
|
+
"use strict";
|
|
321
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AIMessage: () => (/* reexport safe */ _ai_js__WEBPACK_IMPORTED_MODULE_0__.AIMessage),\n/* harmony export */ AIMessageChunk: () => (/* reexport safe */ _ai_js__WEBPACK_IMPORTED_MODULE_0__.AIMessageChunk),\n/* harmony export */ BaseMessage: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__.BaseMessage),\n/* harmony export */ BaseMessageChunk: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__.BaseMessageChunk),\n/* harmony export */ ChatMessage: () => (/* reexport safe */ _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessage),\n/* harmony export */ ChatMessageChunk: () => (/* reexport safe */ _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessageChunk),\n/* harmony export */ FunctionMessage: () => (/* reexport safe */ _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessage),\n/* harmony export */ FunctionMessageChunk: () => (/* reexport safe */ _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessageChunk),\n/* harmony export */ HumanMessage: () => (/* reexport safe */ _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessage),\n/* harmony export */ HumanMessageChunk: () => (/* reexport safe */ _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessageChunk),\n/* harmony export */ SystemMessage: () => (/* reexport safe */ _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessage),\n/* harmony export */ SystemMessageChunk: () => (/* reexport safe */ _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessageChunk),\n/* harmony export */ ToolMessage: () => (/* reexport safe */ _tool_js__WEBPACK_IMPORTED_MODULE_8__.ToolMessage),\n/* harmony export */ ToolMessageChunk: () => (/* reexport safe */ _tool_js__WEBPACK_IMPORTED_MODULE_8__.ToolMessageChunk),\n/* harmony export */ _mergeDicts: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__._mergeDicts),\n/* harmony export */ _mergeLists: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__._mergeLists),\n/* harmony export */ coerceMessageLikeToMessage: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.coerceMessageLikeToMessage),\n/* harmony export */ convertToChunk: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.convertToChunk),\n/* harmony export */ defaultTextSplitter: () => (/* reexport safe */ _transformers_js__WEBPACK_IMPORTED_MODULE_7__.defaultTextSplitter),\n/* harmony export */ filterMessages: () => (/* reexport safe */ _transformers_js__WEBPACK_IMPORTED_MODULE_7__.filterMessages),\n/* harmony export */ getBufferString: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.getBufferString),\n/* harmony export */ isAIMessage: () => (/* reexport safe */ _ai_js__WEBPACK_IMPORTED_MODULE_0__.isAIMessage),\n/* harmony export */ isBaseMessage: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__.isBaseMessage),\n/* harmony export */ isBaseMessageChunk: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__.isBaseMessageChunk),\n/* harmony export */ isOpenAIToolCallArray: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__.isOpenAIToolCallArray),\n/* harmony export */ mapChatMessagesToStoredMessages: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.mapChatMessagesToStoredMessages),\n/* harmony export */ mapStoredMessageToChatMessage: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.mapStoredMessageToChatMessage),\n/* harmony export */ mapStoredMessagesToChatMessages: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_6__.mapStoredMessagesToChatMessages),\n/* harmony export */ mergeContent: () => (/* reexport safe */ _base_js__WEBPACK_IMPORTED_MODULE_1__.mergeContent),\n/* harmony export */ mergeMessageRuns: () => (/* reexport safe */ _transformers_js__WEBPACK_IMPORTED_MODULE_7__.mergeMessageRuns),\n/* harmony export */ trimMessages: () => (/* reexport safe */ _transformers_js__WEBPACK_IMPORTED_MODULE_7__.trimMessages)\n/* harmony export */ });\n/* harmony import */ var _ai_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ai.js */ "./node_modules/@langchain/core/dist/messages/ai.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n/* harmony import */ var _chat_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./chat.js */ "./node_modules/@langchain/core/dist/messages/chat.js");\n/* harmony import */ var _function_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./function.js */ "./node_modules/@langchain/core/dist/messages/function.js");\n/* harmony import */ var _human_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./human.js */ "./node_modules/@langchain/core/dist/messages/human.js");\n/* harmony import */ var _system_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./system.js */ "./node_modules/@langchain/core/dist/messages/system.js");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n/* harmony import */ var _transformers_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./transformers.js */ "./node_modules/@langchain/core/dist/messages/transformers.js");\n/* harmony import */ var _tool_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./tool.js */ "./node_modules/@langchain/core/dist/messages/tool.js");\n\n\n\n\n\n\n\n\n// TODO: Use a star export when we deprecate the\n// existing "ToolCall" type in "base.js".\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/index.js?');
|
|
322
|
+
/***/
|
|
323
|
+
},
|
|
324
|
+
/***/ "./node_modules/@langchain/core/dist/messages/system.js":
|
|
325
|
+
/*!**************************************************************!*\
|
|
326
|
+
!*** ./node_modules/@langchain/core/dist/messages/system.js ***!
|
|
327
|
+
\**************************************************************/
|
|
328
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
329
|
+
"use strict";
|
|
330
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ SystemMessage: () => (/* binding */ SystemMessage),\n/* harmony export */ SystemMessageChunk: () => (/* binding */ SystemMessageChunk)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n\n/**\n * Represents a system message in a conversation.\n */\nclass SystemMessage extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessage {\n static lc_name() {\n return "SystemMessage";\n }\n _getType() {\n return "system";\n }\n}\n/**\n * Represents a chunk of a system message, which can be concatenated with\n * other system message chunks.\n */\nclass SystemMessageChunk extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessageChunk {\n static lc_name() {\n return "SystemMessageChunk";\n }\n _getType() {\n return "system";\n }\n concat(chunk) {\n return new SystemMessageChunk({\n content: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.mergeContent)(this.content, chunk.content),\n additional_kwargs: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),\n response_metadata: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.response_metadata, chunk.response_metadata),\n id: this.id ?? chunk.id,\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/system.js?');
|
|
331
|
+
/***/
|
|
332
|
+
},
|
|
333
|
+
/***/ "./node_modules/@langchain/core/dist/messages/tool.js":
|
|
334
|
+
/*!************************************************************!*\
|
|
335
|
+
!*** ./node_modules/@langchain/core/dist/messages/tool.js ***!
|
|
336
|
+
\************************************************************/
|
|
337
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
338
|
+
"use strict";
|
|
339
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ToolMessage: () => (/* binding */ ToolMessage),\n/* harmony export */ ToolMessageChunk: () => (/* binding */ ToolMessageChunk),\n/* harmony export */ defaultToolCallParser: () => (/* binding */ defaultToolCallParser)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n\n/**\n * Represents a tool message in a conversation.\n */\nclass ToolMessage extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessage {\n static lc_name() {\n return "ToolMessage";\n }\n get lc_aliases() {\n // exclude snake case conversion to pascal case\n return { tool_call_id: "tool_call_id" };\n }\n constructor(fields, tool_call_id, name) {\n if (typeof fields === "string") {\n // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion\n fields = { content: fields, name, tool_call_id: tool_call_id };\n }\n super(fields);\n Object.defineProperty(this, "tool_call_id", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.tool_call_id = fields.tool_call_id;\n }\n _getType() {\n return "tool";\n }\n static isInstance(message) {\n return message._getType() === "tool";\n }\n}\n/**\n * Represents a chunk of a tool message, which can be concatenated\n * with other tool message chunks.\n */\nclass ToolMessageChunk extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessageChunk {\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "tool_call_id", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.tool_call_id = fields.tool_call_id;\n }\n static lc_name() {\n return "ToolMessageChunk";\n }\n _getType() {\n return "tool";\n }\n concat(chunk) {\n return new ToolMessageChunk({\n content: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.mergeContent)(this.content, chunk.content),\n additional_kwargs: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.additional_kwargs, chunk.additional_kwargs),\n response_metadata: (0,_base_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts)(this.response_metadata, chunk.response_metadata),\n tool_call_id: this.tool_call_id,\n id: this.id ?? chunk.id,\n });\n }\n}\nfunction defaultToolCallParser(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nrawToolCalls) {\n const toolCalls = [];\n const invalidToolCalls = [];\n for (const toolCall of rawToolCalls) {\n if (!toolCall.function) {\n continue;\n }\n else {\n const functionName = toolCall.function.name;\n try {\n const functionArgs = JSON.parse(toolCall.function.arguments);\n const parsed = {\n name: functionName || "",\n args: functionArgs || {},\n id: toolCall.id,\n };\n toolCalls.push(parsed);\n }\n catch (error) {\n invalidToolCalls.push({\n name: functionName,\n args: toolCall.function.arguments,\n id: toolCall.id,\n error: "Malformed args.",\n });\n }\n }\n }\n return [toolCalls, invalidToolCalls];\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/tool.js?');
|
|
340
|
+
/***/
|
|
341
|
+
},
|
|
342
|
+
/***/ "./node_modules/@langchain/core/dist/messages/transformers.js":
|
|
343
|
+
/*!********************************************************************!*\
|
|
344
|
+
!*** ./node_modules/@langchain/core/dist/messages/transformers.js ***!
|
|
345
|
+
\********************************************************************/
|
|
346
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
347
|
+
"use strict";
|
|
348
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ defaultTextSplitter: () => (/* binding */ defaultTextSplitter),\n/* harmony export */ filterMessages: () => (/* binding */ filterMessages),\n/* harmony export */ mergeMessageRuns: () => (/* binding */ mergeMessageRuns),\n/* harmony export */ trimMessages: () => (/* binding */ trimMessages)\n/* harmony export */ });\n/* harmony import */ var _runnables_base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../runnables/base.js */ "./node_modules/@langchain/core/dist/runnables/base.js");\n/* harmony import */ var _ai_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ai.js */ "./node_modules/@langchain/core/dist/messages/ai.js");\n/* harmony import */ var _chat_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./chat.js */ "./node_modules/@langchain/core/dist/messages/chat.js");\n/* harmony import */ var _function_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./function.js */ "./node_modules/@langchain/core/dist/messages/function.js");\n/* harmony import */ var _human_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./human.js */ "./node_modules/@langchain/core/dist/messages/human.js");\n/* harmony import */ var _system_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./system.js */ "./node_modules/@langchain/core/dist/messages/system.js");\n/* harmony import */ var _tool_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./tool.js */ "./node_modules/@langchain/core/dist/messages/tool.js");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n\n\n\n\n\n\n\n\nconst _isMessageType = (msg, types) => {\n const typesAsStrings = [\n ...new Set(types?.map((t) => {\n if (typeof t === "string") {\n return t;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const instantiatedMsgClass = new t({});\n if (!("_getType" in instantiatedMsgClass) ||\n typeof instantiatedMsgClass._getType !== "function") {\n throw new Error("Invalid type provided.");\n }\n return instantiatedMsgClass._getType();\n })),\n ];\n const msgType = msg._getType();\n return typesAsStrings.some((t) => t === msgType);\n};\nfunction filterMessages(messagesOrOptions, options) {\n if (Array.isArray(messagesOrOptions)) {\n return _filterMessages(messagesOrOptions, options);\n }\n return _runnables_base_js__WEBPACK_IMPORTED_MODULE_0__.RunnableLambda.from((input) => {\n return _filterMessages(input, messagesOrOptions);\n });\n}\nfunction _filterMessages(messages, options = {}) {\n const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds, } = options;\n const filtered = [];\n for (const msg of messages) {\n if (excludeNames && msg.name && excludeNames.includes(msg.name)) {\n continue;\n }\n else if (excludeTypes && _isMessageType(msg, excludeTypes)) {\n continue;\n }\n else if (excludeIds && msg.id && excludeIds.includes(msg.id)) {\n continue;\n }\n // default to inclusion when no inclusion criteria given.\n if (!(includeTypes || includeIds || includeNames)) {\n filtered.push(msg);\n }\n else if (includeNames &&\n msg.name &&\n includeNames.some((iName) => iName === msg.name)) {\n filtered.push(msg);\n }\n else if (includeTypes && _isMessageType(msg, includeTypes)) {\n filtered.push(msg);\n }\n else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) {\n filtered.push(msg);\n }\n }\n return filtered;\n}\nfunction mergeMessageRuns(messages) {\n if (Array.isArray(messages)) {\n return _mergeMessageRuns(messages);\n }\n return _runnables_base_js__WEBPACK_IMPORTED_MODULE_0__.RunnableLambda.from(_mergeMessageRuns);\n}\nfunction _mergeMessageRuns(messages) {\n if (!messages.length) {\n return [];\n }\n const merged = [];\n for (const msg of messages) {\n const curr = msg; // Create a shallow copy of the message\n const last = merged.pop();\n if (!last) {\n merged.push(curr);\n }\n else if (curr._getType() === "tool" ||\n !(curr._getType() === last._getType())) {\n merged.push(last, curr);\n }\n else {\n const lastChunk = (0,_utils_js__WEBPACK_IMPORTED_MODULE_7__.convertToChunk)(last);\n const currChunk = (0,_utils_js__WEBPACK_IMPORTED_MODULE_7__.convertToChunk)(curr);\n const mergedChunks = lastChunk.concat(currChunk);\n if (typeof lastChunk.content === "string" &&\n typeof currChunk.content === "string") {\n mergedChunks.content = `${lastChunk.content}\\n${currChunk.content}`;\n }\n merged.push(_chunkToMsg(mergedChunks));\n }\n }\n return merged;\n}\nfunction trimMessages(messagesOrOptions, options) {\n if (Array.isArray(messagesOrOptions)) {\n const messages = messagesOrOptions;\n if (!options) {\n throw new Error("Options parameter is required when providing messages.");\n }\n return _trimMessagesHelper(messages, options);\n }\n else {\n const trimmerOptions = messagesOrOptions;\n return _runnables_base_js__WEBPACK_IMPORTED_MODULE_0__.RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions));\n }\n}\nasync function _trimMessagesHelper(messages, options) {\n const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter, } = options;\n if (startOn && strategy === "first") {\n throw new Error("`startOn` should only be specified if `strategy` is \'last\'.");\n }\n if (includeSystem && strategy === "first") {\n throw new Error("`includeSystem` should only be specified if `strategy` is \'last\'.");\n }\n let listTokenCounter;\n if ("getNumTokens" in tokenCounter) {\n listTokenCounter = async (msgs) => {\n const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content)));\n return tokenCounts.reduce((sum, count) => sum + count, 0);\n };\n }\n else {\n listTokenCounter = async (msgs) => tokenCounter(msgs);\n }\n let textSplitterFunc = defaultTextSplitter;\n if (textSplitter) {\n if ("splitText" in textSplitter) {\n textSplitterFunc = textSplitter.splitText;\n }\n else {\n textSplitterFunc = async (text) => textSplitter(text);\n }\n }\n if (strategy === "first") {\n return _firstMaxTokens(messages, {\n maxTokens,\n tokenCounter: listTokenCounter,\n textSplitter: textSplitterFunc,\n partialStrategy: allowPartial ? "first" : undefined,\n endOn,\n });\n }\n else if (strategy === "last") {\n return _lastMaxTokens(messages, {\n maxTokens,\n tokenCounter: listTokenCounter,\n textSplitter: textSplitterFunc,\n allowPartial,\n includeSystem,\n startOn,\n endOn,\n });\n }\n else {\n throw new Error(`Unrecognized strategy: \'${strategy}\'. Must be one of \'first\' or \'last\'.`);\n }\n}\nasync function _firstMaxTokens(messages, options) {\n const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options;\n let messagesCopy = [...messages];\n let idx = 0;\n for (let i = 0; i < messagesCopy.length; i += 1) {\n const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy;\n if ((await tokenCounter(remainingMessages)) <= maxTokens) {\n idx = messagesCopy.length - i;\n break;\n }\n }\n if (idx < messagesCopy.length - 1 && partialStrategy) {\n let includedPartial = false;\n if (Array.isArray(messagesCopy[idx].content)) {\n const excluded = messagesCopy[idx];\n if (typeof excluded.content === "string") {\n throw new Error("Expected content to be an array.");\n }\n const numBlock = excluded.content.length;\n const reversedContent = partialStrategy === "last"\n ? [...excluded.content].reverse()\n : excluded.content;\n for (let i = 1; i <= numBlock; i += 1) {\n const partialContent = partialStrategy === "first"\n ? reversedContent.slice(0, i)\n : reversedContent.slice(-i);\n const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_")));\n const updatedMessage = _switchTypeToMessage(excluded._getType(), {\n ...fields,\n content: partialContent,\n });\n const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage];\n if ((await tokenCounter(slicedMessages)) <= maxTokens) {\n messagesCopy = slicedMessages;\n idx += 1;\n includedPartial = true;\n }\n else {\n break;\n }\n }\n if (includedPartial && partialStrategy === "last") {\n excluded.content = [...reversedContent].reverse();\n }\n }\n if (!includedPartial) {\n const excluded = messagesCopy[idx];\n let text;\n if (Array.isArray(excluded.content) &&\n excluded.content.some((block) => typeof block === "string" || block.type === "text")) {\n const textBlock = excluded.content.find((block) => block.type === "text" && block.text);\n text = textBlock?.text;\n }\n else if (typeof excluded.content === "string") {\n text = excluded.content;\n }\n if (text) {\n const splitTexts = await textSplitter(text);\n const numSplits = splitTexts.length;\n if (partialStrategy === "last") {\n splitTexts.reverse();\n }\n for (let _ = 0; _ < numSplits - 1; _ += 1) {\n splitTexts.pop();\n excluded.content = splitTexts.join("");\n if ((await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <=\n maxTokens) {\n if (partialStrategy === "last") {\n excluded.content = [...splitTexts].reverse().join("");\n }\n messagesCopy = [...messagesCopy.slice(0, idx), excluded];\n idx += 1;\n break;\n }\n }\n }\n }\n }\n if (endOn) {\n const endOnArr = Array.isArray(endOn) ? endOn : [endOn];\n while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) {\n idx -= 1;\n }\n }\n return messagesCopy.slice(0, idx);\n}\nasync function _lastMaxTokens(messages, options) {\n const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options;\n if (endOn) {\n const endOnArr = Array.isArray(endOn) ? endOn : [endOn];\n while (messages &&\n !_isMessageType(messages[messages.length - 1], endOnArr)) {\n messages.pop();\n }\n }\n const swappedSystem = includeSystem && messages[0]._getType() === "system";\n let reversed_ = swappedSystem\n ? messages.slice(0, 1).concat(messages.slice(1).reverse())\n : messages.reverse();\n reversed_ = await _firstMaxTokens(reversed_, {\n ...rest,\n partialStrategy: allowPartial ? "last" : undefined,\n endOn: startOn,\n });\n if (swappedSystem) {\n return [reversed_[0], ...reversed_.slice(1).reverse()];\n }\n else {\n return reversed_.reverse();\n }\n}\nconst _MSG_CHUNK_MAP = {\n human: {\n message: _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessage,\n messageChunk: _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessageChunk,\n },\n ai: {\n message: _ai_js__WEBPACK_IMPORTED_MODULE_1__.AIMessage,\n messageChunk: _ai_js__WEBPACK_IMPORTED_MODULE_1__.AIMessageChunk,\n },\n system: {\n message: _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessage,\n messageChunk: _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessageChunk,\n },\n tool: {\n message: _tool_js__WEBPACK_IMPORTED_MODULE_6__.ToolMessage,\n messageChunk: _tool_js__WEBPACK_IMPORTED_MODULE_6__.ToolMessageChunk,\n },\n function: {\n message: _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessage,\n messageChunk: _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessageChunk,\n },\n generic: {\n message: _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessage,\n messageChunk: _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessageChunk,\n },\n};\nfunction _switchTypeToMessage(messageType, fields, returnChunk) {\n let chunk;\n let msg;\n switch (messageType) {\n case "human":\n if (returnChunk) {\n chunk = new _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessageChunk(fields);\n }\n else {\n msg = new _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessage(fields);\n }\n break;\n case "ai":\n if (returnChunk) {\n let aiChunkFields = {\n ...fields,\n };\n if ("tool_calls" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n chunk = new _ai_js__WEBPACK_IMPORTED_MODULE_1__.AIMessageChunk(aiChunkFields);\n }\n else {\n msg = new _ai_js__WEBPACK_IMPORTED_MODULE_1__.AIMessage(fields);\n }\n break;\n case "system":\n if (returnChunk) {\n chunk = new _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessageChunk(fields);\n }\n else {\n msg = new _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessage(fields);\n }\n break;\n case "tool":\n if ("tool_call_id" in fields) {\n if (returnChunk) {\n chunk = new _tool_js__WEBPACK_IMPORTED_MODULE_6__.ToolMessageChunk(fields);\n }\n else {\n msg = new _tool_js__WEBPACK_IMPORTED_MODULE_6__.ToolMessage(fields);\n }\n }\n else {\n throw new Error("Can not convert ToolMessage to ToolMessageChunk if \'tool_call_id\' field is not defined.");\n }\n break;\n case "function":\n if (returnChunk) {\n chunk = new _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessageChunk(fields);\n }\n else {\n if (!fields.name) {\n throw new Error("FunctionMessage must have a \'name\' field");\n }\n msg = new _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessage(fields);\n }\n break;\n case "generic":\n if ("role" in fields) {\n if (returnChunk) {\n chunk = new _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessageChunk(fields);\n }\n else {\n msg = new _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessage(fields);\n }\n }\n else {\n throw new Error("Can not convert ChatMessage to ChatMessageChunk if \'role\' field is not defined.");\n }\n break;\n default:\n throw new Error(`Unrecognized message type ${messageType}`);\n }\n if (returnChunk && chunk) {\n return chunk;\n }\n if (msg) {\n return msg;\n }\n throw new Error(`Unrecognized message type ${messageType}`);\n}\nfunction _chunkToMsg(chunk) {\n const chunkType = chunk._getType();\n let msg;\n const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_")));\n if (chunkType in _MSG_CHUNK_MAP) {\n msg = _switchTypeToMessage(chunkType, fields);\n }\n if (!msg) {\n throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`);\n }\n return msg;\n}\n/**\n * The default text splitter function that splits text by newlines.\n *\n * @param {string} text\n * @returns A promise that resolves to an array of strings split by newlines.\n */\nfunction defaultTextSplitter(text) {\n const splits = text.split("\\n");\n return Promise.resolve([\n ...splits.slice(0, -1).map((s) => `${s}\\n`),\n splits[splits.length - 1],\n ]);\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/transformers.js?');
|
|
349
|
+
/***/
|
|
350
|
+
},
|
|
351
|
+
/***/ "./node_modules/@langchain/core/dist/messages/utils.js":
|
|
352
|
+
/*!*************************************************************!*\
|
|
353
|
+
!*** ./node_modules/@langchain/core/dist/messages/utils.js ***!
|
|
354
|
+
\*************************************************************/
|
|
355
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
356
|
+
"use strict";
|
|
357
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ coerceMessageLikeToMessage: () => (/* binding */ coerceMessageLikeToMessage),\n/* harmony export */ convertToChunk: () => (/* binding */ convertToChunk),\n/* harmony export */ getBufferString: () => (/* binding */ getBufferString),\n/* harmony export */ mapChatMessagesToStoredMessages: () => (/* binding */ mapChatMessagesToStoredMessages),\n/* harmony export */ mapStoredMessageToChatMessage: () => (/* binding */ mapStoredMessageToChatMessage),\n/* harmony export */ mapStoredMessagesToChatMessages: () => (/* binding */ mapStoredMessagesToChatMessages)\n/* harmony export */ });\n/* harmony import */ var _ai_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ai.js */ "./node_modules/@langchain/core/dist/messages/ai.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/messages/base.js");\n/* harmony import */ var _chat_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./chat.js */ "./node_modules/@langchain/core/dist/messages/chat.js");\n/* harmony import */ var _function_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./function.js */ "./node_modules/@langchain/core/dist/messages/function.js");\n/* harmony import */ var _human_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./human.js */ "./node_modules/@langchain/core/dist/messages/human.js");\n/* harmony import */ var _system_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./system.js */ "./node_modules/@langchain/core/dist/messages/system.js");\n/* harmony import */ var _tool_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./tool.js */ "./node_modules/@langchain/core/dist/messages/tool.js");\n\n\n\n\n\n\n\nfunction coerceMessageLikeToMessage(messageLike) {\n if (typeof messageLike === "string") {\n return new _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessage(messageLike);\n }\n else if ((0,_base_js__WEBPACK_IMPORTED_MODULE_1__.isBaseMessage)(messageLike)) {\n return messageLike;\n }\n const [type, content] = messageLike;\n if (type === "human" || type === "user") {\n return new _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessage({ content });\n }\n else if (type === "ai" || type === "assistant") {\n return new _ai_js__WEBPACK_IMPORTED_MODULE_0__.AIMessage({ content });\n }\n else if (type === "system") {\n return new _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessage({ content });\n }\n else {\n throw new Error(`Unable to coerce message from array: only human, AI, or system message coercion is currently supported.`);\n }\n}\n/**\n * This function is used by memory classes to get a string representation\n * of the chat message history, based on the message content and role.\n */\nfunction getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") {\n const string_messages = [];\n for (const m of messages) {\n let role;\n if (m._getType() === "human") {\n role = humanPrefix;\n }\n else if (m._getType() === "ai") {\n role = aiPrefix;\n }\n else if (m._getType() === "system") {\n role = "System";\n }\n else if (m._getType() === "function") {\n role = "Function";\n }\n else if (m._getType() === "tool") {\n role = "Tool";\n }\n else if (m._getType() === "generic") {\n role = m.role;\n }\n else {\n throw new Error(`Got unsupported message type: ${m._getType()}`);\n }\n const nameStr = m.name ? `${m.name}, ` : "";\n string_messages.push(`${role}: ${nameStr}${m.content}`);\n }\n return string_messages.join("\\n");\n}\n/**\n * Maps messages from an older format (V1) to the current `StoredMessage`\n * format. If the message is already in the `StoredMessage` format, it is\n * returned as is. Otherwise, it transforms the V1 message into a\n * `StoredMessage`. This function is important for maintaining\n * compatibility with older message formats.\n */\nfunction mapV1MessageToStoredMessage(message) {\n // TODO: Remove this mapper when we deprecate the old message format.\n if (message.data !== undefined) {\n return message;\n }\n else {\n const v1Message = message;\n return {\n type: v1Message.type,\n data: {\n content: v1Message.text,\n role: v1Message.role,\n name: undefined,\n tool_call_id: undefined,\n },\n };\n }\n}\nfunction mapStoredMessageToChatMessage(message) {\n const storedMessage = mapV1MessageToStoredMessage(message);\n switch (storedMessage.type) {\n case "human":\n return new _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessage(storedMessage.data);\n case "ai":\n return new _ai_js__WEBPACK_IMPORTED_MODULE_0__.AIMessage(storedMessage.data);\n case "system":\n return new _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessage(storedMessage.data);\n case "function":\n if (storedMessage.data.name === undefined) {\n throw new Error("Name must be defined for function messages");\n }\n return new _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessage(storedMessage.data);\n case "tool":\n if (storedMessage.data.tool_call_id === undefined) {\n throw new Error("Tool call ID must be defined for tool messages");\n }\n return new _tool_js__WEBPACK_IMPORTED_MODULE_6__.ToolMessage(storedMessage.data);\n case "chat": {\n if (storedMessage.data.role === undefined) {\n throw new Error("Role must be defined for chat messages");\n }\n return new _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessage(storedMessage.data);\n }\n default:\n throw new Error(`Got unexpected type: ${storedMessage.type}`);\n }\n}\n/**\n * Transforms an array of `StoredMessage` instances into an array of\n * `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage`\n * function to ensure all messages are in the `StoredMessage` format, then\n * creates new instances of the appropriate `BaseMessage` subclass based\n * on the type of each message. This function is used to prepare stored\n * messages for use in a chat context.\n */\nfunction mapStoredMessagesToChatMessages(messages) {\n return messages.map(mapStoredMessageToChatMessage);\n}\n/**\n * Transforms an array of `BaseMessage` instances into an array of\n * `StoredMessage` instances. It does this by calling the `toDict` method\n * on each `BaseMessage`, which returns a `StoredMessage`. This function\n * is used to prepare chat messages for storage.\n */\nfunction mapChatMessagesToStoredMessages(messages) {\n return messages.map((message) => message.toDict());\n}\nfunction convertToChunk(message) {\n const type = message._getType();\n if (type === "human") {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new _human_js__WEBPACK_IMPORTED_MODULE_4__.HumanMessageChunk({ ...message });\n }\n else if (type === "ai") {\n let aiChunkFields = {\n ...message,\n };\n if ("tool_calls" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new _ai_js__WEBPACK_IMPORTED_MODULE_0__.AIMessageChunk({ ...aiChunkFields });\n }\n else if (type === "system") {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new _system_js__WEBPACK_IMPORTED_MODULE_5__.SystemMessageChunk({ ...message });\n }\n else if (type === "function") {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new _function_js__WEBPACK_IMPORTED_MODULE_3__.FunctionMessageChunk({ ...message });\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n }\n else if (_chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessage.isInstance(message)) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new _chat_js__WEBPACK_IMPORTED_MODULE_2__.ChatMessageChunk({ ...message });\n }\n else {\n throw new Error("Unknown message type.");\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/messages/utils.js?');
|
|
358
|
+
/***/
|
|
359
|
+
},
|
|
360
|
+
/***/ "./node_modules/@langchain/core/dist/outputs.js":
|
|
361
|
+
/*!******************************************************!*\
|
|
362
|
+
!*** ./node_modules/@langchain/core/dist/outputs.js ***!
|
|
363
|
+
\******************************************************/
|
|
364
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
365
|
+
"use strict";
|
|
366
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ChatGenerationChunk: () => (/* binding */ ChatGenerationChunk),\n/* harmony export */ GenerationChunk: () => (/* binding */ GenerationChunk),\n/* harmony export */ RUN_KEY: () => (/* binding */ RUN_KEY)\n/* harmony export */ });\nconst RUN_KEY = "__run";\n/**\n * Chunk of a single generation. Used for streaming.\n */\nclass GenerationChunk {\n constructor(fields) {\n Object.defineProperty(this, "text", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Object.defineProperty(this, "generationInfo", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.text = fields.text;\n this.generationInfo = fields.generationInfo;\n }\n concat(chunk) {\n return new GenerationChunk({\n text: this.text + chunk.text,\n generationInfo: {\n ...this.generationInfo,\n ...chunk.generationInfo,\n },\n });\n }\n}\nclass ChatGenerationChunk extends GenerationChunk {\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "message", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.message = fields.message;\n }\n concat(chunk) {\n return new ChatGenerationChunk({\n text: this.text + chunk.text,\n generationInfo: {\n ...this.generationInfo,\n ...chunk.generationInfo,\n },\n message: this.message.concat(chunk.message),\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/outputs.js?');
|
|
367
|
+
/***/
|
|
368
|
+
},
|
|
369
|
+
/***/ "./node_modules/@langchain/core/dist/prompt_values.js":
|
|
370
|
+
/*!************************************************************!*\
|
|
371
|
+
!*** ./node_modules/@langchain/core/dist/prompt_values.js ***!
|
|
372
|
+
\************************************************************/
|
|
373
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
374
|
+
"use strict";
|
|
375
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BasePromptValue: () => (/* binding */ BasePromptValue),\n/* harmony export */ ChatPromptValue: () => (/* binding */ ChatPromptValue),\n/* harmony export */ ImagePromptValue: () => (/* binding */ ImagePromptValue),\n/* harmony export */ StringPromptValue: () => (/* binding */ StringPromptValue)\n/* harmony export */ });\n/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./load/serializable.js */ "./node_modules/@langchain/core/dist/load/serializable.js");\n/* harmony import */ var _messages_human_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./messages/human.js */ "./node_modules/@langchain/core/dist/messages/human.js");\n/* harmony import */ var _messages_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./messages/utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n\n\n\n/**\n * Base PromptValue class. All prompt values should extend this class.\n */\nclass BasePromptValue extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__.Serializable {\n}\n/**\n * Represents a prompt value as a string. It extends the BasePromptValue\n * class and overrides the toString and toChatMessages methods.\n */\nclass StringPromptValue extends BasePromptValue {\n static lc_name() {\n return "StringPromptValue";\n }\n constructor(value) {\n super({ value });\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "prompt_values"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "value", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.value = value;\n }\n toString() {\n return this.value;\n }\n toChatMessages() {\n return [new _messages_human_js__WEBPACK_IMPORTED_MODULE_1__.HumanMessage(this.value)];\n }\n}\n/**\n * Class that represents a chat prompt value. It extends the\n * BasePromptValue and includes an array of BaseMessage instances.\n */\nclass ChatPromptValue extends BasePromptValue {\n static lc_name() {\n return "ChatPromptValue";\n }\n constructor(fields) {\n if (Array.isArray(fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { messages: fields };\n }\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "prompt_values"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "messages", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.messages = fields.messages;\n }\n toString() {\n return (0,_messages_utils_js__WEBPACK_IMPORTED_MODULE_2__.getBufferString)(this.messages);\n }\n toChatMessages() {\n return this.messages;\n }\n}\n/**\n * Class that represents an image prompt value. It extends the\n * BasePromptValue and includes an ImageURL instance.\n */\nclass ImagePromptValue extends BasePromptValue {\n static lc_name() {\n return "ImagePromptValue";\n }\n constructor(fields) {\n if (!("imageUrl" in fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { imageUrl: fields };\n }\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "prompt_values"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "imageUrl", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n /** @ignore */\n Object.defineProperty(this, "value", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.imageUrl = fields.imageUrl;\n }\n toString() {\n return this.imageUrl.url;\n }\n toChatMessages() {\n return [\n new _messages_human_js__WEBPACK_IMPORTED_MODULE_1__.HumanMessage({\n content: [\n {\n type: "image_url",\n image_url: {\n detail: this.imageUrl.detail,\n url: this.imageUrl.url,\n },\n },\n ],\n }),\n ];\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/prompt_values.js?');
|
|
376
|
+
/***/
|
|
377
|
+
},
|
|
378
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/base.js":
|
|
379
|
+
/*!*************************************************************!*\
|
|
380
|
+
!*** ./node_modules/@langchain/core/dist/runnables/base.js ***!
|
|
381
|
+
\*************************************************************/
|
|
382
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
383
|
+
"use strict";
|
|
384
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Runnable: () => (/* binding */ Runnable),\n/* harmony export */ RunnableAssign: () => (/* binding */ RunnableAssign),\n/* harmony export */ RunnableBinding: () => (/* binding */ RunnableBinding),\n/* harmony export */ RunnableEach: () => (/* binding */ RunnableEach),\n/* harmony export */ RunnableLambda: () => (/* binding */ RunnableLambda),\n/* harmony export */ RunnableMap: () => (/* binding */ RunnableMap),\n/* harmony export */ RunnableParallel: () => (/* binding */ RunnableParallel),\n/* harmony export */ RunnablePick: () => (/* binding */ RunnablePick),\n/* harmony export */ RunnableRetry: () => (/* binding */ RunnableRetry),\n/* harmony export */ RunnableSequence: () => (/* binding */ RunnableSequence),\n/* harmony export */ RunnableTraceable: () => (/* binding */ RunnableTraceable),\n/* harmony export */ RunnableWithFallbacks: () => (/* binding */ RunnableWithFallbacks),\n/* harmony export */ _coerceToDict: () => (/* binding */ _coerceToDict),\n/* harmony export */ _coerceToRunnable: () => (/* binding */ _coerceToRunnable)\n/* harmony export */ });\n/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! zod */ "./node_modules/zod/lib/index.mjs");\n/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-retry */ "./node_modules/p-retry/index.js");\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");\n/* harmony import */ var langsmith_singletons_traceable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! langsmith/singletons/traceable */ "./node_modules/langsmith/singletons/traceable.js");\n/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../callbacks/manager.js */ "./node_modules/@langchain/core/dist/callbacks/manager.js");\n/* harmony import */ var _tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tracers/log_stream.js */ "./node_modules/@langchain/core/dist/tracers/log_stream.js");\n/* harmony import */ var _tracers_event_stream_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../tracers/event_stream.js */ "./node_modules/@langchain/core/dist/tracers/event_stream.js");\n/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../load/serializable.js */ "./node_modules/@langchain/core/dist/load/serializable.js");\n/* harmony import */ var _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./config.js */ "./node_modules/@langchain/core/dist/runnables/config.js");\n/* harmony import */ var _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/async_caller.js */ "./node_modules/@langchain/core/dist/utils/async_caller.js");\n/* harmony import */ var _tracers_root_listener_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../tracers/root_listener.js */ "./node_modules/@langchain/core/dist/tracers/root_listener.js");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@langchain/core/dist/runnables/utils.js");\n/* harmony import */ var _singletons_index_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../singletons/index.js */ "./node_modules/@langchain/core/dist/singletons/index.js");\n/* harmony import */ var _graph_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./graph.js */ "./node_modules/@langchain/core/dist/runnables/graph.js");\n/* harmony import */ var _wrappers_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./wrappers.js */ "./node_modules/@langchain/core/dist/runnables/wrappers.js");\n/* harmony import */ var _iter_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./iter.js */ "./node_modules/@langchain/core/dist/runnables/iter.js");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _coerceToDict(value, defaultKey) {\n return value &&\n !Array.isArray(value) &&\n // eslint-disable-next-line no-instanceof/no-instanceof\n !(value instanceof Date) &&\n typeof value === "object"\n ? value\n : { [defaultKey]: value };\n}\n/**\n * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or\n * transformed.\n */\nclass Runnable extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_5__.Serializable {\n constructor() {\n super(...arguments);\n Object.defineProperty(this, "lc_runnable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n getName(suffix) {\n const name = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.name ?? this.constructor.lc_name() ?? this.constructor.name;\n return suffix ? `${name}${suffix}` : name;\n }\n /**\n * Bind arguments to a Runnable, returning a new Runnable.\n * @param kwargs\n * @returns A new RunnableBinding that, when invoked, will apply the bound args.\n */\n bind(kwargs) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableBinding({ bound: this, kwargs, config: {} });\n }\n /**\n * Return a new Runnable that maps a list of inputs to a list of outputs,\n * by calling invoke() with each input.\n */\n map() {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableEach({ bound: this });\n }\n /**\n * Add retry logic to an existing runnable.\n * @param kwargs\n * @returns A new RunnableRetry that, when invoked, will retry according to the parameters.\n */\n withRetry(fields) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableRetry({\n bound: this,\n kwargs: {},\n config: {},\n maxAttemptNumber: fields?.stopAfterAttempt,\n ...fields,\n });\n }\n /**\n * Bind config to a Runnable, returning a new Runnable.\n * @param config New configuration parameters to attach to the new runnable.\n * @returns A new RunnableBinding with a config matching what\'s passed.\n */\n withConfig(config) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableBinding({\n bound: this,\n config,\n kwargs: {},\n });\n }\n /**\n * Create a new runnable from the current one that will try invoking\n * other passed fallback runnables if the initial invocation fails.\n * @param fields.fallbacks Other runnables to call if the runnable errors.\n * @returns A new RunnableWithFallbacks.\n */\n withFallbacks(fields) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableWithFallbacks({\n runnable: this,\n fallbacks: fields.fallbacks,\n });\n }\n _getOptionsList(options, length = 0) {\n if (Array.isArray(options) && options.length !== length) {\n throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`);\n }\n if (Array.isArray(options)) {\n return options.map(_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig);\n }\n if (length > 1 && !Array.isArray(options) && options.runId) {\n console.warn("Provided runId will be used only for the first element of the batch.");\n const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId"));\n return Array.from({ length }, (_, i) => (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(i === 0 ? options : subsequent));\n }\n return Array.from({ length }, () => (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options));\n }\n async batch(inputs, options, batchOptions) {\n const configList = this._getOptionsList(options ?? {}, inputs.length);\n const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency;\n const caller = new _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_8__.AsyncCaller({\n maxConcurrency,\n onFailedAttempt: (e) => {\n throw e;\n },\n });\n const batchCalls = inputs.map((input, i) => caller.call(async () => {\n try {\n const result = await this.invoke(input, configList[i]);\n return result;\n }\n catch (e) {\n if (batchOptions?.returnExceptions) {\n return e;\n }\n throw e;\n }\n }));\n return Promise.all(batchCalls);\n }\n /**\n * Default streaming implementation.\n * Subclasses should override this method if they support streaming output.\n * @param input\n * @param options\n */\n async *_streamIterator(input, options) {\n yield this.invoke(input, options);\n }\n /**\n * Stream output in chunks.\n * @param input\n * @param options\n * @returns A readable stream that is also an iterable.\n */\n async stream(input, options) {\n // Buffer the first streamed chunk to allow for initial errors\n // to surface immediately.\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const wrappedGenerator = new _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.AsyncGeneratorWithSetup({\n generator: this._streamIterator(input, config),\n config,\n });\n await wrappedGenerator.setup;\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n _separateRunnableConfigFromCallOptions(options) {\n let runnableConfig;\n if (options === undefined) {\n runnableConfig = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n }\n else {\n runnableConfig = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)({\n callbacks: options.callbacks,\n tags: options.tags,\n metadata: options.metadata,\n runName: options.runName,\n configurable: options.configurable,\n recursionLimit: options.recursionLimit,\n maxConcurrency: options.maxConcurrency,\n runId: options.runId,\n });\n }\n const callOptions = { ...options };\n delete callOptions.callbacks;\n delete callOptions.tags;\n delete callOptions.metadata;\n delete callOptions.runName;\n delete callOptions.configurable;\n delete callOptions.recursionLimit;\n delete callOptions.maxConcurrency;\n delete callOptions.runId;\n return [runnableConfig, callOptions];\n }\n async _callWithConfig(func, input, options) {\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const callbackManager_ = await (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig)(config);\n const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, config?.runType, undefined, undefined, config?.runName ?? this.getName());\n delete config.runId;\n let output;\n try {\n output = await func.call(this, input, config, runManager);\n }\n catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(output, "output"));\n return output;\n }\n /**\n * Internal method that handles batching and configuration for a runnable\n * It takes a function, input values, and optional configuration, and\n * returns a promise that resolves to the output values.\n * @param func The function to be executed for each input value.\n * @param input The input values to be processed.\n * @param config Optional configuration for the function execution.\n * @returns A promise that resolves to the output values.\n */\n async _batchWithConfig(func, inputs, options, batchOptions) {\n const optionsList = this._getOptionsList(options ?? {}, inputs.length);\n const callbackManagers = await Promise.all(optionsList.map(_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig));\n const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {\n const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName());\n delete optionsList[i].runId;\n return handleStartRes;\n }));\n let outputs;\n try {\n outputs = await func.call(this, inputs, optionsList, runManagers, batchOptions);\n }\n catch (e) {\n await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));\n throw e;\n }\n await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output"))));\n return outputs;\n }\n /**\n * Helper method to transform an Iterator of Input values into an Iterator of\n * Output values, with callbacks.\n * Use this to implement `stream()` or `transform()` in Runnable subclasses.\n */\n async *_transformStreamWithConfig(inputGenerator, transformer, options) {\n let finalInput;\n let finalInputSupported = true;\n let finalOutput;\n let finalOutputSupported = true;\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const callbackManager_ = await (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig)(config);\n async function* wrapInputForTracing() {\n for await (const chunk of inputGenerator) {\n if (finalInputSupported) {\n if (finalInput === undefined) {\n finalInput = chunk;\n }\n else {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalInput = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalInput, chunk);\n }\n catch {\n finalInput = undefined;\n finalInputSupported = false;\n }\n }\n }\n yield chunk;\n }\n }\n let runManager;\n try {\n const pipe = await (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.pipeGeneratorWithSetup)(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), config);\n delete config.runId;\n runManager = pipe.setup;\n const streamEventsHandler = runManager?.handlers.find(_tracers_event_stream_js__WEBPACK_IMPORTED_MODULE_4__.isStreamEventsHandler);\n let iterator = pipe.output;\n if (streamEventsHandler !== undefined && runManager !== undefined) {\n iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator);\n }\n const streamLogHandler = runManager?.handlers.find(_tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_3__.isLogStreamHandler);\n if (streamLogHandler !== undefined && runManager !== undefined) {\n iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator);\n }\n for await (const chunk of iterator) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n }\n else {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalOutput, chunk);\n }\n catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n }\n catch (e) {\n await runManager?.handleChainError(e, undefined, undefined, undefined, {\n inputs: _coerceToDict(finalInput, "input"),\n });\n throw e;\n }\n await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") });\n }\n getGraph(_) {\n const graph = new _graph_js__WEBPACK_IMPORTED_MODULE_12__.Graph();\n // TODO: Add input schema for runnables\n const inputNode = graph.addNode({\n name: `${this.getName()}Input`,\n schema: zod__WEBPACK_IMPORTED_MODULE_15__.z.any(),\n });\n const runnableNode = graph.addNode(this);\n // TODO: Add output schemas for runnables\n const outputNode = graph.addNode({\n name: `${this.getName()}Output`,\n schema: zod__WEBPACK_IMPORTED_MODULE_15__.z.any(),\n });\n graph.addEdge(inputNode, runnableNode);\n graph.addEdge(runnableNode, outputNode);\n return graph;\n }\n /**\n * Create a new runnable sequence that runs each individual runnable in series,\n * piping the output of one runnable into another runnable or runnable-like.\n * @param coerceable A runnable, function, or object whose values are functions or runnables.\n * @returns A new runnable sequence.\n */\n pipe(coerceable) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableSequence({\n first: this,\n last: _coerceToRunnable(coerceable),\n });\n }\n /**\n * Pick keys from the dict output of this runnable. Returns a new runnable.\n */\n pick(keys) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return this.pipe(new RunnablePick(keys));\n }\n /**\n * Assigns new fields to the dict output of this runnable. Returns a new runnable.\n */\n assign(mapping) {\n return this.pipe(\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n new RunnableAssign(\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n new RunnableMap({ steps: mapping })));\n }\n /**\n * Default implementation of transform, which buffers input and then calls stream.\n * Subclasses should override this method if they can start producing output while\n * input is still being generated.\n * @param generator\n * @param options\n */\n async *transform(generator, options) {\n let finalChunk;\n for await (const chunk of generator) {\n if (finalChunk === undefined) {\n finalChunk = chunk;\n }\n else {\n // Make a best effort to gather, for any type that supports concat.\n // This method should throw an error if gathering fails.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalChunk = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalChunk, chunk);\n }\n }\n yield* this._streamIterator(finalChunk, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options));\n }\n /**\n * Stream all output from a runnable, as reported to the callback system.\n * This includes all inner runs of LLMs, Retrievers, Tools, etc.\n * Output is streamed as Log objects, which include a list of\n * jsonpatch ops that describe how the state of the run has changed in each\n * step, and the final state of the run.\n * The jsonpatch ops can be applied in order to construct state.\n * @param input\n * @param options\n * @param streamOptions\n */\n async *streamLog(input, options, streamOptions) {\n const logStreamCallbackHandler = new _tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_3__.LogStreamCallbackHandler({\n ...streamOptions,\n autoClose: false,\n _schemaFormat: "original",\n });\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n yield* this._streamLog(input, logStreamCallbackHandler, config);\n }\n async *_streamLog(input, logStreamCallbackHandler, config) {\n const { callbacks } = config;\n if (callbacks === undefined) {\n // eslint-disable-next-line no-param-reassign\n config.callbacks = [logStreamCallbackHandler];\n }\n else if (Array.isArray(callbacks)) {\n // eslint-disable-next-line no-param-reassign\n config.callbacks = callbacks.concat([logStreamCallbackHandler]);\n }\n else {\n const copiedCallbacks = callbacks.copy();\n copiedCallbacks.inheritableHandlers.push(logStreamCallbackHandler);\n // eslint-disable-next-line no-param-reassign\n config.callbacks = copiedCallbacks;\n }\n const runnableStreamPromise = this.stream(input, config);\n async function consumeRunnableStream() {\n try {\n const runnableStream = await runnableStreamPromise;\n for await (const chunk of runnableStream) {\n const patch = new _tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_3__.RunLogPatch({\n ops: [\n {\n op: "add",\n path: "/streamed_output/-",\n value: chunk,\n },\n ],\n });\n await logStreamCallbackHandler.writer.write(patch);\n }\n }\n finally {\n await logStreamCallbackHandler.writer.close();\n }\n }\n const runnableStreamConsumePromise = consumeRunnableStream();\n try {\n for await (const log of logStreamCallbackHandler) {\n yield log;\n }\n }\n finally {\n await runnableStreamConsumePromise;\n }\n }\n streamEvents(input, options, streamOptions) {\n let stream;\n if (options.version === "v1") {\n stream = this._streamEventsV1(input, options, streamOptions);\n }\n else if (options.version === "v2") {\n stream = this._streamEventsV2(input, options, streamOptions);\n }\n else {\n throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`);\n }\n if (options.encoding === "text/event-stream") {\n return (0,_wrappers_js__WEBPACK_IMPORTED_MODULE_13__.convertToHttpEventStream)(stream);\n }\n else {\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(stream);\n }\n }\n async *_streamEventsV2(input, options, streamOptions) {\n const eventStreamer = new _tracers_event_stream_js__WEBPACK_IMPORTED_MODULE_4__.EventStreamCallbackHandler({\n ...streamOptions,\n autoClose: false,\n });\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const runId = config.runId ?? (0,uuid__WEBPACK_IMPORTED_MODULE_16__["default"])();\n config.runId = runId;\n const callbacks = config.callbacks;\n if (callbacks === undefined) {\n config.callbacks = [eventStreamer];\n }\n else if (Array.isArray(callbacks)) {\n config.callbacks = callbacks.concat(eventStreamer);\n }\n else {\n const copiedCallbacks = callbacks.copy();\n copiedCallbacks.inheritableHandlers.push(eventStreamer);\n // eslint-disable-next-line no-param-reassign\n config.callbacks = copiedCallbacks;\n }\n // Call the runnable in streaming mode,\n // add each chunk to the output stream\n const outerThis = this;\n async function consumeRunnableStream() {\n try {\n const runnableStream = await outerThis.stream(input, config);\n const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for await (const _ of tappedStream) {\n // Just iterate so that the callback handler picks up events\n }\n }\n finally {\n await eventStreamer.finish();\n }\n }\n const runnableStreamConsumePromise = consumeRunnableStream();\n let firstEventSent = false;\n let firstEventRunId;\n try {\n for await (const event of eventStreamer) {\n // This is a work-around an issue where the inputs into the\n // chain are not available until the entire input is consumed.\n // As a temporary solution, we\'ll modify the input to be the input\n // that was passed into the chain.\n if (!firstEventSent) {\n event.data.input = input;\n firstEventSent = true;\n firstEventRunId = event.run_id;\n yield event;\n continue;\n }\n if (event.run_id === firstEventRunId && event.event.endsWith("_end")) {\n // If it\'s the end event corresponding to the root runnable\n // we dont include the input in the event since it\'s guaranteed\n // to be included in the first event.\n if (event.data?.input) {\n delete event.data.input;\n }\n }\n yield event;\n }\n }\n finally {\n await runnableStreamConsumePromise;\n }\n }\n async *_streamEventsV1(input, options, streamOptions) {\n let runLog;\n let hasEncounteredStartEvent = false;\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const rootTags = config.tags ?? [];\n const rootMetadata = config.metadata ?? {};\n const rootName = config.runName ?? this.getName();\n const logStreamCallbackHandler = new _tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_3__.LogStreamCallbackHandler({\n ...streamOptions,\n autoClose: false,\n _schemaFormat: "streaming_events",\n });\n const rootEventFilter = new _utils_js__WEBPACK_IMPORTED_MODULE_10__._RootEventFilter({\n ...streamOptions,\n });\n const logStream = this._streamLog(input, logStreamCallbackHandler, config);\n for await (const log of logStream) {\n if (!runLog) {\n runLog = _tracers_log_stream_js__WEBPACK_IMPORTED_MODULE_3__.RunLog.fromRunLogPatch(log);\n }\n else {\n runLog = runLog.concat(log);\n }\n if (runLog.state === undefined) {\n throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);\n }\n // Yield the start event for the root runnable if it hasn\'t been seen.\n // The root run is never filtered out\n if (!hasEncounteredStartEvent) {\n hasEncounteredStartEvent = true;\n const state = { ...runLog.state };\n const event = {\n run_id: state.id,\n event: `on_${state.type}_start`,\n name: rootName,\n tags: rootTags,\n metadata: rootMetadata,\n data: {\n input,\n },\n };\n if (rootEventFilter.includeEvent(event, state.type)) {\n yield event;\n }\n }\n const paths = log.ops\n .filter((op) => op.path.startsWith("/logs/"))\n .map((op) => op.path.split("/")[2]);\n const dedupedPaths = [...new Set(paths)];\n for (const path of dedupedPaths) {\n let eventType;\n let data = {};\n const logEntry = runLog.state.logs[path];\n if (logEntry.end_time === undefined) {\n if (logEntry.streamed_output.length > 0) {\n eventType = "stream";\n }\n else {\n eventType = "start";\n }\n }\n else {\n eventType = "end";\n }\n if (eventType === "start") {\n // Include the inputs with the start event if they are available.\n // Usually they will NOT be available for components that operate\n // on streams, since those components stream the input and\n // don\'t know its final value until the end of the stream.\n if (logEntry.inputs !== undefined) {\n data.input = logEntry.inputs;\n }\n }\n else if (eventType === "end") {\n if (logEntry.inputs !== undefined) {\n data.input = logEntry.inputs;\n }\n data.output = logEntry.final_output;\n }\n else if (eventType === "stream") {\n const chunkCount = logEntry.streamed_output.length;\n if (chunkCount !== 1) {\n throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`);\n }\n data = { chunk: logEntry.streamed_output[0] };\n // Clean up the stream, we don\'t need it anymore.\n // And this avoids duplicates as well!\n logEntry.streamed_output = [];\n }\n yield {\n event: `on_${logEntry.type}_${eventType}`,\n name: logEntry.name,\n run_id: logEntry.id,\n tags: logEntry.tags,\n metadata: logEntry.metadata,\n data,\n };\n }\n // Finally, we take care of the streaming output from the root chain\n // if there is any.\n const { state } = runLog;\n if (state.streamed_output.length > 0) {\n const chunkCount = state.streamed_output.length;\n if (chunkCount !== 1) {\n throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`);\n }\n const data = { chunk: state.streamed_output[0] };\n // Clean up the stream, we don\'t need it anymore.\n state.streamed_output = [];\n const event = {\n event: `on_${state.type}_stream`,\n run_id: state.id,\n tags: rootTags,\n metadata: rootMetadata,\n name: rootName,\n data,\n };\n if (rootEventFilter.includeEvent(event, state.type)) {\n yield event;\n }\n }\n }\n const state = runLog?.state;\n if (state !== undefined) {\n // Finally, yield the end event for the root runnable.\n const event = {\n event: `on_${state.type}_end`,\n name: rootName,\n run_id: state.id,\n tags: rootTags,\n metadata: rootMetadata,\n data: {\n output: state.final_output,\n },\n };\n if (rootEventFilter.includeEvent(event, state.type))\n yield event;\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static isRunnable(thing) {\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_10__.isRunnableInterface)(thing);\n }\n /**\n * Bind lifecycle listeners to a Runnable, returning a new Runnable.\n * The Run object contains information about the run, including its id,\n * type, input, output, error, startTime, endTime, and any tags or metadata\n * added to the run.\n *\n * @param {Object} params - The object containing the callback functions.\n * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n */\n withListeners({ onStart, onEnd, onError, }) {\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunnableBinding({\n bound: this,\n config: {},\n configFactories: [\n (config) => ({\n callbacks: [\n new _tracers_root_listener_js__WEBPACK_IMPORTED_MODULE_9__.RootListenersTracer({\n config,\n onStart,\n onEnd,\n onError,\n }),\n ],\n }),\n ],\n });\n }\n}\n/**\n * A runnable that delegates calls to another runnable with a set of kwargs.\n */\nclass RunnableBinding extends Runnable {\n static lc_name() {\n return "RunnableBinding";\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "bound", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "config", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "kwargs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "configFactories", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.bound = fields.bound;\n this.kwargs = fields.kwargs;\n this.config = fields.config;\n this.configFactories = fields.configFactories;\n }\n getName(suffix) {\n return this.bound.getName(suffix);\n }\n async _mergeConfig(...options) {\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.mergeConfigs)(this.config, ...options);\n return (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.mergeConfigs)(config, ...(this.configFactories\n ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config)))\n : []));\n }\n bind(kwargs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new this.constructor({\n bound: this.bound,\n kwargs: { ...this.kwargs, ...kwargs },\n config: this.config,\n });\n }\n withConfig(config) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new this.constructor({\n bound: this.bound,\n kwargs: this.kwargs,\n config: { ...this.config, ...config },\n });\n }\n withRetry(fields) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new this.constructor({\n bound: this.bound.withRetry(fields),\n kwargs: this.kwargs,\n config: this.config,\n });\n }\n async invoke(input, options) {\n return this.bound.invoke(input, await this._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options), this.kwargs));\n }\n async batch(inputs, options, batchOptions) {\n const mergedOptions = Array.isArray(options)\n ? await Promise.all(options.map(async (individualOption) => this._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(individualOption), this.kwargs)))\n : await this._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options), this.kwargs);\n return this.bound.batch(inputs, mergedOptions, batchOptions);\n }\n async *_streamIterator(input, options) {\n yield* this.bound._streamIterator(input, await this._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options), this.kwargs));\n }\n async stream(input, options) {\n return this.bound.stream(input, await this._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options), this.kwargs));\n }\n async *transform(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n generator, options) {\n yield* this.bound.transform(generator, await this._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options), this.kwargs));\n }\n streamEvents(input, options, streamOptions) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const outerThis = this;\n const generator = async function* () {\n yield* outerThis.bound.streamEvents(input, {\n ...(await outerThis._mergeConfig((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options), outerThis.kwargs)),\n version: options.version,\n }, streamOptions);\n };\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(generator());\n }\n static isRunnableBinding(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n thing\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) {\n return thing.bound && Runnable.isRunnable(thing.bound);\n }\n /**\n * Bind lifecycle listeners to a Runnable, returning a new Runnable.\n * The Run object contains information about the run, including its id,\n * type, input, output, error, startTime, endTime, and any tags or metadata\n * added to the run.\n *\n * @param {Object} params - The object containing the callback functions.\n * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n */\n withListeners({ onStart, onEnd, onError, }) {\n return new RunnableBinding({\n bound: this.bound,\n kwargs: this.kwargs,\n config: this.config,\n configFactories: [\n (config) => ({\n callbacks: [\n new _tracers_root_listener_js__WEBPACK_IMPORTED_MODULE_9__.RootListenersTracer({\n config,\n onStart,\n onEnd,\n onError,\n }),\n ],\n }),\n ],\n });\n }\n}\n/**\n * A runnable that delegates calls to another runnable\n * with each element of the input sequence.\n */\nclass RunnableEach extends Runnable {\n static lc_name() {\n return "RunnableEach";\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "bound", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.bound = fields.bound;\n }\n /**\n * Binds the runnable with the specified arguments.\n * @param kwargs The arguments to bind the runnable with.\n * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments.\n */\n bind(kwargs) {\n return new RunnableEach({\n bound: this.bound.bind(kwargs),\n });\n }\n /**\n * Invokes the runnable with the specified input and configuration.\n * @param input The input to invoke the runnable with.\n * @param config The configuration to invoke the runnable with.\n * @returns A promise that resolves to the output of the runnable.\n */\n async invoke(inputs, config) {\n return this._callWithConfig(this._invoke, inputs, config);\n }\n /**\n * A helper method that is used to invoke the runnable with the specified input and configuration.\n * @param input The input to invoke the runnable with.\n * @param config The configuration to invoke the runnable with.\n * @returns A promise that resolves to the output of the runnable.\n */\n async _invoke(inputs, config, runManager) {\n return this.bound.batch(inputs, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, { callbacks: runManager?.getChild() }));\n }\n /**\n * Bind lifecycle listeners to a Runnable, returning a new Runnable.\n * The Run object contains information about the run, including its id,\n * type, input, output, error, startTime, endTime, and any tags or metadata\n * added to the run.\n *\n * @param {Object} params - The object containing the callback functions.\n * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object.\n * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object.\n * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object.\n */\n withListeners({ onStart, onEnd, onError, }) {\n return new RunnableEach({\n bound: this.bound.withListeners({ onStart, onEnd, onError }),\n });\n }\n}\n/**\n * Base class for runnables that can be retried a\n * specified number of times.\n */\nclass RunnableRetry extends RunnableBinding {\n static lc_name() {\n return "RunnableRetry";\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "maxAttemptNumber", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 3\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Object.defineProperty(this, "onFailedAttempt", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: () => { }\n });\n this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber;\n this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt;\n }\n _patchConfigForRetry(attempt, config, runManager) {\n const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined;\n return (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, { callbacks: runManager?.getChild(tag) });\n }\n async _invoke(input, config, runManager) {\n return p_retry__WEBPACK_IMPORTED_MODULE_0__((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onFailedAttempt: (error) => this.onFailedAttempt(error, input),\n retries: Math.max(this.maxAttemptNumber - 1, 0),\n randomize: true,\n });\n }\n /**\n * Method that invokes the runnable with the specified input, run manager,\n * and config. It handles the retry logic by catching any errors and\n * recursively invoking itself with the updated config for the next retry\n * attempt.\n * @param input The input for the runnable.\n * @param runManager The run manager for the runnable.\n * @param config The config for the runnable.\n * @returns A promise that resolves to the output of the runnable.\n */\n async invoke(input, config) {\n return this._callWithConfig(this._invoke, input, config);\n }\n async _batch(inputs, configs, runManagers, batchOptions) {\n const resultsMap = {};\n try {\n await p_retry__WEBPACK_IMPORTED_MODULE_0__(async (attemptNumber) => {\n const remainingIndexes = inputs\n .map((_, i) => i)\n .filter((i) => resultsMap[i.toString()] === undefined ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n resultsMap[i.toString()] instanceof Error);\n const remainingInputs = remainingIndexes.map((i) => inputs[i]);\n const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));\n const results = await super.batch(remainingInputs, patchedConfigs, {\n ...batchOptions,\n returnExceptions: true,\n });\n let firstException;\n for (let i = 0; i < results.length; i += 1) {\n const result = results[i];\n const resultMapIndex = remainingIndexes[i];\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (result instanceof Error) {\n if (firstException === undefined) {\n firstException = result;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n firstException.input = remainingInputs[i];\n }\n }\n resultsMap[resultMapIndex.toString()] = result;\n }\n if (firstException) {\n throw firstException;\n }\n return results;\n }, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n onFailedAttempt: (error) => this.onFailedAttempt(error, error.input),\n retries: Math.max(this.maxAttemptNumber - 1, 0),\n randomize: true,\n });\n }\n catch (e) {\n if (batchOptions?.returnExceptions !== true) {\n throw e;\n }\n }\n return Object.keys(resultsMap)\n .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))\n .map((key) => resultsMap[parseInt(key, 10)]);\n }\n async batch(inputs, options, batchOptions) {\n return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions);\n }\n}\n/**\n * A sequence of runnables, where the output of each is the input of the next.\n * @example\n * ```typescript\n * const promptTemplate = PromptTemplate.fromTemplate(\n * "Tell me a joke about {topic}",\n * );\n * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]);\n * const result = await chain.invoke({ topic: "bears" });\n * ```\n */\nclass RunnableSequence extends Runnable {\n static lc_name() {\n return "RunnableSequence";\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "first", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "middle", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Object.defineProperty(this, "last", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n this.first = fields.first;\n this.middle = fields.middle ?? this.middle;\n this.last = fields.last;\n this.name = fields.name;\n }\n get steps() {\n return [this.first, ...this.middle, this.last];\n }\n async invoke(input, options) {\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const callbackManager_ = await (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig)(config);\n const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config?.runName);\n delete config.runId;\n let nextStepInput = input;\n let finalOutput;\n try {\n const initialSteps = [this.first, ...this.middle];\n for (let i = 0; i < initialSteps.length; i += 1) {\n const step = initialSteps[i];\n nextStepInput = await step.invoke(nextStepInput, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, {\n callbacks: runManager?.getChild(`seq:step:${i + 1}`),\n }));\n }\n // TypeScript can\'t detect that the last output of the sequence returns RunOutput, so call it out of the loop here\n finalOutput = await this.last.invoke(nextStepInput, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, {\n callbacks: runManager?.getChild(`seq:step:${this.steps.length}`),\n }));\n }\n catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));\n return finalOutput;\n }\n async batch(inputs, options, batchOptions) {\n const configList = this._getOptionsList(options ?? {}, inputs.length);\n const callbackManagers = await Promise.all(configList.map(_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig));\n const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {\n const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName);\n delete configList[i].runId;\n return handleStartRes;\n }));\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let nextStepInputs = inputs;\n try {\n for (let i = 0; i < this.steps.length; i += 1) {\n const step = this.steps[i];\n nextStepInputs = await step.batch(nextStepInputs, runManagers.map((runManager, j) => {\n const childRunManager = runManager?.getChild(`seq:step:${i + 1}`);\n return (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(configList[j], { callbacks: childRunManager });\n }), batchOptions);\n }\n }\n catch (e) {\n await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e)));\n throw e;\n }\n await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(nextStepInputs, "output"))));\n return nextStepInputs;\n }\n async *_streamIterator(input, options) {\n const callbackManager_ = await (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig)(options);\n const { runId, ...otherOptions } = options ?? {};\n const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName);\n const steps = [this.first, ...this.middle, this.last];\n let concatSupported = true;\n let finalOutput;\n async function* inputGenerator() {\n yield input;\n }\n try {\n let finalGenerator = steps[0].transform(inputGenerator(), (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(otherOptions, {\n callbacks: runManager?.getChild(`seq:step:1`),\n }));\n for (let i = 1; i < steps.length; i += 1) {\n const step = steps[i];\n finalGenerator = await step.transform(finalGenerator, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(otherOptions, {\n callbacks: runManager?.getChild(`seq:step:${i + 1}`),\n }));\n }\n for await (const chunk of finalGenerator) {\n yield chunk;\n if (concatSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n }\n else {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalOutput, chunk);\n }\n catch (e) {\n finalOutput = undefined;\n concatSupported = false;\n }\n }\n }\n }\n }\n catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output"));\n }\n getGraph(config) {\n const graph = new _graph_js__WEBPACK_IMPORTED_MODULE_12__.Graph();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let currentLastNode = null;\n this.steps.forEach((step, index) => {\n const stepGraph = step.getGraph(config);\n if (index !== 0) {\n stepGraph.trimFirstNode();\n }\n if (index !== this.steps.length - 1) {\n stepGraph.trimLastNode();\n }\n graph.extend(stepGraph);\n const stepFirstNode = stepGraph.firstNode();\n if (!stepFirstNode) {\n throw new Error(`Runnable ${step} has no first node`);\n }\n if (currentLastNode) {\n graph.addEdge(currentLastNode, stepFirstNode);\n }\n currentLastNode = stepGraph.lastNode();\n });\n return graph;\n }\n pipe(coerceable) {\n if (RunnableSequence.isRunnableSequence(coerceable)) {\n return new RunnableSequence({\n first: this.first,\n middle: this.middle.concat([\n this.last,\n coerceable.first,\n ...coerceable.middle,\n ]),\n last: coerceable.last,\n name: this.name ?? coerceable.name,\n });\n }\n else {\n return new RunnableSequence({\n first: this.first,\n middle: [...this.middle, this.last],\n last: _coerceToRunnable(coerceable),\n name: this.name,\n });\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static isRunnableSequence(thing) {\n return Array.isArray(thing.middle) && Runnable.isRunnable(thing);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static from([first, ...runnables], name) {\n return new RunnableSequence({\n first: _coerceToRunnable(first),\n middle: runnables.slice(0, -1).map(_coerceToRunnable),\n last: _coerceToRunnable(runnables[runnables.length - 1]),\n name,\n });\n }\n}\n/**\n * A runnable that runs a mapping of runnables in parallel,\n * and returns a mapping of their outputs.\n * @example\n * ```typescript\n * const mapChain = RunnableMap.from({\n * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe(\n * new ChatAnthropic({}),\n * ),\n * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe(\n * new ChatAnthropic({}),\n * ),\n * });\n * const result = await mapChain.invoke({ topic: "bear" });\n * ```\n */\nclass RunnableMap extends Runnable {\n static lc_name() {\n return "RunnableMap";\n }\n getStepsKeys() {\n return Object.keys(this.steps);\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "steps", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.steps = {};\n for (const [key, value] of Object.entries(fields.steps)) {\n this.steps[key] = _coerceToRunnable(value);\n }\n }\n static from(steps) {\n return new RunnableMap({ steps });\n }\n async invoke(input, options) {\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const callbackManager_ = await (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig)(config);\n const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {\n input,\n }, config.runId, undefined, undefined, undefined, config?.runName);\n delete config.runId;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const output = {};\n try {\n await Promise.all(Object.entries(this.steps).map(async ([key, runnable]) => {\n output[key] = await runnable.invoke(input, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, {\n callbacks: runManager?.getChild(`map:key:${key}`),\n }));\n }));\n }\n catch (e) {\n await runManager?.handleChainError(e);\n throw e;\n }\n await runManager?.handleChainEnd(output);\n return output;\n }\n async *_transform(generator, runManager, options) {\n // shallow copy steps to ignore changes while iterating\n const steps = { ...this.steps };\n // each step gets a copy of the input iterator\n const inputCopies = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.atee)(generator, Object.keys(steps).length);\n // start the first iteration of each output iterator\n const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => {\n const gen = runnable.transform(inputCopies[i], (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(options, {\n callbacks: runManager?.getChild(`map:key:${key}`),\n }));\n return [key, gen.next().then((result) => ({ key, gen, result }))];\n }));\n // yield chunks as they become available,\n // starting new iterations as needed,\n // until all iterators are done\n while (tasks.size) {\n const { key, result, gen } = await Promise.race(tasks.values());\n tasks.delete(key);\n if (!result.done) {\n yield { [key]: result.value };\n tasks.set(key, gen.next().then((result) => ({ key, gen, result })));\n }\n }\n }\n transform(generator, options) {\n return this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n }\n async stream(input, options) {\n async function* generator() {\n yield input;\n }\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const wrappedGenerator = new _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n/**\n * A runnable that wraps a traced LangSmith function.\n */\nclass RunnableTraceable extends Runnable {\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "func", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (!(0,langsmith_singletons_traceable__WEBPACK_IMPORTED_MODULE_1__.isTraceableFunction)(fields.func)) {\n throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");\n }\n this.func = fields.func;\n }\n async invoke(input, options) {\n const [config] = this._getOptionsList(options ?? {}, 1);\n const callbacks = await (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.getCallbackManagerForConfig)(config);\n return (await this.func((0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, { callbacks }), input));\n }\n async *_streamIterator(input, options) {\n const result = await this.invoke(input, options);\n if ((0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.isAsyncIterable)(result)) {\n for await (const item of result) {\n yield item;\n }\n return;\n }\n if ((0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.isIterator)(result)) {\n while (true) {\n const state = result.next();\n if (state.done)\n break;\n yield state.value;\n }\n return;\n }\n yield result;\n }\n static from(func) {\n return new RunnableTraceable({ func });\n }\n}\nfunction assertNonTraceableFunction(func) {\n if ((0,langsmith_singletons_traceable__WEBPACK_IMPORTED_MODULE_1__.isTraceableFunction)(func)) {\n throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn\'t happen.");\n }\n}\n/**\n * A runnable that runs a callable.\n */\nclass RunnableLambda extends Runnable {\n static lc_name() {\n return "RunnableLambda";\n }\n constructor(fields) {\n if ((0,langsmith_singletons_traceable__WEBPACK_IMPORTED_MODULE_1__.isTraceableFunction)(fields.func)) {\n // eslint-disable-next-line no-constructor-return\n return RunnableTraceable.from(fields.func);\n }\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "func", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n assertNonTraceableFunction(fields.func);\n this.func = fields.func;\n }\n static from(func) {\n return new RunnableLambda({\n func,\n });\n }\n async _invoke(input, config, runManager) {\n return new Promise((resolve, reject) => {\n const childConfig = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, {\n callbacks: runManager?.getChild(),\n recursionLimit: (config?.recursionLimit ?? _config_js__WEBPACK_IMPORTED_MODULE_7__.DEFAULT_RECURSION_LIMIT) - 1,\n });\n void _singletons_index_js__WEBPACK_IMPORTED_MODULE_11__.AsyncLocalStorageProviderSingleton.getInstance().run(childConfig, async () => {\n try {\n let output = await this.func(input, {\n ...childConfig,\n config: childConfig,\n });\n if (output && Runnable.isRunnable(output)) {\n if (config?.recursionLimit === 0) {\n throw new Error("Recursion limit reached.");\n }\n output = await output.invoke(input, {\n ...childConfig,\n recursionLimit: (childConfig.recursionLimit ?? _config_js__WEBPACK_IMPORTED_MODULE_7__.DEFAULT_RECURSION_LIMIT) - 1,\n });\n }\n else if ((0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.isAsyncIterable)(output)) {\n let finalOutput;\n for await (const chunk of (0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.consumeAsyncIterableInContext)(childConfig, output)) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n }\n else {\n // Make a best effort to gather, for any type that supports concat.\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalOutput, chunk);\n }\n catch (e) {\n finalOutput = chunk;\n }\n }\n }\n output = finalOutput;\n }\n else if ((0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.isIterableIterator)(output)) {\n let finalOutput;\n for (const chunk of (0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.consumeIteratorInContext)(childConfig, output)) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n }\n else {\n // Make a best effort to gather, for any type that supports concat.\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalOutput, chunk);\n }\n catch (e) {\n finalOutput = chunk;\n }\n }\n }\n output = finalOutput;\n }\n resolve(output);\n }\n catch (e) {\n reject(e);\n }\n });\n });\n }\n async invoke(input, options) {\n return this._callWithConfig(this._invoke, input, options);\n }\n async *_transform(generator, runManager, config) {\n let finalChunk;\n for await (const chunk of generator) {\n if (finalChunk === undefined) {\n finalChunk = chunk;\n }\n else {\n // Make a best effort to gather, for any type that supports concat.\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalChunk = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.concat)(finalChunk, chunk);\n }\n catch (e) {\n finalChunk = chunk;\n }\n }\n }\n const output = await new Promise((resolve, reject) => {\n void _singletons_index_js__WEBPACK_IMPORTED_MODULE_11__.AsyncLocalStorageProviderSingleton.getInstance().run(config, async () => {\n try {\n const res = await this.func(finalChunk, {\n ...config,\n config,\n });\n resolve(res);\n }\n catch (e) {\n reject(e);\n }\n });\n });\n if (output && Runnable.isRunnable(output)) {\n if (config?.recursionLimit === 0) {\n throw new Error("Recursion limit reached.");\n }\n const stream = await output.stream(finalChunk, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(config, {\n callbacks: runManager?.getChild(),\n recursionLimit: (config?.recursionLimit ?? _config_js__WEBPACK_IMPORTED_MODULE_7__.DEFAULT_RECURSION_LIMIT) - 1,\n }));\n for await (const chunk of stream) {\n yield chunk;\n }\n }\n else if ((0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.isAsyncIterable)(output)) {\n for await (const chunk of (0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.consumeAsyncIterableInContext)(config, output)) {\n yield chunk;\n }\n }\n else if ((0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.isIterableIterator)(output)) {\n for (const chunk of (0,_iter_js__WEBPACK_IMPORTED_MODULE_14__.consumeIteratorInContext)(config, output)) {\n yield chunk;\n }\n }\n else {\n yield output;\n }\n }\n transform(generator, options) {\n return this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n }\n async stream(input, options) {\n async function* generator() {\n yield input;\n }\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const wrappedGenerator = new _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\nclass RunnableParallel extends RunnableMap {\n}\n/**\n * A Runnable that can fallback to other Runnables if it fails.\n */\nclass RunnableWithFallbacks extends Runnable {\n static lc_name() {\n return "RunnableWithFallbacks";\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "runnable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "fallbacks", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.runnable = fields.runnable;\n this.fallbacks = fields.fallbacks;\n }\n *runnables() {\n yield this.runnable;\n for (const fallback of this.fallbacks) {\n yield fallback;\n }\n }\n async invoke(input, options) {\n const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_2__.CallbackManager.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata);\n const { runId, ...otherOptions } = options ?? {};\n const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName);\n let firstError;\n for (const runnable of this.runnables()) {\n try {\n const output = await runnable.invoke(input, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(otherOptions, { callbacks: runManager?.getChild() }));\n await runManager?.handleChainEnd(_coerceToDict(output, "output"));\n return output;\n }\n catch (e) {\n if (firstError === undefined) {\n firstError = e;\n }\n }\n }\n if (firstError === undefined) {\n throw new Error("No error stored at end of fallback.");\n }\n await runManager?.handleChainError(firstError);\n throw firstError;\n }\n async batch(inputs, options, batchOptions) {\n if (batchOptions?.returnExceptions) {\n throw new Error("Not implemented.");\n }\n const configList = this._getOptionsList(options ?? {}, inputs.length);\n const callbackManagers = await Promise.all(configList.map((config) => _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_2__.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata)));\n const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => {\n const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName);\n delete configList[i].runId;\n return handleStartRes;\n }));\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let firstError;\n for (const runnable of this.runnables()) {\n try {\n const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(configList[j], {\n callbacks: runManager?.getChild(),\n })), batchOptions);\n await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output"))));\n return outputs;\n }\n catch (e) {\n if (firstError === undefined) {\n firstError = e;\n }\n }\n }\n if (!firstError) {\n throw new Error("No error stored at end of fallbacks.");\n }\n await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError)));\n throw firstError;\n }\n}\n// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type\nfunction _coerceToRunnable(coerceable) {\n if (typeof coerceable === "function") {\n return new RunnableLambda({ func: coerceable });\n }\n else if (Runnable.isRunnable(coerceable)) {\n return coerceable;\n }\n else if (!Array.isArray(coerceable) && typeof coerceable === "object") {\n const runnables = {};\n for (const [key, value] of Object.entries(coerceable)) {\n runnables[key] = _coerceToRunnable(value);\n }\n return new RunnableMap({\n steps: runnables,\n });\n }\n else {\n throw new Error(`Expected a Runnable, function or object.\\nInstead got an unsupported type.`);\n }\n}\n/**\n * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.\n */\nclass RunnableAssign extends Runnable {\n static lc_name() {\n return "RunnableAssign";\n }\n constructor(fields) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (fields instanceof RunnableMap) {\n // eslint-disable-next-line no-param-reassign\n fields = { mapper: fields };\n }\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "mapper", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.mapper = fields.mapper;\n }\n async invoke(input, options) {\n const mapperResult = await this.mapper.invoke(input, options);\n return {\n ...input,\n ...mapperResult,\n };\n }\n async *_transform(generator, runManager, options) {\n // collect mapper keys\n const mapperKeys = this.mapper.getStepsKeys();\n // create two input gens, one for the mapper, one for the input\n const [forPassthrough, forMapper] = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.atee)(generator);\n // create mapper output gen\n const mapperOutput = this.mapper.transform(forMapper, (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.patchConfig)(options, { callbacks: runManager?.getChild() }));\n // start the mapper\n const firstMapperChunkPromise = mapperOutput.next();\n // yield the passthrough\n for await (const chunk of forPassthrough) {\n if (typeof chunk !== "object" || Array.isArray(chunk)) {\n throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`);\n }\n const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key)));\n if (Object.keys(filtered).length > 0) {\n yield filtered;\n }\n }\n // yield the mapper output\n yield (await firstMapperChunkPromise).value;\n for await (const chunk of mapperOutput) {\n yield chunk;\n }\n }\n transform(generator, options) {\n return this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n }\n async stream(input, options) {\n async function* generator() {\n yield input;\n }\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const wrappedGenerator = new _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n/**\n * A runnable that assigns key-value pairs to inputs of type `Record<string, unknown>`.\n */\nclass RunnablePick extends Runnable {\n static lc_name() {\n return "RunnablePick";\n }\n constructor(fields) {\n if (typeof fields === "string" || Array.isArray(fields)) {\n // eslint-disable-next-line no-param-reassign\n fields = { keys: fields };\n }\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "keys", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.keys = fields.keys;\n }\n async _pick(input) {\n if (typeof this.keys === "string") {\n return input[this.keys];\n }\n else {\n const picked = this.keys\n .map((key) => [key, input[key]])\n .filter((v) => v[1] !== undefined);\n return picked.length === 0 ? undefined : Object.fromEntries(picked);\n }\n }\n async invoke(input, options) {\n return this._callWithConfig(this._pick.bind(this), input, options);\n }\n async *_transform(generator) {\n for await (const chunk of generator) {\n const picked = await this._pick(chunk);\n if (picked !== undefined) {\n yield picked;\n }\n }\n }\n transform(generator, options) {\n return this._transformStreamWithConfig(generator, this._transform.bind(this), options);\n }\n async stream(input, options) {\n async function* generator() {\n yield input;\n }\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_7__.ensureConfig)(options);\n const wrappedGenerator = new _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.AsyncGeneratorWithSetup({\n generator: this.transform(generator(), config),\n config,\n });\n await wrappedGenerator.setup;\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_6__.IterableReadableStream.fromAsyncGenerator(wrappedGenerator);\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/base.js?');
|
|
385
|
+
/***/
|
|
386
|
+
},
|
|
387
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/config.js":
|
|
388
|
+
/*!***************************************************************!*\
|
|
389
|
+
!*** ./node_modules/@langchain/core/dist/runnables/config.js ***!
|
|
390
|
+
\***************************************************************/
|
|
391
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
392
|
+
"use strict";
|
|
393
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_RECURSION_LIMIT: () => (/* binding */ DEFAULT_RECURSION_LIMIT),\n/* harmony export */ ensureConfig: () => (/* binding */ ensureConfig),\n/* harmony export */ getCallbackManagerForConfig: () => (/* binding */ getCallbackManagerForConfig),\n/* harmony export */ mergeConfigs: () => (/* binding */ mergeConfigs),\n/* harmony export */ patchConfig: () => (/* binding */ patchConfig)\n/* harmony export */ });\n/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../callbacks/manager.js */ "./node_modules/@langchain/core/dist/callbacks/manager.js");\n/* harmony import */ var _singletons_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../singletons/index.js */ "./node_modules/@langchain/core/dist/singletons/index.js");\n\n\nconst DEFAULT_RECURSION_LIMIT = 25;\nasync function getCallbackManagerForConfig(config) {\n return _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_0__.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);\n}\nfunction mergeConfigs(...configs) {\n // We do not want to call ensureConfig on the empty state here as this may cause\n // double loading of callbacks if async local storage is being used.\n const copy = {};\n for (const options of configs.filter((c) => !!c)) {\n for (const key of Object.keys(options)) {\n if (key === "metadata") {\n copy[key] = { ...copy[key], ...options[key] };\n }\n else if (key === "tags") {\n const baseKeys = copy[key] ?? [];\n copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))];\n }\n else if (key === "configurable") {\n copy[key] = { ...copy[key], ...options[key] };\n }\n else if (key === "callbacks") {\n const baseCallbacks = copy.callbacks;\n const providedCallbacks = options.callbacks;\n // callbacks can be either undefined, Array<handler> or manager\n // so merging two callbacks values has 6 cases\n if (Array.isArray(providedCallbacks)) {\n if (!baseCallbacks) {\n copy.callbacks = providedCallbacks;\n }\n else if (Array.isArray(baseCallbacks)) {\n copy.callbacks = baseCallbacks.concat(providedCallbacks);\n }\n else {\n // baseCallbacks is a manager\n const manager = baseCallbacks.copy();\n for (const callback of providedCallbacks) {\n manager.addHandler((0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_0__.ensureHandler)(callback), true);\n }\n copy.callbacks = manager;\n }\n }\n else if (providedCallbacks) {\n // providedCallbacks is a manager\n if (!baseCallbacks) {\n copy.callbacks = providedCallbacks;\n }\n else if (Array.isArray(baseCallbacks)) {\n const manager = providedCallbacks.copy();\n for (const callback of baseCallbacks) {\n manager.addHandler((0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_0__.ensureHandler)(callback), true);\n }\n copy.callbacks = manager;\n }\n else {\n // baseCallbacks is also a manager\n copy.callbacks = new _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_0__.CallbackManager(providedCallbacks._parentRunId, {\n handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers),\n inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers),\n tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))),\n inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))),\n metadata: {\n ...baseCallbacks.metadata,\n ...providedCallbacks.metadata,\n },\n });\n }\n }\n }\n else {\n const typedKey = key;\n copy[typedKey] = options[typedKey] ?? copy[typedKey];\n }\n }\n }\n return copy;\n}\nconst PRIMITIVES = new Set(["string", "number", "boolean"]);\n/**\n * Ensure that a passed config is an object with all required keys present.\n *\n * Note: To make sure async local storage loading works correctly, this\n * should not be called with a default or prepopulated config argument.\n */\nfunction ensureConfig(config) {\n const loadedConfig = config ?? _singletons_index_js__WEBPACK_IMPORTED_MODULE_1__.AsyncLocalStorageProviderSingleton.getInstance().getStore();\n let empty = {\n tags: [],\n metadata: {},\n callbacks: undefined,\n recursionLimit: 25,\n runId: undefined,\n };\n if (loadedConfig) {\n empty = { ...empty, ...loadedConfig };\n }\n if (loadedConfig?.configurable) {\n for (const key of Object.keys(loadedConfig.configurable)) {\n if (PRIMITIVES.has(typeof loadedConfig.configurable[key]) &&\n !empty.metadata?.[key]) {\n if (!empty.metadata) {\n empty.metadata = {};\n }\n empty.metadata[key] = loadedConfig.configurable[key];\n }\n }\n }\n return empty;\n}\n/**\n * Helper function that patches runnable configs with updated properties.\n */\nfunction patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId, } = {}) {\n const newConfig = ensureConfig(config);\n if (callbacks !== undefined) {\n /**\n * If we\'re replacing callbacks we need to unset runName\n * since that should apply only to the same run as the original callbacks\n */\n delete newConfig.runName;\n newConfig.callbacks = callbacks;\n }\n if (recursionLimit !== undefined) {\n newConfig.recursionLimit = recursionLimit;\n }\n if (maxConcurrency !== undefined) {\n newConfig.maxConcurrency = maxConcurrency;\n }\n if (runName !== undefined) {\n newConfig.runName = runName;\n }\n if (configurable !== undefined) {\n newConfig.configurable = { ...newConfig.configurable, ...configurable };\n }\n if (runId !== undefined) {\n delete newConfig.runId;\n }\n return newConfig;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/config.js?');
|
|
394
|
+
/***/
|
|
395
|
+
},
|
|
396
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/graph.js":
|
|
397
|
+
/*!**************************************************************!*\
|
|
398
|
+
!*** ./node_modules/@langchain/core/dist/runnables/graph.js ***!
|
|
399
|
+
\**************************************************************/
|
|
400
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
401
|
+
"use strict";
|
|
402
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Graph: () => (/* binding */ Graph),\n/* harmony export */ nodeDataStr: () => (/* binding */ nodeDataStr)\n/* harmony export */ });\n/* harmony import */ var zod_to_json_schema__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! zod-to-json-schema */ "./node_modules/zod-to-json-schema/dist/esm/index.js");\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/validate.js");\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@langchain/core/dist/runnables/utils.js");\n\n\n\nconst MAX_DATA_DISPLAY_NAME_LENGTH = 42;\nfunction nodeDataStr(node) {\n if (!(0,uuid__WEBPACK_IMPORTED_MODULE_2__["default"])(node.id)) {\n return node.id;\n }\n else if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.isRunnableInterface)(node.data)) {\n try {\n let data = node.data.toString();\n if (data.startsWith("<") ||\n data[0] !== data[0].toUpperCase() ||\n data.split("\\n").length > 1) {\n data = node.data.getName();\n }\n else if (data.length > MAX_DATA_DISPLAY_NAME_LENGTH) {\n data = `${data.substring(0, MAX_DATA_DISPLAY_NAME_LENGTH)}...`;\n }\n return data.startsWith("Runnable") ? data.slice("Runnable".length) : data;\n }\n catch (error) {\n return node.data.getName();\n }\n }\n else {\n return node.data.name ?? "UnknownSchema";\n }\n}\nfunction nodeDataJson(node) {\n // if node.data is implements Runnable\n if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.isRunnableInterface)(node.data)) {\n return {\n type: "runnable",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n }\n else {\n return {\n type: "schema",\n data: { ...(0,zod_to_json_schema__WEBPACK_IMPORTED_MODULE_0__.zodToJsonSchema)(node.data.schema), title: node.data.name },\n };\n }\n}\nclass Graph {\n constructor() {\n Object.defineProperty(this, "nodes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {}\n });\n Object.defineProperty(this, "edges", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n }\n // Convert the graph to a JSON-serializable format.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON() {\n const stableNodeIds = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = (0,uuid__WEBPACK_IMPORTED_MODULE_2__["default"])(node.id) ? i : node.id;\n });\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n })),\n edges: this.edges.map((edge) => edge.data\n ? {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n data: edge.data,\n }\n : {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n }),\n };\n }\n addNode(data, id) {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id || (0,uuid__WEBPACK_IMPORTED_MODULE_3__["default"])();\n const node = { id: nodeId, data };\n this.nodes[nodeId] = node;\n return node;\n }\n removeNode(node) {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n // Filter out edges connected to the node\n this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id);\n }\n addEdge(source, target, data) {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge = { source: source.id, target: target.id, data };\n this.edges.push(edge);\n return edge;\n }\n firstNode() {\n const targets = new Set(this.edges.map((edge) => edge.target));\n const found = [];\n Object.values(this.nodes).forEach((node) => {\n if (!targets.has(node.id)) {\n found.push(node);\n }\n });\n return found[0];\n }\n lastNode() {\n const sources = new Set(this.edges.map((edge) => edge.source));\n const found = [];\n Object.values(this.nodes).forEach((node) => {\n if (!sources.has(node.id)) {\n found.push(node);\n }\n });\n return found[0];\n }\n extend(graph) {\n // Add all nodes from the other graph, taking care to avoid duplicates\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[key] = value;\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...graph.edges];\n }\n trimFirstNode() {\n const firstNode = this.firstNode();\n if (firstNode) {\n const outgoingEdges = this.edges.filter((edge) => edge.source === firstNode.id);\n if (Object.keys(this.nodes).length === 1 || outgoingEdges.length === 1) {\n this.removeNode(firstNode);\n }\n }\n }\n trimLastNode() {\n const lastNode = this.lastNode();\n if (lastNode) {\n const incomingEdges = this.edges.filter((edge) => edge.target === lastNode.id);\n if (Object.keys(this.nodes).length === 1 || incomingEdges.length === 1) {\n this.removeNode(lastNode);\n }\n }\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/graph.js?');
|
|
403
|
+
/***/
|
|
404
|
+
},
|
|
405
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/iter.js":
|
|
406
|
+
/*!*************************************************************!*\
|
|
407
|
+
!*** ./node_modules/@langchain/core/dist/runnables/iter.js ***!
|
|
408
|
+
\*************************************************************/
|
|
409
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
410
|
+
"use strict";
|
|
411
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ consumeAsyncIterableInContext: () => (/* binding */ consumeAsyncIterableInContext),\n/* harmony export */ consumeIteratorInContext: () => (/* binding */ consumeIteratorInContext),\n/* harmony export */ isAsyncIterable: () => (/* binding */ isAsyncIterable),\n/* harmony export */ isIterableIterator: () => (/* binding */ isIterableIterator),\n/* harmony export */ isIterator: () => (/* binding */ isIterator)\n/* harmony export */ });\n/* harmony import */ var _singletons_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../singletons/index.js */ "./node_modules/@langchain/core/dist/singletons/index.js");\n\nfunction isIterableIterator(thing) {\n return (typeof thing === "object" &&\n thing !== null &&\n typeof thing[Symbol.iterator] === "function" &&\n // avoid detecting array/set as iterator\n typeof thing.next === "function");\n}\nconst isIterator = (x) => x != null &&\n typeof x === "object" &&\n "next" in x &&\n typeof x.next === "function";\nfunction isAsyncIterable(thing) {\n return (typeof thing === "object" &&\n thing !== null &&\n typeof thing[Symbol.asyncIterator] ===\n "function");\n}\nfunction* consumeIteratorInContext(context, iter) {\n const storage = _singletons_index_js__WEBPACK_IMPORTED_MODULE_0__.AsyncLocalStorageProviderSingleton.getInstance();\n while (true) {\n const { value, done } = storage.run(context, iter.next.bind(iter));\n if (done) {\n break;\n }\n else {\n yield value;\n }\n }\n}\nasync function* consumeAsyncIterableInContext(context, iter) {\n const storage = _singletons_index_js__WEBPACK_IMPORTED_MODULE_0__.AsyncLocalStorageProviderSingleton.getInstance();\n const iterator = iter[Symbol.asyncIterator]();\n while (true) {\n const { value, done } = await storage.run(context, iterator.next.bind(iter));\n if (done) {\n break;\n }\n else {\n yield value;\n }\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/iter.js?');
|
|
412
|
+
/***/
|
|
413
|
+
},
|
|
414
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/passthrough.js":
|
|
415
|
+
/*!********************************************************************!*\
|
|
416
|
+
!*** ./node_modules/@langchain/core/dist/runnables/passthrough.js ***!
|
|
417
|
+
\********************************************************************/
|
|
418
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
419
|
+
"use strict";
|
|
420
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RunnablePassthrough: () => (/* binding */ RunnablePassthrough)\n/* harmony export */ });\n/* harmony import */ var _utils_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/runnables/base.js");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./config.js */ "./node_modules/@langchain/core/dist/runnables/config.js");\n\n\n\n/**\n * A runnable to passthrough inputs unchanged or with additional keys.\n *\n * This runnable behaves almost like the identity function, except that it\n * can be configured to add additional keys to the output, if the input is\n * an object.\n *\n * The example below demonstrates how to use `RunnablePassthrough to\n * passthrough the input from the `.invoke()`\n *\n * @example\n * ```typescript\n * const chain = RunnableSequence.from([\n * {\n * question: new RunnablePassthrough(),\n * context: async () => loadContextFromStore(),\n * },\n * prompt,\n * llm,\n * outputParser,\n * ]);\n * const response = await chain.invoke(\n * "I can pass a single string instead of an object since I\'m using `RunnablePassthrough`."\n * );\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nclass RunnablePassthrough extends _base_js__WEBPACK_IMPORTED_MODULE_1__.Runnable {\n static lc_name() {\n return "RunnablePassthrough";\n }\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "lc_namespace", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: ["langchain_core", "runnables"]\n });\n Object.defineProperty(this, "lc_serializable", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "func", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n if (fields) {\n this.func = fields.func;\n }\n }\n async invoke(input, options) {\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_2__.ensureConfig)(options);\n if (this.func) {\n await this.func(input, config);\n }\n return this._callWithConfig((input) => Promise.resolve(input), input, config);\n }\n async *transform(generator, options) {\n const config = (0,_config_js__WEBPACK_IMPORTED_MODULE_2__.ensureConfig)(options);\n let finalOutput;\n let finalOutputSupported = true;\n for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n }\n else {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = (0,_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.concat)(finalOutput, chunk);\n }\n catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n if (this.func && finalOutput !== undefined) {\n await this.func(finalOutput, config);\n }\n }\n /**\n * A runnable that assigns key-value pairs to the input.\n *\n * The example below shows how you could use it with an inline function.\n *\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}\n * Question: {question}\n * SQL Query:`);\n *\n * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`\n * // call (in this example it\'s the question), along with any inputs passed to the `.assign()` method.\n * // In this case, we\'re passing the schema.\n * const sqlQueryGeneratorChain = RunnableSequence.from([\n * RunnablePassthrough.assign({\n * schema: async () => db.getTableInfo(),\n * }),\n * prompt,\n * new ChatOpenAI({}).bind({ stop: ["\\nSQLResult:"] }),\n * new StringOutputParser(),\n * ]);\n * const result = await sqlQueryGeneratorChain.invoke({\n * question: "How many employees are there?",\n * });\n * ```\n */\n static assign(mapping) {\n return new _base_js__WEBPACK_IMPORTED_MODULE_1__.RunnableAssign(new _base_js__WEBPACK_IMPORTED_MODULE_1__.RunnableMap({ steps: mapping }));\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/passthrough.js?');
|
|
421
|
+
/***/
|
|
422
|
+
},
|
|
423
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/utils.js":
|
|
424
|
+
/*!**************************************************************!*\
|
|
425
|
+
!*** ./node_modules/@langchain/core/dist/runnables/utils.js ***!
|
|
426
|
+
\**************************************************************/
|
|
427
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
428
|
+
"use strict";
|
|
429
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ _RootEventFilter: () => (/* binding */ _RootEventFilter),\n/* harmony export */ isRunnableInterface: () => (/* binding */ isRunnableInterface)\n/* harmony export */ });\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isRunnableInterface(thing) {\n return thing ? thing.lc_runnable : false;\n}\n/**\n * Utility to filter the root event in the streamEvents implementation.\n * This is simply binding the arguments to the namespace to make save on\n * a bit of typing in the streamEvents implementation.\n *\n * TODO: Refactor and remove.\n */\nclass _RootEventFilter {\n constructor(fields) {\n Object.defineProperty(this, "includeNames", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "includeTypes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "includeTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeNames", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeTypes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.includeNames = fields.includeNames;\n this.includeTypes = fields.includeTypes;\n this.includeTags = fields.includeTags;\n this.excludeNames = fields.excludeNames;\n this.excludeTypes = fields.excludeTypes;\n this.excludeTags = fields.excludeTags;\n }\n includeEvent(event, rootType) {\n let include = this.includeNames === undefined &&\n this.includeTypes === undefined &&\n this.includeTags === undefined;\n const eventTags = event.tags ?? [];\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(event.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(rootType);\n }\n if (this.includeTags !== undefined) {\n include =\n include || eventTags.some((tag) => this.includeTags?.includes(tag));\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(event.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(rootType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && eventTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/utils.js?');
|
|
430
|
+
/***/
|
|
431
|
+
},
|
|
432
|
+
/***/ "./node_modules/@langchain/core/dist/runnables/wrappers.js":
|
|
433
|
+
/*!*****************************************************************!*\
|
|
434
|
+
!*** ./node_modules/@langchain/core/dist/runnables/wrappers.js ***!
|
|
435
|
+
\*****************************************************************/
|
|
436
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
437
|
+
"use strict";
|
|
438
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ convertToHttpEventStream: () => (/* binding */ convertToHttpEventStream)\n/* harmony export */ });\n/* harmony import */ var _utils_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n\nfunction convertToHttpEventStream(stream) {\n const encoder = new TextEncoder();\n const finalStream = new ReadableStream({\n async start(controller) {\n for await (const chunk of stream) {\n controller.enqueue(encoder.encode(`event: data\\ndata: ${JSON.stringify(chunk)}\\n\\n`));\n }\n controller.enqueue(encoder.encode("event: end\\n\\n"));\n controller.close();\n },\n });\n return _utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.IterableReadableStream.fromReadableStream(finalStream);\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/runnables/wrappers.js?');
|
|
439
|
+
/***/
|
|
440
|
+
},
|
|
441
|
+
/***/ "./node_modules/@langchain/core/dist/singletons/index.js":
|
|
442
|
+
/*!***************************************************************!*\
|
|
443
|
+
!*** ./node_modules/@langchain/core/dist/singletons/index.js ***!
|
|
444
|
+
\***************************************************************/
|
|
445
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
446
|
+
"use strict";
|
|
447
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncLocalStorageProviderSingleton: () => (/* binding */ AsyncLocalStorageProviderSingleton),\n/* harmony export */ MockAsyncLocalStorage: () => (/* binding */ MockAsyncLocalStorage)\n/* harmony export */ });\n/* eslint-disable @typescript-eslint/no-explicit-any */\nclass MockAsyncLocalStorage {\n getStore() {\n return undefined;\n }\n run(_store, callback) {\n return callback();\n }\n}\nconst mockAsyncLocalStorage = new MockAsyncLocalStorage();\nclass AsyncLocalStorageProvider {\n getInstance() {\n return (globalThis.__lc_tracing_async_local_storage ??\n mockAsyncLocalStorage);\n }\n initializeGlobalInstance(instance) {\n if (globalThis.__lc_tracing_async_local_storage === undefined) {\n globalThis.__lc_tracing_async_local_storage = instance;\n }\n }\n}\nconst AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/singletons/index.js?");
|
|
448
|
+
/***/
|
|
449
|
+
},
|
|
450
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/base.js":
|
|
451
|
+
/*!***********************************************************!*\
|
|
452
|
+
!*** ./node_modules/@langchain/core/dist/tracers/base.js ***!
|
|
453
|
+
\***********************************************************/
|
|
454
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
455
|
+
"use strict";
|
|
456
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseTracer: () => (/* binding */ BaseTracer)\n/* harmony export */ });\n/* harmony import */ var _callbacks_base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../callbacks/base.js */ "./node_modules/@langchain/core/dist/callbacks/base.js");\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _coerceToDict(value, defaultKey) {\n return value && !Array.isArray(value) && typeof value === "object"\n ? value\n : { [defaultKey]: value };\n}\nfunction stripNonAlphanumeric(input) {\n return input.replace(/[-:.]/g, "");\n}\nfunction convertToDottedOrderFormat(epoch, runId, executionOrder) {\n const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");\n return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId);\n}\nclass BaseTracer extends _callbacks_base_js__WEBPACK_IMPORTED_MODULE_0__.BaseCallbackHandler {\n constructor(_fields) {\n super(...arguments);\n Object.defineProperty(this, "runMap", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n }\n copy() {\n return this;\n }\n stringifyError(error) {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n return error.message + (error?.stack ? `\\n\\n${error.stack}` : "");\n }\n if (typeof error === "string") {\n return error;\n }\n return `${error}`;\n }\n _addChildRun(parentRun, childRun) {\n parentRun.child_runs.push(childRun);\n }\n async _startTrace(run) {\n const currentDottedOrder = convertToDottedOrderFormat(run.start_time, run.id, run.execution_order);\n const storedRun = { ...run };\n if (storedRun.parent_run_id !== undefined) {\n const parentRun = this.runMap.get(storedRun.parent_run_id);\n if (parentRun) {\n this._addChildRun(parentRun, storedRun);\n parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);\n storedRun.trace_id = parentRun.trace_id;\n if (parentRun.dotted_order !== undefined) {\n storedRun.dotted_order = [\n parentRun.dotted_order,\n currentDottedOrder,\n ].join(".");\n }\n else {\n // This can happen naturally for callbacks added within a run\n // console.debug(`Parent run with UUID ${storedRun.parent_run_id} has no dotted order.`);\n }\n }\n else {\n // This can happen naturally for callbacks added within a run\n // console.debug(\n // `Parent run with UUID ${storedRun.parent_run_id} not found.`\n // );\n }\n }\n else {\n storedRun.trace_id = storedRun.id;\n storedRun.dotted_order = currentDottedOrder;\n }\n this.runMap.set(storedRun.id, storedRun);\n await this.onRunCreate?.(storedRun);\n }\n async _endTrace(run) {\n const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id);\n if (parentRun) {\n parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order);\n }\n else {\n await this.persistRun(run);\n }\n this.runMap.delete(run.id);\n await this.onRunUpdate?.(run);\n }\n _getExecutionOrder(parentRunId) {\n const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId);\n // If a run has no parent then execution order is 1\n if (!parentRun) {\n return 1;\n }\n return parentRun.child_execution_order + 1;\n }\n async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {\n const execution_order = this._getExecutionOrder(parentRunId);\n const start_time = Date.now();\n const finalExtraParams = metadata\n ? { ...extraParams, metadata }\n : extraParams;\n const run = {\n id: runId,\n name: name ?? llm.id[llm.id.length - 1],\n parent_run_id: parentRunId,\n start_time,\n serialized: llm,\n events: [\n {\n name: "start",\n time: new Date(start_time).toISOString(),\n },\n ],\n inputs: { prompts },\n execution_order,\n child_runs: [],\n child_execution_order: execution_order,\n run_type: "llm",\n extra: finalExtraParams ?? {},\n tags: tags || [],\n };\n await this._startTrace(run);\n await this.onLLMStart?.(run);\n return run;\n }\n async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {\n const execution_order = this._getExecutionOrder(parentRunId);\n const start_time = Date.now();\n const finalExtraParams = metadata\n ? { ...extraParams, metadata }\n : extraParams;\n const run = {\n id: runId,\n name: name ?? llm.id[llm.id.length - 1],\n parent_run_id: parentRunId,\n start_time,\n serialized: llm,\n events: [\n {\n name: "start",\n time: new Date(start_time).toISOString(),\n },\n ],\n inputs: { messages },\n execution_order,\n child_runs: [],\n child_execution_order: execution_order,\n run_type: "llm",\n extra: finalExtraParams ?? {},\n tags: tags || [],\n };\n await this._startTrace(run);\n await this.onLLMStart?.(run);\n return run;\n }\n async handleLLMEnd(output, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "llm") {\n throw new Error("No LLM run to end.");\n }\n run.end_time = Date.now();\n run.outputs = output;\n run.events.push({\n name: "end",\n time: new Date(run.end_time).toISOString(),\n });\n await this.onLLMEnd?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleLLMError(error, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "llm") {\n throw new Error("No LLM run to end.");\n }\n run.end_time = Date.now();\n run.error = this.stringifyError(error);\n run.events.push({\n name: "error",\n time: new Date(run.end_time).toISOString(),\n });\n await this.onLLMError?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {\n const execution_order = this._getExecutionOrder(parentRunId);\n const start_time = Date.now();\n const run = {\n id: runId,\n name: name ?? chain.id[chain.id.length - 1],\n parent_run_id: parentRunId,\n start_time,\n serialized: chain,\n events: [\n {\n name: "start",\n time: new Date(start_time).toISOString(),\n },\n ],\n inputs,\n execution_order,\n child_execution_order: execution_order,\n run_type: runType ?? "chain",\n child_runs: [],\n extra: metadata ? { metadata } : {},\n tags: tags || [],\n };\n await this._startTrace(run);\n await this.onChainStart?.(run);\n return run;\n }\n async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) {\n const run = this.runMap.get(runId);\n if (!run) {\n throw new Error("No chain run to end.");\n }\n run.end_time = Date.now();\n run.outputs = _coerceToDict(outputs, "output");\n run.events.push({\n name: "end",\n time: new Date(run.end_time).toISOString(),\n });\n if (kwargs?.inputs !== undefined) {\n run.inputs = _coerceToDict(kwargs.inputs, "input");\n }\n await this.onChainEnd?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleChainError(error, runId, _parentRunId, _tags, kwargs) {\n const run = this.runMap.get(runId);\n if (!run) {\n throw new Error("No chain run to end.");\n }\n run.end_time = Date.now();\n run.error = this.stringifyError(error);\n run.events.push({\n name: "error",\n time: new Date(run.end_time).toISOString(),\n });\n if (kwargs?.inputs !== undefined) {\n run.inputs = _coerceToDict(kwargs.inputs, "input");\n }\n await this.onChainError?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) {\n const execution_order = this._getExecutionOrder(parentRunId);\n const start_time = Date.now();\n const run = {\n id: runId,\n name: name ?? tool.id[tool.id.length - 1],\n parent_run_id: parentRunId,\n start_time,\n serialized: tool,\n events: [\n {\n name: "start",\n time: new Date(start_time).toISOString(),\n },\n ],\n inputs: { input },\n execution_order,\n child_execution_order: execution_order,\n run_type: "tool",\n child_runs: [],\n extra: metadata ? { metadata } : {},\n tags: tags || [],\n };\n await this._startTrace(run);\n await this.onToolStart?.(run);\n return run;\n }\n async handleToolEnd(output, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "tool") {\n throw new Error("No tool run to end");\n }\n run.end_time = Date.now();\n run.outputs = { output };\n run.events.push({\n name: "end",\n time: new Date(run.end_time).toISOString(),\n });\n await this.onToolEnd?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleToolError(error, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "tool") {\n throw new Error("No tool run to end");\n }\n run.end_time = Date.now();\n run.error = this.stringifyError(error);\n run.events.push({\n name: "error",\n time: new Date(run.end_time).toISOString(),\n });\n await this.onToolError?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleAgentAction(action, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "chain") {\n return;\n }\n const agentRun = run;\n agentRun.actions = agentRun.actions || [];\n agentRun.actions.push(action);\n agentRun.events.push({\n name: "agent_action",\n time: new Date().toISOString(),\n kwargs: { action },\n });\n await this.onAgentAction?.(run);\n }\n async handleAgentEnd(action, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "chain") {\n return;\n }\n run.events.push({\n name: "agent_end",\n time: new Date().toISOString(),\n kwargs: { action },\n });\n await this.onAgentEnd?.(run);\n }\n async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {\n const execution_order = this._getExecutionOrder(parentRunId);\n const start_time = Date.now();\n const run = {\n id: runId,\n name: name ?? retriever.id[retriever.id.length - 1],\n parent_run_id: parentRunId,\n start_time,\n serialized: retriever,\n events: [\n {\n name: "start",\n time: new Date(start_time).toISOString(),\n },\n ],\n inputs: { query },\n execution_order,\n child_execution_order: execution_order,\n run_type: "retriever",\n child_runs: [],\n extra: metadata ? { metadata } : {},\n tags: tags || [],\n };\n await this._startTrace(run);\n await this.onRetrieverStart?.(run);\n return run;\n }\n async handleRetrieverEnd(documents, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "retriever") {\n throw new Error("No retriever run to end");\n }\n run.end_time = Date.now();\n run.outputs = { documents };\n run.events.push({\n name: "end",\n time: new Date(run.end_time).toISOString(),\n });\n await this.onRetrieverEnd?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleRetrieverError(error, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "retriever") {\n throw new Error("No retriever run to end");\n }\n run.end_time = Date.now();\n run.error = this.stringifyError(error);\n run.events.push({\n name: "error",\n time: new Date(run.end_time).toISOString(),\n });\n await this.onRetrieverError?.(run);\n await this._endTrace(run);\n return run;\n }\n async handleText(text, runId) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "chain") {\n return;\n }\n run.events.push({\n name: "text",\n time: new Date().toISOString(),\n kwargs: { text },\n });\n await this.onText?.(run);\n }\n async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) {\n const run = this.runMap.get(runId);\n if (!run || run?.run_type !== "llm") {\n throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);\n }\n run.events.push({\n name: "new_token",\n time: new Date().toISOString(),\n kwargs: { token, idx, chunk: fields?.chunk },\n });\n await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk });\n return run;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/base.js?');
|
|
457
|
+
/***/
|
|
458
|
+
},
|
|
459
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/console.js":
|
|
460
|
+
/*!**************************************************************!*\
|
|
461
|
+
!*** ./node_modules/@langchain/core/dist/tracers/console.js ***!
|
|
462
|
+
\**************************************************************/
|
|
463
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
464
|
+
"use strict";
|
|
465
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ConsoleCallbackHandler: () => (/* binding */ ConsoleCallbackHandler)\n/* harmony export */ });\n/* harmony import */ var ansi_styles__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ansi-styles */ "./node_modules/ansi-styles/index.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/tracers/base.js");\n\n\nfunction wrap(style, text) {\n return `${style.open}${text}${style.close}`;\n}\nfunction tryJsonStringify(obj, fallback) {\n try {\n return JSON.stringify(obj, null, 2);\n }\n catch (err) {\n return fallback;\n }\n}\nfunction elapsed(run) {\n if (!run.end_time)\n return "";\n const elapsed = run.end_time - run.start_time;\n if (elapsed < 1000) {\n return `${elapsed}ms`;\n }\n return `${(elapsed / 1000).toFixed(2)}s`;\n}\nconst { color } = ansi_styles__WEBPACK_IMPORTED_MODULE_0__;\n/**\n * A tracer that logs all events to the console. It extends from the\n * `BaseTracer` class and overrides its methods to provide custom logging\n * functionality.\n * @example\n * ```typescript\n *\n * const llm = new ChatAnthropic({\n * temperature: 0,\n * tags: ["example", "callbacks", "constructor"],\n * callbacks: [new ConsoleCallbackHandler()],\n * });\n *\n * ```\n */\nclass ConsoleCallbackHandler extends _base_js__WEBPACK_IMPORTED_MODULE_1__.BaseTracer {\n constructor() {\n super(...arguments);\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "console_callback_handler"\n });\n }\n /**\n * Method used to persist the run. In this case, it simply returns a\n * resolved promise as there\'s no persistence logic.\n * @param _run The run to persist.\n * @returns A resolved promise.\n */\n persistRun(_run) {\n return Promise.resolve();\n }\n // utility methods\n /**\n * Method used to get all the parent runs of a given run.\n * @param run The run whose parents are to be retrieved.\n * @returns An array of parent runs.\n */\n getParents(run) {\n const parents = [];\n let currentRun = run;\n while (currentRun.parent_run_id) {\n const parent = this.runMap.get(currentRun.parent_run_id);\n if (parent) {\n parents.push(parent);\n currentRun = parent;\n }\n else {\n break;\n }\n }\n return parents;\n }\n /**\n * Method used to get a string representation of the run\'s lineage, which\n * is used in logging.\n * @param run The run whose lineage is to be retrieved.\n * @returns A string representation of the run\'s lineage.\n */\n getBreadcrumbs(run) {\n const parents = this.getParents(run).reverse();\n const string = [...parents, run]\n .map((parent, i, arr) => {\n const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`;\n return i === arr.length - 1 ? wrap(ansi_styles__WEBPACK_IMPORTED_MODULE_0__.bold, name) : name;\n })\n .join(" > ");\n return wrap(color.grey, string);\n }\n // logging methods\n /**\n * Method used to log the start of a chain run.\n * @param run The chain run that has started.\n * @returns void\n */\n onChainStart(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`);\n }\n /**\n * Method used to log the end of a chain run.\n * @param run The chain run that has ended.\n * @returns void\n */\n onChainEnd(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`);\n }\n /**\n * Method used to log any errors of a chain run.\n * @param run The chain run that has errored.\n * @returns void\n */\n onChainError(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`);\n }\n /**\n * Method used to log the start of an LLM run.\n * @param run The LLM run that has started.\n * @returns void\n */\n onLLMStart(run) {\n const crumbs = this.getBreadcrumbs(run);\n const inputs = "prompts" in run.inputs\n ? { prompts: run.inputs.prompts.map((p) => p.trim()) }\n : run.inputs;\n console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`);\n }\n /**\n * Method used to log the end of an LLM run.\n * @param run The LLM run that has ended.\n * @returns void\n */\n onLLMEnd(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`);\n }\n /**\n * Method used to log any errors of an LLM run.\n * @param run The LLM run that has errored.\n * @returns void\n */\n onLLMError(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`);\n }\n /**\n * Method used to log the start of a tool run.\n * @param run The tool run that has started.\n * @returns void\n */\n onToolStart(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${run.inputs.input?.trim()}"`);\n }\n /**\n * Method used to log the end of a tool run.\n * @param run The tool run that has ended.\n * @returns void\n */\n onToolEnd(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${run.outputs?.output?.trim()}"`);\n }\n /**\n * Method used to log any errors of a tool run.\n * @param run The tool run that has errored.\n * @returns void\n */\n onToolError(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`);\n }\n /**\n * Method used to log the start of a retriever run.\n * @param run The retriever run that has started.\n * @returns void\n */\n onRetrieverStart(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`);\n }\n /**\n * Method used to log the end of a retriever run.\n * @param run The retriever run that has ended.\n * @returns void\n */\n onRetrieverEnd(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`);\n }\n /**\n * Method used to log any errors of a retriever run.\n * @param run The retriever run that has errored.\n * @returns void\n */\n onRetrieverError(run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`);\n }\n /**\n * Method used to log the action selected by the agent.\n * @param run The run in which the agent action occurred.\n * @returns void\n */\n onAgentAction(run) {\n const agentRun = run;\n const crumbs = this.getBreadcrumbs(run);\n console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`);\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/console.js?');
|
|
466
|
+
/***/
|
|
467
|
+
},
|
|
468
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/event_stream.js":
|
|
469
|
+
/*!*******************************************************************!*\
|
|
470
|
+
!*** ./node_modules/@langchain/core/dist/tracers/event_stream.js ***!
|
|
471
|
+
\*******************************************************************/
|
|
472
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
473
|
+
"use strict";
|
|
474
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ EventStreamCallbackHandler: () => (/* binding */ EventStreamCallbackHandler),\n/* harmony export */ isStreamEventsHandler: () => (/* binding */ isStreamEventsHandler)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/tracers/base.js");\n/* harmony import */ var _utils_stream_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n/* harmony import */ var _messages_ai_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../messages/ai.js */ "./node_modules/@langchain/core/dist/messages/ai.js");\n/* harmony import */ var _outputs_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../outputs.js */ "./node_modules/@langchain/core/dist/outputs.js");\n\n\n\n\nfunction assignName({ name, serialized, }) {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n }\n else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return "Unnamed";\n}\nconst isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer";\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nclass EventStreamCallbackHandler extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseTracer {\n constructor(fields) {\n super({ _awaitHandler: true, ...fields });\n Object.defineProperty(this, "autoClose", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "includeNames", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "includeTypes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "includeTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeNames", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeTypes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "runInfoMap", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n Object.defineProperty(this, "tappedPromises", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n Object.defineProperty(this, "transformStream", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "writer", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "receiveStream", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "event_stream_tracer"\n });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream();\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = _utils_stream_js__WEBPACK_IMPORTED_MODULE_1__.IterableReadableStream.fromReadableStream(this.transformStream.readable);\n }\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n async persistRun(_run) {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n _includeRun(run) {\n const runTags = run.tags ?? [];\n let include = this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n async *tapOutputIterable(runId, outputStream) {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don\'t issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send({\n ...event,\n data: { chunk: firstChunk.value },\n }, runInfo);\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don\'t yield tool and retriever stream events\n if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") {\n await this.send({\n ...event,\n data: {\n chunk,\n },\n }, runInfo);\n }\n yield chunk;\n }\n }\n finally {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n tappedPromiseResolver();\n // Don\'t delete from the promises map to keep track of which runs have been tapped.\n }\n }\n else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n async send(payload, run) {\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n async sendEndEvent(payload, run) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n void tappedPromise.then(() => {\n void this.send(payload, run);\n });\n }\n else {\n await this.send(payload, run);\n }\n }\n async onLLMStart(run) {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? "chat_model" : "llm";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send({\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n }, runInfo);\n }\n async onLLMNewToken(run, token, \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs) {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.runType === "chat_model") {\n eventName = "on_chat_model_stream";\n if (kwargs?.chunk === undefined) {\n chunk = new _messages_ai_js__WEBPACK_IMPORTED_MODULE_2__.AIMessageChunk({ content: token });\n }\n else {\n chunk = kwargs.chunk.message;\n }\n }\n else if (runInfo.runType === "llm") {\n eventName = "on_llm_stream";\n if (kwargs?.chunk === undefined) {\n chunk = new _outputs_js__WEBPACK_IMPORTED_MODULE_3__.GenerationChunk({ text: token });\n }\n else {\n chunk = kwargs.chunk;\n }\n }\n else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send({\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n }, runInfo);\n }\n async onLLMEnd(run) {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations = run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output;\n if (runInfo.runType === "chat_model") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = generation[0]?.message;\n }\n eventName = "on_chat_model_end";\n }\n else if (runInfo.runType === "llm") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = "on_llm_end";\n }\n else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent({\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n }, runInfo);\n }\n async onChainStart(run) {\n const runName = assignName(run);\n const runType = run.run_type ?? "chain";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n }\n else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n }\n else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send({\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n }, runInfo);\n }\n async onChainEnd(run) {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent({\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n }, runInfo);\n }\n async onToolStart(run) {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: "tool",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send({\n event: "on_tool_start",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n }, runInfo);\n }\n async onToolEnd(run) {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`);\n }\n const output = run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent({\n event: "on_tool_end",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n }, runInfo);\n }\n async onRetrieverStart(run) {\n const runName = assignName(run);\n const runType = "retriever";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send({\n event: "on_retriever_start",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n }, runInfo);\n }\n async onRetrieverEnd(run) {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent({\n event: "on_retriever_end",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n }, runInfo);\n }\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n void Promise.all(pendingPromises).finally(() => {\n void this.writer.close();\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/event_stream.js?');
|
|
475
|
+
/***/
|
|
476
|
+
},
|
|
477
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/initialize.js":
|
|
478
|
+
/*!*****************************************************************!*\
|
|
479
|
+
!*** ./node_modules/@langchain/core/dist/tracers/initialize.js ***!
|
|
480
|
+
\*****************************************************************/
|
|
481
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
482
|
+
"use strict";
|
|
483
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getTracingCallbackHandler: () => (/* binding */ getTracingCallbackHandler),\n/* harmony export */ getTracingV2CallbackHandler: () => (/* binding */ getTracingV2CallbackHandler)\n/* harmony export */ });\n/* harmony import */ var _tracer_langchain_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tracer_langchain.js */ "./node_modules/@langchain/core/dist/tracers/tracer_langchain.js");\n/* harmony import */ var _tracer_langchain_v1_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tracer_langchain_v1.js */ "./node_modules/@langchain/core/dist/tracers/tracer_langchain_v1.js");\n\n\n/**\n * @deprecated Use the V2 handler instead.\n *\n * Function that returns an instance of `LangChainTracerV1`. If a session\n * is provided, it loads that session into the tracer; otherwise, it loads\n * a default session.\n * @param session Optional session to load into the tracer.\n * @returns An instance of `LangChainTracerV1`.\n */\nasync function getTracingCallbackHandler(session) {\n const tracer = new _tracer_langchain_v1_js__WEBPACK_IMPORTED_MODULE_1__.LangChainTracerV1();\n if (session) {\n await tracer.loadSession(session);\n }\n else {\n await tracer.loadDefaultSession();\n }\n return tracer;\n}\n/**\n * Function that returns an instance of `LangChainTracer`. It does not\n * load any session data.\n * @returns An instance of `LangChainTracer`.\n */\nasync function getTracingV2CallbackHandler() {\n return new _tracer_langchain_js__WEBPACK_IMPORTED_MODULE_0__.LangChainTracer();\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/initialize.js?');
|
|
484
|
+
/***/
|
|
485
|
+
},
|
|
486
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/log_stream.js":
|
|
487
|
+
/*!*****************************************************************!*\
|
|
488
|
+
!*** ./node_modules/@langchain/core/dist/tracers/log_stream.js ***!
|
|
489
|
+
\*****************************************************************/
|
|
490
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
491
|
+
"use strict";
|
|
492
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ LogStreamCallbackHandler: () => (/* binding */ LogStreamCallbackHandler),\n/* harmony export */ RunLog: () => (/* binding */ RunLog),\n/* harmony export */ RunLogPatch: () => (/* binding */ RunLogPatch),\n/* harmony export */ isLogStreamHandler: () => (/* binding */ isLogStreamHandler)\n/* harmony export */ });\n/* harmony import */ var _utils_fast_json_patch_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/fast-json-patch/index.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/tracers/base.js");\n/* harmony import */ var _utils_stream_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n/* harmony import */ var _messages_ai_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../messages/ai.js */ "./node_modules/@langchain/core/dist/messages/ai.js");\n\n\n\n\n/**\n * List of jsonpatch JSONPatchOperations, which describe how to create the run state\n * from an empty dict. This is the minimal representation of the log, designed to\n * be serialized as JSON and sent over the wire to reconstruct the log on the other\n * side. Reconstruction of the state can be done with any jsonpatch-compliant library,\n * see https://jsonpatch.com for more information.\n */\nclass RunLogPatch {\n constructor(fields) {\n Object.defineProperty(this, "ops", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.ops = fields.ops ?? [];\n }\n concat(other) {\n const ops = this.ops.concat(other.ops);\n const states = (0,_utils_fast_json_patch_index_js__WEBPACK_IMPORTED_MODULE_0__.applyPatch)({}, ops);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunLog({\n ops,\n state: states[states.length - 1].newDocument,\n });\n }\n}\nclass RunLog extends RunLogPatch {\n constructor(fields) {\n super(fields);\n Object.defineProperty(this, "state", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.state = fields.state;\n }\n concat(other) {\n const ops = this.ops.concat(other.ops);\n const states = (0,_utils_fast_json_patch_index_js__WEBPACK_IMPORTED_MODULE_0__.applyPatch)(this.state, other.ops);\n return new RunLog({ ops, state: states[states.length - 1].newDocument });\n }\n static fromRunLogPatch(patch) {\n const states = (0,_utils_fast_json_patch_index_js__WEBPACK_IMPORTED_MODULE_0__.applyPatch)({}, patch.ops);\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n return new RunLog({\n ops: patch.ops,\n state: states[states.length - 1].newDocument,\n });\n }\n}\nconst isLogStreamHandler = (handler) => handler.name === "log_stream_tracer";\n/**\n * Extract standardized inputs from a run.\n *\n * Standardizes the inputs based on the type of the runnable used.\n *\n * @param run - Run object\n * @param schemaFormat - The schema format to use.\n *\n * @returns Valid inputs are only dict. By conventions, inputs always represented\n * invocation using named arguments.\n * A null means that the input is not yet known!\n */\nasync function _getStandardizedInputs(run, schemaFormat) {\n if (schemaFormat === "original") {\n throw new Error("Do not assign inputs with original schema drop the key for now. " +\n "When inputs are added to streamLog they should be added with " +\n "standardized schema for streaming events.");\n }\n const { inputs } = run;\n if (["retriever", "llm", "prompt"].includes(run.run_type)) {\n return inputs;\n }\n if (Object.keys(inputs).length === 1 && inputs?.input === "") {\n return undefined;\n }\n // new style chains\n // These nest an additional \'input\' key inside the \'inputs\' to make sure\n // the input is always a dict. We need to unpack and user the inner value.\n // We should try to fix this in Runnables and callbacks/tracers\n // Runnables should be using a null type here not a placeholder\n // dict.\n return inputs.input;\n}\nasync function _getStandardizedOutputs(run, schemaFormat) {\n const { outputs } = run;\n if (schemaFormat === "original") {\n // Return the old schema, without standardizing anything\n return outputs;\n }\n if (["retriever", "llm", "prompt"].includes(run.run_type)) {\n return outputs;\n }\n // TODO: Remove this hacky check\n if (outputs !== undefined &&\n Object.keys(outputs).length === 1 &&\n outputs?.output !== undefined) {\n return outputs.output;\n }\n return outputs;\n}\nfunction isChatGenerationChunk(x) {\n return x !== undefined && x.message !== undefined;\n}\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nclass LogStreamCallbackHandler extends _base_js__WEBPACK_IMPORTED_MODULE_1__.BaseTracer {\n constructor(fields) {\n super({ _awaitHandler: true, ...fields });\n Object.defineProperty(this, "autoClose", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "includeNames", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "includeTypes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "includeTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeNames", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeTypes", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "excludeTags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "_schemaFormat", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "original"\n });\n Object.defineProperty(this, "rootId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "keyMapByRunId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {}\n });\n Object.defineProperty(this, "counterMapByRunName", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {}\n });\n Object.defineProperty(this, "transformStream", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "writer", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "receiveStream", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "log_stream_tracer"\n });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;\n this.transformStream = new TransformStream();\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = _utils_stream_js__WEBPACK_IMPORTED_MODULE_2__.IterableReadableStream.fromReadableStream(this.transformStream.readable);\n }\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n async persistRun(_run) {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n _includeRun(run) {\n if (run.id === this.rootId) {\n return false;\n }\n const runTags = run.tags ?? [];\n let include = this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.run_type);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.run_type);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n async *tapOutputIterable(runId, output) {\n // Tap an output async iterator to stream its values to the log.\n for await (const chunk of output) {\n // root run is handled in .streamLog()\n if (runId !== this.rootId) {\n // if we can\'t find the run silently ignore\n // eg. because this run wasn\'t included in the log\n const key = this.keyMapByRunId[runId];\n if (key) {\n await this.writer.write(new RunLogPatch({\n ops: [\n {\n op: "add",\n path: `/logs/${key}/streamed_output/-`,\n value: chunk,\n },\n ],\n }));\n }\n }\n yield chunk;\n }\n }\n async onRunCreate(run) {\n if (this.rootId === undefined) {\n this.rootId = run.id;\n await this.writer.write(new RunLogPatch({\n ops: [\n {\n op: "replace",\n path: "",\n value: {\n id: run.id,\n name: run.name,\n type: run.run_type,\n streamed_output: [],\n final_output: undefined,\n logs: {},\n },\n },\n ],\n }));\n }\n if (!this._includeRun(run)) {\n return;\n }\n if (this.counterMapByRunName[run.name] === undefined) {\n this.counterMapByRunName[run.name] = 0;\n }\n this.counterMapByRunName[run.name] += 1;\n const count = this.counterMapByRunName[run.name];\n this.keyMapByRunId[run.id] =\n count === 1 ? run.name : `${run.name}:${count}`;\n const logEntry = {\n id: run.id,\n name: run.name,\n type: run.run_type,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n start_time: new Date(run.start_time).toISOString(),\n streamed_output: [],\n streamed_output_str: [],\n final_output: undefined,\n end_time: undefined,\n };\n if (this._schemaFormat === "streaming_events") {\n logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);\n }\n await this.writer.write(new RunLogPatch({\n ops: [\n {\n op: "add",\n path: `/logs/${this.keyMapByRunId[run.id]}`,\n value: logEntry,\n },\n ],\n }));\n }\n async onRunUpdate(run) {\n try {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n const ops = [];\n if (this._schemaFormat === "streaming_events") {\n ops.push({\n op: "replace",\n path: `/logs/${runName}/inputs`,\n value: await _getStandardizedInputs(run, this._schemaFormat),\n });\n }\n ops.push({\n op: "add",\n path: `/logs/${runName}/final_output`,\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n });\n if (run.end_time !== undefined) {\n ops.push({\n op: "add",\n path: `/logs/${runName}/end_time`,\n value: new Date(run.end_time).toISOString(),\n });\n }\n const patch = new RunLogPatch({ ops });\n await this.writer.write(patch);\n }\n finally {\n if (run.id === this.rootId) {\n const patch = new RunLogPatch({\n ops: [\n {\n op: "replace",\n path: "/final_output",\n value: await _getStandardizedOutputs(run, this._schemaFormat),\n },\n ],\n });\n await this.writer.write(patch);\n if (this.autoClose) {\n await this.writer.close();\n }\n }\n }\n }\n async onLLMNewToken(run, token, kwargs) {\n const runName = this.keyMapByRunId[run.id];\n if (runName === undefined) {\n return;\n }\n // TODO: Remove hack\n const isChatModel = run.inputs.messages !== undefined;\n let streamedOutputValue;\n if (isChatModel) {\n if (isChatGenerationChunk(kwargs?.chunk)) {\n streamedOutputValue = kwargs?.chunk;\n }\n else {\n streamedOutputValue = new _messages_ai_js__WEBPACK_IMPORTED_MODULE_3__.AIMessageChunk(token);\n }\n }\n else {\n streamedOutputValue = token;\n }\n const patch = new RunLogPatch({\n ops: [\n {\n op: "add",\n path: `/logs/${runName}/streamed_output_str/-`,\n value: token,\n },\n {\n op: "add",\n path: `/logs/${runName}/streamed_output/-`,\n value: streamedOutputValue,\n },\n ],\n });\n await this.writer.write(patch);\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/log_stream.js?');
|
|
493
|
+
/***/
|
|
494
|
+
},
|
|
495
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/root_listener.js":
|
|
496
|
+
/*!********************************************************************!*\
|
|
497
|
+
!*** ./node_modules/@langchain/core/dist/tracers/root_listener.js ***!
|
|
498
|
+
\********************************************************************/
|
|
499
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
500
|
+
"use strict";
|
|
501
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RootListenersTracer: () => (/* binding */ RootListenersTracer)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/tracers/base.js");\n\nclass RootListenersTracer extends _base_js__WEBPACK_IMPORTED_MODULE_0__.BaseTracer {\n constructor({ config, onStart, onEnd, onError, }) {\n super({ _awaitHandler: true });\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "RootListenersTracer"\n });\n /** The Run\'s ID. Type UUID */\n Object.defineProperty(this, "rootId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "config", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "argOnStart", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "argOnEnd", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "argOnError", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.config = config;\n this.argOnStart = onStart;\n this.argOnEnd = onEnd;\n this.argOnError = onError;\n }\n /**\n * This is a legacy method only called once for an entire run tree\n * therefore not useful here\n * @param {Run} _ Not used\n */\n persistRun(_) {\n return Promise.resolve();\n }\n async onRunCreate(run) {\n if (this.rootId) {\n return;\n }\n this.rootId = run.id;\n if (this.argOnStart) {\n if (this.argOnStart.length === 1) {\n await this.argOnStart(run);\n }\n else if (this.argOnStart.length === 2) {\n await this.argOnStart(run, this.config);\n }\n }\n }\n async onRunUpdate(run) {\n if (run.id !== this.rootId) {\n return;\n }\n if (!run.error) {\n if (this.argOnEnd) {\n if (this.argOnEnd.length === 1) {\n await this.argOnEnd(run);\n }\n else if (this.argOnEnd.length === 2) {\n await this.argOnEnd(run, this.config);\n }\n }\n }\n else if (this.argOnError) {\n if (this.argOnError.length === 1) {\n await this.argOnError(run);\n }\n else if (this.argOnError.length === 2) {\n await this.argOnError(run, this.config);\n }\n }\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/root_listener.js?');
|
|
502
|
+
/***/
|
|
503
|
+
},
|
|
504
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/tracer_langchain.js":
|
|
505
|
+
/*!***********************************************************************!*\
|
|
506
|
+
!*** ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js ***!
|
|
507
|
+
\***********************************************************************/
|
|
508
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
509
|
+
"use strict";
|
|
510
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ LangChainTracer: () => (/* binding */ LangChainTracer)\n/* harmony export */ });\n/* harmony import */ var langsmith__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! langsmith */ "./node_modules/langsmith/index.js");\n/* harmony import */ var langsmith_singletons_traceable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! langsmith/singletons/traceable */ "./node_modules/langsmith/singletons/traceable.js");\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/env.js */ "./node_modules/@langchain/core/dist/utils/env.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/tracers/base.js");\n\n\n\n\nclass LangChainTracer extends _base_js__WEBPACK_IMPORTED_MODULE_3__.BaseTracer {\n constructor(fields = {}) {\n super(fields);\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "langchain_tracer"\n });\n Object.defineProperty(this, "projectName", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "exampleId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "client", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n const { exampleId, projectName, client } = fields;\n this.projectName =\n projectName ??\n (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_PROJECT") ??\n (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_SESSION");\n this.exampleId = exampleId;\n this.client = client ?? new langsmith__WEBPACK_IMPORTED_MODULE_0__.Client({});\n // if we\'re inside traceable, we can obtain the traceable tree\n // and populate the run map, which is used to correctly\n // infer dotted order and execution order\n const traceableTree = this.getTraceableRunTree();\n if (traceableTree) {\n let rootRun = traceableTree;\n const visited = new Set();\n while (rootRun.parent_run) {\n if (visited.has(rootRun.id))\n break;\n visited.add(rootRun.id);\n if (!rootRun.parent_run)\n break;\n rootRun = rootRun.parent_run;\n }\n visited.clear();\n const queue = [rootRun];\n while (queue.length > 0) {\n const current = queue.shift();\n if (!current || visited.has(current.id))\n continue;\n visited.add(current.id);\n // @ts-expect-error Types of property \'events\' are incompatible.\n this.runMap.set(current.id, current);\n if (current.child_runs) {\n queue.push(...current.child_runs);\n }\n }\n this.client = traceableTree.client ?? this.client;\n this.projectName = traceableTree.project_name ?? this.projectName;\n this.exampleId = traceableTree.reference_example_id ?? this.exampleId;\n }\n }\n async _convertToCreate(run, example_id = undefined) {\n return {\n ...run,\n extra: {\n ...run.extra,\n runtime: await (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getRuntimeEnvironment)(),\n },\n child_runs: undefined,\n session_name: this.projectName,\n reference_example_id: run.parent_run_id ? undefined : example_id,\n };\n }\n async persistRun(_run) { }\n async onRunCreate(run) {\n const persistedRun = await this._convertToCreate(run, this.exampleId);\n await this.client.createRun(persistedRun);\n }\n async onRunUpdate(run) {\n const runUpdate = {\n end_time: run.end_time,\n error: run.error,\n outputs: run.outputs,\n events: run.events,\n inputs: run.inputs,\n trace_id: run.trace_id,\n dotted_order: run.dotted_order,\n parent_run_id: run.parent_run_id,\n };\n await this.client.updateRun(run.id, runUpdate);\n }\n getRun(id) {\n return this.runMap.get(id);\n }\n getTraceableRunTree() {\n try {\n return (0,langsmith_singletons_traceable__WEBPACK_IMPORTED_MODULE_1__.getCurrentRunTree)();\n }\n catch {\n return undefined;\n }\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/tracer_langchain.js?');
|
|
511
|
+
/***/
|
|
512
|
+
},
|
|
513
|
+
/***/ "./node_modules/@langchain/core/dist/tracers/tracer_langchain_v1.js":
|
|
514
|
+
/*!**************************************************************************!*\
|
|
515
|
+
!*** ./node_modules/@langchain/core/dist/tracers/tracer_langchain_v1.js ***!
|
|
516
|
+
\**************************************************************************/
|
|
517
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
518
|
+
"use strict";
|
|
519
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ LangChainTracerV1: () => (/* binding */ LangChainTracerV1)\n/* harmony export */ });\n/* harmony import */ var _messages_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../messages/utils.js */ "./node_modules/@langchain/core/dist/messages/utils.js");\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/env.js */ "./node_modules/@langchain/core/dist/utils/env.js");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base.js */ "./node_modules/@langchain/core/dist/tracers/base.js");\n\n\n\n/** @deprecated Use LangChainTracer instead. */\nclass LangChainTracerV1 extends _base_js__WEBPACK_IMPORTED_MODULE_2__.BaseTracer {\n constructor() {\n super();\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: "langchain_tracer"\n });\n Object.defineProperty(this, "endpoint", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_1__.getEnvironmentVariable)("LANGCHAIN_ENDPOINT") || "http://localhost:1984"\n });\n Object.defineProperty(this, "headers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n "Content-Type": "application/json",\n }\n });\n Object.defineProperty(this, "session", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n const apiKey = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_1__.getEnvironmentVariable)("LANGCHAIN_API_KEY");\n if (apiKey) {\n this.headers["x-api-key"] = apiKey;\n }\n }\n async newSession(sessionName) {\n const sessionCreate = {\n start_time: Date.now(),\n name: sessionName,\n };\n const session = await this.persistSession(sessionCreate);\n this.session = session;\n return session;\n }\n async loadSession(sessionName) {\n const endpoint = `${this.endpoint}/sessions?name=${sessionName}`;\n return this._handleSessionResponse(endpoint);\n }\n async loadDefaultSession() {\n const endpoint = `${this.endpoint}/sessions?name=default`;\n return this._handleSessionResponse(endpoint);\n }\n async convertV2RunToRun(run) {\n const session = this.session ?? (await this.loadDefaultSession());\n const serialized = run.serialized;\n let runResult;\n if (run.run_type === "llm") {\n const prompts = run.inputs.prompts\n ? run.inputs.prompts\n : run.inputs.messages.map((x) => (0,_messages_utils_js__WEBPACK_IMPORTED_MODULE_0__.getBufferString)(x));\n const llmRun = {\n uuid: run.id,\n start_time: run.start_time,\n end_time: run.end_time,\n execution_order: run.execution_order,\n child_execution_order: run.child_execution_order,\n serialized,\n type: run.run_type,\n session_id: session.id,\n prompts,\n response: run.outputs,\n };\n runResult = llmRun;\n }\n else if (run.run_type === "chain") {\n const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run)));\n const chainRun = {\n uuid: run.id,\n start_time: run.start_time,\n end_time: run.end_time,\n execution_order: run.execution_order,\n child_execution_order: run.child_execution_order,\n serialized,\n type: run.run_type,\n session_id: session.id,\n inputs: run.inputs,\n outputs: run.outputs,\n child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"),\n child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"),\n child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"),\n };\n runResult = chainRun;\n }\n else if (run.run_type === "tool") {\n const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run)));\n const toolRun = {\n uuid: run.id,\n start_time: run.start_time,\n end_time: run.end_time,\n execution_order: run.execution_order,\n child_execution_order: run.child_execution_order,\n serialized,\n type: run.run_type,\n session_id: session.id,\n tool_input: run.inputs.input,\n output: run.outputs?.output,\n action: JSON.stringify(serialized),\n child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"),\n child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"),\n child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"),\n };\n runResult = toolRun;\n }\n else {\n throw new Error(`Unknown run type: ${run.run_type}`);\n }\n return runResult;\n }\n async persistRun(run) {\n let endpoint;\n let v1Run;\n if (run.run_type !== undefined) {\n v1Run = await this.convertV2RunToRun(run);\n }\n else {\n v1Run = run;\n }\n if (v1Run.type === "llm") {\n endpoint = `${this.endpoint}/llm-runs`;\n }\n else if (v1Run.type === "chain") {\n endpoint = `${this.endpoint}/chain-runs`;\n }\n else {\n endpoint = `${this.endpoint}/tool-runs`;\n }\n const response = await fetch(endpoint, {\n method: "POST",\n headers: this.headers,\n body: JSON.stringify(v1Run),\n });\n if (!response.ok) {\n console.error(`Failed to persist run: ${response.status} ${response.statusText}`);\n }\n }\n async persistSession(sessionCreate) {\n const endpoint = `${this.endpoint}/sessions`;\n const response = await fetch(endpoint, {\n method: "POST",\n headers: this.headers,\n body: JSON.stringify(sessionCreate),\n });\n if (!response.ok) {\n console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`);\n return {\n id: 1,\n ...sessionCreate,\n };\n }\n return {\n id: (await response.json()).id,\n ...sessionCreate,\n };\n }\n async _handleSessionResponse(endpoint) {\n const response = await fetch(endpoint, {\n method: "GET",\n headers: this.headers,\n });\n let tracerSession;\n if (!response.ok) {\n console.error(`Failed to load session: ${response.status} ${response.statusText}`);\n tracerSession = {\n id: 1,\n start_time: Date.now(),\n };\n this.session = tracerSession;\n return tracerSession;\n }\n const resp = (await response.json());\n if (resp.length === 0) {\n tracerSession = {\n id: 1,\n start_time: Date.now(),\n };\n this.session = tracerSession;\n return tracerSession;\n }\n [tracerSession] = resp;\n this.session = tracerSession;\n return tracerSession;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/tracers/tracer_langchain_v1.js?');
|
|
520
|
+
/***/
|
|
521
|
+
},
|
|
522
|
+
/***/ "./node_modules/@langchain/core/dist/utils/async_caller.js":
|
|
523
|
+
/*!*****************************************************************!*\
|
|
524
|
+
!*** ./node_modules/@langchain/core/dist/utils/async_caller.js ***!
|
|
525
|
+
\*****************************************************************/
|
|
526
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
527
|
+
"use strict";
|
|
528
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncCaller: () => (/* binding */ AsyncCaller)\n/* harmony export */ });\n/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-retry */ "./node_modules/p-retry/index.js");\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-queue */ "./node_modules/p-queue/dist/index.js");\n\n\nconst STATUS_NO_RETRY = [\n 400,\n 401,\n 402,\n 403,\n 404,\n 405,\n 406,\n 407,\n 409, // Conflict\n];\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst defaultFailedAttemptHandler = (error) => {\n if (error.message.startsWith("Cancel") ||\n error.message.startsWith("AbortError") ||\n error.name === "AbortError") {\n throw error;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (error?.code === "ECONNABORTED") {\n throw error;\n }\n const status = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n error?.response?.status ?? error?.status;\n if (status && STATUS_NO_RETRY.includes(+status)) {\n throw error;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (error?.error?.code === "insufficient_quota") {\n const err = new Error(error?.message);\n err.name = "InsufficientQuotaError";\n throw err;\n }\n};\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of "expensive" external resource,\n * be it because it\'s rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nclass AsyncCaller {\n constructor(params) {\n Object.defineProperty(this, "maxConcurrency", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "maxRetries", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "onFailedAttempt", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "queue", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n this.onFailedAttempt =\n params.onFailedAttempt ?? defaultFailedAttemptHandler;\n const PQueue = true ? p_queue__WEBPACK_IMPORTED_MODULE_1__["default"] : p_queue__WEBPACK_IMPORTED_MODULE_1__;\n this.queue = new PQueue({ concurrency: this.maxConcurrency });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n call(callable, ...args) {\n return this.queue.add(() => p_retry__WEBPACK_IMPORTED_MODULE_0__(() => callable(...args).catch((error) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n }\n else {\n throw new Error(error);\n }\n }), {\n onFailedAttempt: this.onFailedAttempt,\n retries: this.maxRetries,\n randomize: true,\n // If needed we can change some of the defaults here,\n // but they\'re quite sensible.\n }), { throwOnTimeout: true });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions(options, callable, ...args) {\n // Note this doesn\'t cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n return Promise.race([\n this.call(callable, ...args),\n new Promise((_, reject) => {\n options.signal?.addEventListener("abort", () => {\n reject(new Error("AbortError"));\n });\n }),\n ]);\n }\n return this.call(callable, ...args);\n }\n fetch(...args) {\n return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res))));\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/async_caller.js?');
|
|
529
|
+
/***/
|
|
530
|
+
},
|
|
531
|
+
/***/ "./node_modules/@langchain/core/dist/utils/env.js":
|
|
532
|
+
/*!********************************************************!*\
|
|
533
|
+
!*** ./node_modules/@langchain/core/dist/utils/env.js ***!
|
|
534
|
+
\********************************************************/
|
|
535
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
536
|
+
"use strict";
|
|
537
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getEnv: () => (/* binding */ getEnv),\n/* harmony export */ getEnvironmentVariable: () => (/* binding */ getEnvironmentVariable),\n/* harmony export */ getRuntimeEnvironment: () => (/* binding */ getRuntimeEnvironment),\n/* harmony export */ isBrowser: () => (/* binding */ isBrowser),\n/* harmony export */ isDeno: () => (/* binding */ isDeno),\n/* harmony export */ isJsDom: () => (/* binding */ isJsDom),\n/* harmony export */ isNode: () => (/* binding */ isNode),\n/* harmony export */ isWebWorker: () => (/* binding */ isWebWorker)\n/* harmony export */ });\nconst isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";\nconst isWebWorker = () => typeof globalThis === "object" &&\n globalThis.constructor &&\n globalThis.constructor.name === "DedicatedWorkerGlobalScope";\nconst isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") ||\n (typeof navigator !== "undefined" &&\n (navigator.userAgent.includes("Node.js") ||\n navigator.userAgent.includes("jsdom")));\n// Supabase Edge Function provides a `Deno` global object\n// without `version` property\nconst isDeno = () => typeof Deno !== "undefined";\n// Mark not-as-node if in Supabase Edge Function\nconst isNode = () => typeof process !== "undefined" &&\n typeof process.versions !== "undefined" &&\n typeof process.versions.node !== "undefined" &&\n !isDeno();\nconst getEnv = () => {\n let env;\n if (isBrowser()) {\n env = "browser";\n }\n else if (isNode()) {\n env = "node";\n }\n else if (isWebWorker()) {\n env = "webworker";\n }\n else if (isJsDom()) {\n env = "jsdom";\n }\n else if (isDeno()) {\n env = "deno";\n }\n else {\n env = "other";\n }\n return env;\n};\nlet runtimeEnvironment;\nasync function getRuntimeEnvironment() {\n if (runtimeEnvironment === undefined) {\n const env = getEnv();\n runtimeEnvironment = {\n library: "langchain-js",\n runtime: env,\n };\n }\n return runtimeEnvironment;\n}\nfunction getEnvironmentVariable(name) {\n // Certain Deno setups will throw an error if you try to access environment variables\n // https://github.com/langchain-ai/langchainjs/issues/1412\n try {\n return typeof process !== "undefined"\n ? // eslint-disable-next-line no-process-env\n process.env?.[name]\n : undefined;\n }\n catch (e) {\n return undefined;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/env.js?');
|
|
538
|
+
/***/
|
|
539
|
+
},
|
|
540
|
+
/***/ "./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js":
|
|
541
|
+
/*!**************************************************************************!*\
|
|
542
|
+
!*** ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js ***!
|
|
543
|
+
\**************************************************************************/
|
|
544
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
545
|
+
"use strict";
|
|
546
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ JsonPatchError: () => (/* reexport safe */ _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__.PatchError),\n/* harmony export */ _areEquals: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__._areEquals),\n/* harmony export */ applyOperation: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__.applyOperation),\n/* harmony export */ applyPatch: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__.applyPatch),\n/* harmony export */ applyReducer: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__.applyReducer),\n/* harmony export */ compare: () => (/* reexport safe */ _src_duplex_js__WEBPACK_IMPORTED_MODULE_1__.compare),\n/* harmony export */ deepClone: () => (/* reexport safe */ _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__._deepClone),\n/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ escapePathComponent: () => (/* reexport safe */ _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__.escapePathComponent),\n/* harmony export */ generate: () => (/* reexport safe */ _src_duplex_js__WEBPACK_IMPORTED_MODULE_1__.generate),\n/* harmony export */ getValueByPointer: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__.getValueByPointer),\n/* harmony export */ observe: () => (/* reexport safe */ _src_duplex_js__WEBPACK_IMPORTED_MODULE_1__.observe),\n/* harmony export */ unescapePathComponent: () => (/* reexport safe */ _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__.unescapePathComponent),\n/* harmony export */ unobserve: () => (/* reexport safe */ _src_duplex_js__WEBPACK_IMPORTED_MODULE_1__.unobserve),\n/* harmony export */ validate: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__.validate),\n/* harmony export */ validator: () => (/* reexport safe */ _src_core_js__WEBPACK_IMPORTED_MODULE_0__.validator)\n/* harmony export */ });\n/* harmony import */ var _src_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/core.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js");\n/* harmony import */ var _src_duplex_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./src/duplex.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js");\n/* harmony import */ var _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./src/helpers.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js");\n\n\n\n/**\n * Default export for backwards compat\n */\n\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n ..._src_core_js__WEBPACK_IMPORTED_MODULE_0__,\n // ...duplex,\n JsonPatchError: _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__.PatchError,\n deepClone: _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__._deepClone,\n escapePathComponent: _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__.escapePathComponent,\n unescapePathComponent: _src_helpers_js__WEBPACK_IMPORTED_MODULE_2__.unescapePathComponent,\n});\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js?');
|
|
547
|
+
/***/
|
|
548
|
+
},
|
|
549
|
+
/***/ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js":
|
|
550
|
+
/*!*****************************************************************************!*\
|
|
551
|
+
!*** ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js ***!
|
|
552
|
+
\*****************************************************************************/
|
|
553
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
554
|
+
"use strict";
|
|
555
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ JsonPatchError: () => (/* binding */ JsonPatchError),\n/* harmony export */ _areEquals: () => (/* binding */ _areEquals),\n/* harmony export */ applyOperation: () => (/* binding */ applyOperation),\n/* harmony export */ applyPatch: () => (/* binding */ applyPatch),\n/* harmony export */ applyReducer: () => (/* binding */ applyReducer),\n/* harmony export */ deepClone: () => (/* binding */ deepClone),\n/* harmony export */ getValueByPointer: () => (/* binding */ getValueByPointer),\n/* harmony export */ validate: () => (/* binding */ validate),\n/* harmony export */ validator: () => (/* binding */ validator)\n/* harmony export */ });\n/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js");\n// @ts-nocheck\n\nconst JsonPatchError = _helpers_js__WEBPACK_IMPORTED_MODULE_0__.PatchError;\nconst deepClone = _helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone;\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n/* The operations applicable to an object */\nconst objOps = {\n add: function (obj, key, document) {\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed };\n },\n replace: function (obj, key, document) {\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n let removed = getValueByPointer(document, this.path);\n if (removed) {\n removed = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(removed);\n }\n const originalValue = applyOperation(document, {\n op: "remove",\n path: this.from,\n }).removed;\n applyOperation(document, {\n op: "add",\n path: this.path,\n value: originalValue,\n });\n return { newDocument: document, removed };\n },\n copy: function (obj, key, document) {\n const valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don\'t affect source (see issue #177)\n applyOperation(document, {\n op: "add",\n path: this.path,\n value: (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(valueToCopy),\n });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n },\n};\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if ((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.isInteger)(i)) {\n arr.splice(i, 0, this.value);\n }\n else {\n // array props\n arr[i] = this.value;\n }\n // this may be needed when using \'-\' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get,\n};\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nfunction getValueByPointer(document, pointer) {\n if (pointer == "") {\n return document;\n }\n var getOriginalDestination = { op: "_get", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch\'s validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nfunction applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) {\n if (validateOperation) {\n if (typeof validateOperation == "function") {\n validateOperation(operation, 0, document, operation.path);\n }\n else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === "") {\n let returnValue = { newDocument: document };\n if (operation.op === "add") {\n returnValue.newDocument = operation.value;\n return returnValue;\n }\n else if (operation.op === "replace") {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n }\n else if (operation.op === "move" || operation.op === "copy") {\n // it\'s a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === "move") {\n // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n }\n else if (operation.op === "test") {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);\n }\n returnValue.newDocument = document;\n return returnValue;\n }\n else if (operation.op === "remove") {\n // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n }\n else if (operation.op === "_get") {\n operation.value = document;\n return returnValue;\n }\n else {\n /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document);\n }\n else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */\n else {\n if (!mutateDocument) {\n document = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(document);\n }\n const path = operation.path || "";\n const keys = path.split("/");\n let obj = document;\n let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n let len = keys.length;\n let existingPathFragment = undefined;\n let key;\n let validateFunction;\n if (typeof validateOperation == "function") {\n validateFunction = validateOperation;\n }\n else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf("~") != -1) {\n key = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.unescapePathComponent)(key);\n }\n if (banPrototypeModifications &&\n (key == "__proto__" ||\n (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) {\n 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");\n }\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join("/");\n }\n else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === "-") {\n key = obj.length;\n }\n else {\n if (validateOperation && !(0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.isInteger)(key)) {\n throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document);\n } // only parse key when it\'s an integer for `arr.prop` to work\n else if ((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.isInteger)(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === "add" && key > obj.length) {\n throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document);\n }\n const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);\n }\n return returnValue;\n }\n }\n else {\n if (t >= len) {\n const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn\'t a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== "object")) {\n throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document);\n }\n }\n }\n}\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch\'s validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nfunction applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) {\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");\n }\n }\n if (!mutateDocument) {\n document = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(document);\n }\n const results = new Array(patch.length);\n for (let i = 0, length = patch.length; i < length; i++) {\n // we don\'t need to pass mutateDocument argument because if it was true, we already deep cloned the object, we\'ll just pass `true`\n results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nfunction applyReducer(document, operation, index) {\n const operationResult = applyOperation(document, operation);\n if (operationResult.test === false) {\n // failed test\n throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document);\n }\n return operationResult.newDocument;\n}\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nfunction validator(operation, index, document, existingPathFragment) {\n if (typeof operation !== "object" ||\n operation === null ||\n Array.isArray(operation)) {\n throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document);\n }\n else if (!objOps[operation.op]) {\n throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document);\n }\n else if (typeof operation.path !== "string") {\n throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document);\n }\n else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) {\n // paths that aren\'t empty string should start with "/"\n throw new JsonPatchError(\'Operation `path` property must start with "/"\', "OPERATION_PATH_INVALID", index, operation, document);\n }\n else if ((operation.op === "move" || operation.op === "copy") &&\n typeof operation.from !== "string") {\n throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document);\n }\n else if ((operation.op === "add" ||\n operation.op === "replace" ||\n operation.op === "test") &&\n operation.value === undefined) {\n throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document);\n }\n else if ((operation.op === "add" ||\n operation.op === "replace" ||\n operation.op === "test") &&\n (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.hasUndefined)(operation.value)) {\n throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document);\n }\n else if (document) {\n if (operation.op == "add") {\n var pathLen = operation.path.split("/").length;\n var existingPathLen = existingPathFragment.split("/").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document);\n }\n }\n else if (operation.op === "replace" ||\n operation.op === "remove" ||\n operation.op === "_get") {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document);\n }\n }\n else if (operation.op === "move" || operation.op === "copy") {\n var existingValue = {\n op: "_get",\n path: operation.from,\n value: undefined,\n };\n var error = validate([existingValue], document);\n if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") {\n throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document);\n }\n }\n }\n}\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nfunction validate(sequence, document, externalValidator) {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(document), (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(sequence), externalValidator || true);\n }\n else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n }\n catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n }\n else {\n throw e;\n }\n }\n}\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n// Copyright (c) 2017 Evgeny Poberezkin\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the "Software"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nfunction _areEquals(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == "object" && typeof b == "object") {\n var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!_areEquals(a[i], b[i]))\n return false;\n return true;\n }\n if (arrA != arrB)\n return false;\n var keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!b.hasOwnProperty(keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!_areEquals(a[key], b[key]))\n return false;\n }\n return true;\n }\n return a !== a && b !== b;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js?');
|
|
556
|
+
/***/
|
|
557
|
+
},
|
|
558
|
+
/***/ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js":
|
|
559
|
+
/*!*******************************************************************************!*\
|
|
560
|
+
!*** ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js ***!
|
|
561
|
+
\*******************************************************************************/
|
|
562
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
563
|
+
"use strict";
|
|
564
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compare: () => (/* binding */ compare),\n/* harmony export */ generate: () => (/* binding */ generate),\n/* harmony export */ observe: () => (/* binding */ observe),\n/* harmony export */ unobserve: () => (/* binding */ unobserve)\n/* harmony export */ });\n/* harmony import */ var _helpers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js");\n/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./core.js */ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js");\n// @ts-nocheck\n// Inlined because of ESM import issues\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2013-2021 Joachim Wester\n * MIT license\n */\n\n\nvar beforeDict = new WeakMap();\nclass Mirror {\n constructor(obj) {\n Object.defineProperty(this, "obj", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "observers", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Map()\n });\n Object.defineProperty(this, "value", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.obj = obj;\n }\n}\nclass ObserverInfo {\n constructor(callback, observer) {\n Object.defineProperty(this, "callback", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "observer", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.callback = callback;\n this.observer = observer;\n }\n}\nfunction getMirror(obj) {\n return beforeDict.get(obj);\n}\nfunction getObserverFromMirror(mirror, callback) {\n return mirror.observers.get(callback);\n}\nfunction removeObserverFromMirror(mirror, observer) {\n mirror.observers.delete(observer.callback);\n}\n/**\n * Detach an observer from an object\n */\nfunction unobserve(root, observer) {\n observer.unobserve();\n}\n/**\n * Observes changes made to an object, which can then be retrieved using generate\n */\nfunction observe(obj, callback) {\n var patches = [];\n var observer;\n var mirror = getMirror(obj);\n if (!mirror) {\n mirror = new Mirror(obj);\n beforeDict.set(obj, mirror);\n }\n else {\n const observerInfo = getObserverFromMirror(mirror, callback);\n observer = observerInfo && observerInfo.observer;\n }\n if (observer) {\n return observer;\n }\n observer = {};\n mirror.value = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(obj);\n if (callback) {\n observer.callback = callback;\n observer.next = null;\n var dirtyCheck = () => {\n generate(observer);\n };\n var fastCheck = () => {\n clearTimeout(observer.next);\n observer.next = setTimeout(dirtyCheck);\n };\n if (typeof window !== "undefined") {\n //not Node\n window.addEventListener("mouseup", fastCheck);\n window.addEventListener("keyup", fastCheck);\n window.addEventListener("mousedown", fastCheck);\n window.addEventListener("keydown", fastCheck);\n window.addEventListener("change", fastCheck);\n }\n }\n observer.patches = patches;\n observer.object = obj;\n observer.unobserve = () => {\n generate(observer);\n clearTimeout(observer.next);\n removeObserverFromMirror(mirror, observer);\n if (typeof window !== "undefined") {\n window.removeEventListener("mouseup", fastCheck);\n window.removeEventListener("keyup", fastCheck);\n window.removeEventListener("mousedown", fastCheck);\n window.removeEventListener("keydown", fastCheck);\n window.removeEventListener("change", fastCheck);\n }\n };\n mirror.observers.set(callback, new ObserverInfo(callback, observer));\n return observer;\n}\n/**\n * Generate an array of patches from an observer\n */\nfunction generate(observer, invertible = false) {\n var mirror = beforeDict.get(observer.object);\n _generate(mirror.value, observer.object, observer.patches, "", invertible);\n if (observer.patches.length) {\n (0,_core_js__WEBPACK_IMPORTED_MODULE_1__.applyPatch)(mirror.value, observer.patches);\n }\n var temp = observer.patches;\n if (temp.length > 0) {\n observer.patches = [];\n if (observer.callback) {\n observer.callback(temp);\n }\n }\n return temp;\n}\n// Dirty check if obj is different from mirror, generate patches and update mirror\nfunction _generate(mirror, obj, patches, path, invertible) {\n if (obj === mirror) {\n return;\n }\n if (typeof obj.toJSON === "function") {\n obj = obj.toJSON();\n }\n var newKeys = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._objectKeys)(obj);\n var oldKeys = (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._objectKeys)(mirror);\n var changed = false;\n var deleted = false;\n //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)"\n for (var t = oldKeys.length - 1; t >= 0; t--) {\n var key = oldKeys[t];\n var oldVal = mirror[key];\n if ((0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.hasOwnProperty)(obj, key) &&\n !(obj[key] === undefined &&\n oldVal !== undefined &&\n Array.isArray(obj) === false)) {\n var newVal = obj[key];\n if (typeof oldVal == "object" &&\n oldVal != null &&\n typeof newVal == "object" &&\n newVal != null &&\n Array.isArray(oldVal) === Array.isArray(newVal)) {\n _generate(oldVal, newVal, patches, path + "/" + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.escapePathComponent)(key), invertible);\n }\n else {\n if (oldVal !== newVal) {\n changed = true;\n if (invertible) {\n patches.push({\n op: "test",\n path: path + "/" + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.escapePathComponent)(key),\n value: (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(oldVal),\n });\n }\n patches.push({\n op: "replace",\n path: path + "/" + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.escapePathComponent)(key),\n value: (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(newVal),\n });\n }\n }\n }\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\n if (invertible) {\n patches.push({\n op: "test",\n path: path + "/" + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.escapePathComponent)(key),\n value: (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(oldVal),\n });\n }\n patches.push({\n op: "remove",\n path: path + "/" + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.escapePathComponent)(key),\n });\n deleted = true; // property has been deleted\n }\n else {\n if (invertible) {\n patches.push({ op: "test", path, value: mirror });\n }\n patches.push({ op: "replace", path, value: obj });\n changed = true;\n }\n }\n if (!deleted && newKeys.length == oldKeys.length) {\n return;\n }\n for (var t = 0; t < newKeys.length; t++) {\n var key = newKeys[t];\n if (!(0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.hasOwnProperty)(mirror, key) && obj[key] !== undefined) {\n patches.push({\n op: "add",\n path: path + "/" + (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__.escapePathComponent)(key),\n value: (0,_helpers_js__WEBPACK_IMPORTED_MODULE_0__._deepClone)(obj[key]),\n });\n }\n }\n}\n/**\n * Create an array of patches from the differences in two objects\n */\nfunction compare(tree1, tree2, invertible = false) {\n var patches = [];\n _generate(tree1, tree2, patches, "", invertible);\n return patches;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js?');
|
|
565
|
+
/***/
|
|
566
|
+
},
|
|
567
|
+
/***/ "./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js":
|
|
568
|
+
/*!********************************************************************************!*\
|
|
569
|
+
!*** ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js ***!
|
|
570
|
+
\********************************************************************************/
|
|
571
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
572
|
+
"use strict";
|
|
573
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PatchError: () => (/* binding */ PatchError),\n/* harmony export */ _deepClone: () => (/* binding */ _deepClone),\n/* harmony export */ _getPathRecursive: () => (/* binding */ _getPathRecursive),\n/* harmony export */ _objectKeys: () => (/* binding */ _objectKeys),\n/* harmony export */ escapePathComponent: () => (/* binding */ escapePathComponent),\n/* harmony export */ getPath: () => (/* binding */ getPath),\n/* harmony export */ hasOwnProperty: () => (/* binding */ hasOwnProperty),\n/* harmony export */ hasUndefined: () => (/* binding */ hasUndefined),\n/* harmony export */ isInteger: () => (/* binding */ isInteger),\n/* harmony export */ unescapePathComponent: () => (/* binding */ unescapePathComponent)\n/* harmony export */ });\n// @ts-nocheck\n// Inlined because of ESM import issues\n/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017-2022 Joachim Wester\n * MIT licensed\n */\nconst _hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction hasOwnProperty(obj, key) {\n return _hasOwnProperty.call(obj, key);\n}\nfunction _objectKeys(obj) {\n if (Array.isArray(obj)) {\n const keys = new Array(obj.length);\n for (let k = 0; k < keys.length; k++) {\n keys[k] = "" + k;\n }\n return keys;\n }\n if (Object.keys) {\n return Object.keys(obj);\n }\n let keys = [];\n for (let i in obj) {\n if (hasOwnProperty(obj, i)) {\n keys.push(i);\n }\n }\n return keys;\n}\n/**\n * Deeply clone the object.\n * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)\n * @param {any} obj value to clone\n * @return {any} cloned obj\n */\nfunction _deepClone(obj) {\n switch (typeof obj) {\n case "object":\n return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5\n case "undefined":\n return null; //this is how JSON.stringify behaves for array items\n default:\n return obj; //no need to clone primitives\n }\n}\n//3x faster than cached /^\\d+$/.test(str)\nfunction isInteger(str) {\n let i = 0;\n const len = str.length;\n let charCode;\n while (i < len) {\n charCode = str.charCodeAt(i);\n if (charCode >= 48 && charCode <= 57) {\n i++;\n continue;\n }\n return false;\n }\n return true;\n}\n/**\n * Escapes a json pointer path\n * @param path The raw pointer\n * @return the Escaped path\n */\nfunction escapePathComponent(path) {\n if (path.indexOf("/") === -1 && path.indexOf("~") === -1)\n return path;\n return path.replace(/~/g, "~0").replace(/\\//g, "~1");\n}\n/**\n * Unescapes a json pointer path\n * @param path The escaped pointer\n * @return The unescaped path\n */\nfunction unescapePathComponent(path) {\n return path.replace(/~1/g, "/").replace(/~0/g, "~");\n}\nfunction _getPathRecursive(root, obj) {\n let found;\n for (let key in root) {\n if (hasOwnProperty(root, key)) {\n if (root[key] === obj) {\n return escapePathComponent(key) + "/";\n }\n else if (typeof root[key] === "object") {\n found = _getPathRecursive(root[key], obj);\n if (found != "") {\n return escapePathComponent(key) + "/" + found;\n }\n }\n }\n }\n return "";\n}\nfunction getPath(root, obj) {\n if (root === obj) {\n return "/";\n }\n const path = _getPathRecursive(root, obj);\n if (path === "") {\n throw new Error("Object not found in root");\n }\n return `/${path}`;\n}\n/**\n * Recursively checks whether an object has any undefined values inside.\n */\nfunction hasUndefined(obj) {\n if (obj === undefined) {\n return true;\n }\n if (obj) {\n if (Array.isArray(obj)) {\n for (let i = 0, len = obj.length; i < len; i++) {\n if (hasUndefined(obj[i])) {\n return true;\n }\n }\n }\n else if (typeof obj === "object") {\n const objKeys = _objectKeys(obj);\n const objKeysLength = objKeys.length;\n for (var i = 0; i < objKeysLength; i++) {\n if (hasUndefined(obj[objKeys[i]])) {\n return true;\n }\n }\n }\n }\n return false;\n}\nfunction patchErrorMessageFormatter(message, args) {\n const messageParts = [message];\n for (const key in args) {\n const value = typeof args[key] === "object"\n ? JSON.stringify(args[key], null, 2)\n : args[key]; // pretty print\n if (typeof value !== "undefined") {\n messageParts.push(`${key}: ${value}`);\n }\n }\n return messageParts.join("\\n");\n}\nclass PatchError extends Error {\n constructor(message, name, index, operation, tree) {\n super(patchErrorMessageFormatter(message, { name, index, operation, tree }));\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: name\n });\n Object.defineProperty(this, "index", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: index\n });\n Object.defineProperty(this, "operation", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: operation\n });\n Object.defineProperty(this, "tree", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: tree\n });\n Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359\n this.message = patchErrorMessageFormatter(message, {\n name,\n index,\n operation,\n tree,\n });\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js?');
|
|
574
|
+
/***/
|
|
575
|
+
},
|
|
576
|
+
/***/ "./node_modules/@langchain/core/dist/utils/hash.js":
|
|
577
|
+
/*!*********************************************************!*\
|
|
578
|
+
!*** ./node_modules/@langchain/core/dist/utils/hash.js ***!
|
|
579
|
+
\*********************************************************/
|
|
580
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
581
|
+
"use strict";
|
|
582
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ insecureHash: () => (/* reexport safe */ _js_sha1_hash_js__WEBPACK_IMPORTED_MODULE_0__.insecureHash)\n/* harmony export */ });\n/* harmony import */ var _js_sha1_hash_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./js-sha1/hash.js */ "./node_modules/@langchain/core/dist/utils/js-sha1/hash.js");\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/hash.js?');
|
|
583
|
+
/***/
|
|
584
|
+
},
|
|
585
|
+
/***/ "./node_modules/@langchain/core/dist/utils/js-sha1/hash.js":
|
|
586
|
+
/*!*****************************************************************!*\
|
|
587
|
+
!*** ./node_modules/@langchain/core/dist/utils/js-sha1/hash.js ***!
|
|
588
|
+
\*****************************************************************/
|
|
589
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
590
|
+
"use strict";
|
|
591
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ insecureHash: () => (/* binding */ insecureHash)\n/* harmony export */ });\n// @ts-nocheck\n// Inlined to deal with portability issues with importing crypto module\n/*\n * [js-sha1]{@link https://github.com/emn178/js-sha1}\n *\n * @version 0.6.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2014-2017\n * @license MIT\n */\n/*jslint bitwise: true */\n\nvar root = typeof window === "object" ? window : {};\nvar HEX_CHARS = "0123456789abcdef".split("");\nvar EXTRA = [-2147483648, 8388608, 32768, 128];\nvar SHIFT = [24, 16, 8, 0];\nvar OUTPUT_TYPES = ["hex", "array", "digest", "arrayBuffer"];\nvar blocks = [];\nfunction Sha1(sharedMemory) {\n if (sharedMemory) {\n blocks[0] =\n blocks[16] =\n blocks[1] =\n blocks[2] =\n blocks[3] =\n blocks[4] =\n blocks[5] =\n blocks[6] =\n blocks[7] =\n blocks[8] =\n blocks[9] =\n blocks[10] =\n blocks[11] =\n blocks[12] =\n blocks[13] =\n blocks[14] =\n blocks[15] =\n 0;\n this.blocks = blocks;\n }\n else {\n this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n }\n this.h0 = 0x67452301;\n this.h1 = 0xefcdab89;\n this.h2 = 0x98badcfe;\n this.h3 = 0x10325476;\n this.h4 = 0xc3d2e1f0;\n this.block = this.start = this.bytes = this.hBytes = 0;\n this.finalized = this.hashed = false;\n this.first = true;\n}\nSha1.prototype.update = function (message) {\n if (this.finalized) {\n return;\n }\n var notString = typeof message !== "string";\n if (notString && message.constructor === root.ArrayBuffer) {\n message = new Uint8Array(message);\n }\n var code, index = 0, i, length = message.length || 0, blocks = this.blocks;\n while (index < length) {\n if (this.hashed) {\n this.hashed = false;\n blocks[0] = this.block;\n blocks[16] =\n blocks[1] =\n blocks[2] =\n blocks[3] =\n blocks[4] =\n blocks[5] =\n blocks[6] =\n blocks[7] =\n blocks[8] =\n blocks[9] =\n blocks[10] =\n blocks[11] =\n blocks[12] =\n blocks[13] =\n blocks[14] =\n blocks[15] =\n 0;\n }\n if (notString) {\n for (i = this.start; index < length && i < 64; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n }\n else {\n for (i = this.start; index < length && i < 64; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n }\n else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n else {\n code =\n 0x10000 +\n (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n }\n this.lastByteIndex = i;\n this.bytes += i - this.start;\n if (i >= 64) {\n this.block = blocks[16];\n this.start = i - 64;\n this.hash();\n this.hashed = true;\n }\n else {\n this.start = i;\n }\n }\n if (this.bytes > 4294967295) {\n this.hBytes += (this.bytes / 4294967296) << 0;\n this.bytes = this.bytes % 4294967296;\n }\n return this;\n};\nSha1.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex;\n blocks[16] = this.block;\n blocks[i >> 2] |= EXTRA[i & 3];\n this.block = blocks[16];\n if (i >= 56) {\n if (!this.hashed) {\n this.hash();\n }\n blocks[0] = this.block;\n blocks[16] =\n blocks[1] =\n blocks[2] =\n blocks[3] =\n blocks[4] =\n blocks[5] =\n blocks[6] =\n blocks[7] =\n blocks[8] =\n blocks[9] =\n blocks[10] =\n blocks[11] =\n blocks[12] =\n blocks[13] =\n blocks[14] =\n blocks[15] =\n 0;\n }\n blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29);\n blocks[15] = this.bytes << 3;\n this.hash();\n};\nSha1.prototype.hash = function () {\n var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4;\n var f, j, t, blocks = this.blocks;\n for (j = 16; j < 80; ++j) {\n t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16];\n blocks[j] = (t << 1) | (t >>> 31);\n }\n for (j = 0; j < 20; j += 5) {\n f = (b & c) | (~b & d);\n t = (a << 5) | (a >>> 27);\n e = (t + f + e + 1518500249 + blocks[j]) << 0;\n b = (b << 30) | (b >>> 2);\n f = (a & b) | (~a & c);\n t = (e << 5) | (e >>> 27);\n d = (t + f + d + 1518500249 + blocks[j + 1]) << 0;\n a = (a << 30) | (a >>> 2);\n f = (e & a) | (~e & b);\n t = (d << 5) | (d >>> 27);\n c = (t + f + c + 1518500249 + blocks[j + 2]) << 0;\n e = (e << 30) | (e >>> 2);\n f = (d & e) | (~d & a);\n t = (c << 5) | (c >>> 27);\n b = (t + f + b + 1518500249 + blocks[j + 3]) << 0;\n d = (d << 30) | (d >>> 2);\n f = (c & d) | (~c & e);\n t = (b << 5) | (b >>> 27);\n a = (t + f + a + 1518500249 + blocks[j + 4]) << 0;\n c = (c << 30) | (c >>> 2);\n }\n for (; j < 40; j += 5) {\n f = b ^ c ^ d;\n t = (a << 5) | (a >>> 27);\n e = (t + f + e + 1859775393 + blocks[j]) << 0;\n b = (b << 30) | (b >>> 2);\n f = a ^ b ^ c;\n t = (e << 5) | (e >>> 27);\n d = (t + f + d + 1859775393 + blocks[j + 1]) << 0;\n a = (a << 30) | (a >>> 2);\n f = e ^ a ^ b;\n t = (d << 5) | (d >>> 27);\n c = (t + f + c + 1859775393 + blocks[j + 2]) << 0;\n e = (e << 30) | (e >>> 2);\n f = d ^ e ^ a;\n t = (c << 5) | (c >>> 27);\n b = (t + f + b + 1859775393 + blocks[j + 3]) << 0;\n d = (d << 30) | (d >>> 2);\n f = c ^ d ^ e;\n t = (b << 5) | (b >>> 27);\n a = (t + f + a + 1859775393 + blocks[j + 4]) << 0;\n c = (c << 30) | (c >>> 2);\n }\n for (; j < 60; j += 5) {\n f = (b & c) | (b & d) | (c & d);\n t = (a << 5) | (a >>> 27);\n e = (t + f + e - 1894007588 + blocks[j]) << 0;\n b = (b << 30) | (b >>> 2);\n f = (a & b) | (a & c) | (b & c);\n t = (e << 5) | (e >>> 27);\n d = (t + f + d - 1894007588 + blocks[j + 1]) << 0;\n a = (a << 30) | (a >>> 2);\n f = (e & a) | (e & b) | (a & b);\n t = (d << 5) | (d >>> 27);\n c = (t + f + c - 1894007588 + blocks[j + 2]) << 0;\n e = (e << 30) | (e >>> 2);\n f = (d & e) | (d & a) | (e & a);\n t = (c << 5) | (c >>> 27);\n b = (t + f + b - 1894007588 + blocks[j + 3]) << 0;\n d = (d << 30) | (d >>> 2);\n f = (c & d) | (c & e) | (d & e);\n t = (b << 5) | (b >>> 27);\n a = (t + f + a - 1894007588 + blocks[j + 4]) << 0;\n c = (c << 30) | (c >>> 2);\n }\n for (; j < 80; j += 5) {\n f = b ^ c ^ d;\n t = (a << 5) | (a >>> 27);\n e = (t + f + e - 899497514 + blocks[j]) << 0;\n b = (b << 30) | (b >>> 2);\n f = a ^ b ^ c;\n t = (e << 5) | (e >>> 27);\n d = (t + f + d - 899497514 + blocks[j + 1]) << 0;\n a = (a << 30) | (a >>> 2);\n f = e ^ a ^ b;\n t = (d << 5) | (d >>> 27);\n c = (t + f + c - 899497514 + blocks[j + 2]) << 0;\n e = (e << 30) | (e >>> 2);\n f = d ^ e ^ a;\n t = (c << 5) | (c >>> 27);\n b = (t + f + b - 899497514 + blocks[j + 3]) << 0;\n d = (d << 30) | (d >>> 2);\n f = c ^ d ^ e;\n t = (b << 5) | (b >>> 27);\n a = (t + f + a - 899497514 + blocks[j + 4]) << 0;\n c = (c << 30) | (c >>> 2);\n }\n this.h0 = (this.h0 + a) << 0;\n this.h1 = (this.h1 + b) << 0;\n this.h2 = (this.h2 + c) << 0;\n this.h3 = (this.h3 + d) << 0;\n this.h4 = (this.h4 + e) << 0;\n};\nSha1.prototype.hex = function () {\n this.finalize();\n var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4;\n return (HEX_CHARS[(h0 >> 28) & 0x0f] +\n HEX_CHARS[(h0 >> 24) & 0x0f] +\n HEX_CHARS[(h0 >> 20) & 0x0f] +\n HEX_CHARS[(h0 >> 16) & 0x0f] +\n HEX_CHARS[(h0 >> 12) & 0x0f] +\n HEX_CHARS[(h0 >> 8) & 0x0f] +\n HEX_CHARS[(h0 >> 4) & 0x0f] +\n HEX_CHARS[h0 & 0x0f] +\n HEX_CHARS[(h1 >> 28) & 0x0f] +\n HEX_CHARS[(h1 >> 24) & 0x0f] +\n HEX_CHARS[(h1 >> 20) & 0x0f] +\n HEX_CHARS[(h1 >> 16) & 0x0f] +\n HEX_CHARS[(h1 >> 12) & 0x0f] +\n HEX_CHARS[(h1 >> 8) & 0x0f] +\n HEX_CHARS[(h1 >> 4) & 0x0f] +\n HEX_CHARS[h1 & 0x0f] +\n HEX_CHARS[(h2 >> 28) & 0x0f] +\n HEX_CHARS[(h2 >> 24) & 0x0f] +\n HEX_CHARS[(h2 >> 20) & 0x0f] +\n HEX_CHARS[(h2 >> 16) & 0x0f] +\n HEX_CHARS[(h2 >> 12) & 0x0f] +\n HEX_CHARS[(h2 >> 8) & 0x0f] +\n HEX_CHARS[(h2 >> 4) & 0x0f] +\n HEX_CHARS[h2 & 0x0f] +\n HEX_CHARS[(h3 >> 28) & 0x0f] +\n HEX_CHARS[(h3 >> 24) & 0x0f] +\n HEX_CHARS[(h3 >> 20) & 0x0f] +\n HEX_CHARS[(h3 >> 16) & 0x0f] +\n HEX_CHARS[(h3 >> 12) & 0x0f] +\n HEX_CHARS[(h3 >> 8) & 0x0f] +\n HEX_CHARS[(h3 >> 4) & 0x0f] +\n HEX_CHARS[h3 & 0x0f] +\n HEX_CHARS[(h4 >> 28) & 0x0f] +\n HEX_CHARS[(h4 >> 24) & 0x0f] +\n HEX_CHARS[(h4 >> 20) & 0x0f] +\n HEX_CHARS[(h4 >> 16) & 0x0f] +\n HEX_CHARS[(h4 >> 12) & 0x0f] +\n HEX_CHARS[(h4 >> 8) & 0x0f] +\n HEX_CHARS[(h4 >> 4) & 0x0f] +\n HEX_CHARS[h4 & 0x0f]);\n};\nSha1.prototype.toString = Sha1.prototype.hex;\nSha1.prototype.digest = function () {\n this.finalize();\n var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4;\n return [\n (h0 >> 24) & 0xff,\n (h0 >> 16) & 0xff,\n (h0 >> 8) & 0xff,\n h0 & 0xff,\n (h1 >> 24) & 0xff,\n (h1 >> 16) & 0xff,\n (h1 >> 8) & 0xff,\n h1 & 0xff,\n (h2 >> 24) & 0xff,\n (h2 >> 16) & 0xff,\n (h2 >> 8) & 0xff,\n h2 & 0xff,\n (h3 >> 24) & 0xff,\n (h3 >> 16) & 0xff,\n (h3 >> 8) & 0xff,\n h3 & 0xff,\n (h4 >> 24) & 0xff,\n (h4 >> 16) & 0xff,\n (h4 >> 8) & 0xff,\n h4 & 0xff,\n ];\n};\nSha1.prototype.array = Sha1.prototype.digest;\nSha1.prototype.arrayBuffer = function () {\n this.finalize();\n var buffer = new ArrayBuffer(20);\n var dataView = new DataView(buffer);\n dataView.setUint32(0, this.h0);\n dataView.setUint32(4, this.h1);\n dataView.setUint32(8, this.h2);\n dataView.setUint32(12, this.h3);\n dataView.setUint32(16, this.h4);\n return buffer;\n};\nconst insecureHash = (message) => {\n return new Sha1(true).update(message)["hex"]();\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/js-sha1/hash.js?');
|
|
592
|
+
/***/
|
|
593
|
+
},
|
|
594
|
+
/***/ "./node_modules/@langchain/core/dist/utils/json.js":
|
|
595
|
+
/*!*********************************************************!*\
|
|
596
|
+
!*** ./node_modules/@langchain/core/dist/utils/json.js ***!
|
|
597
|
+
\*********************************************************/
|
|
598
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
599
|
+
"use strict";
|
|
600
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseJsonMarkdown: () => (/* binding */ parseJsonMarkdown),\n/* harmony export */ parsePartialJson: () => (/* binding */ parsePartialJson)\n/* harmony export */ });\nfunction parseJsonMarkdown(s, parser = parsePartialJson) {\n // eslint-disable-next-line no-param-reassign\n s = s.trim();\n const match = /```(json)?(.*)```/s.exec(s);\n if (!match) {\n return parser(s);\n }\n else {\n return parser(match[2]);\n }\n}\n// Adapted from https://github.com/KillianLucas/open-interpreter/blob/main/interpreter/core/llm/utils/parse_partial_json.py\n// MIT License\nfunction parsePartialJson(s) {\n // If the input is undefined, return null to indicate failure.\n if (typeof s === "undefined") {\n return null;\n }\n // Attempt to parse the string as-is.\n try {\n return JSON.parse(s);\n }\n catch (error) {\n // Pass\n }\n // Initialize variables.\n let new_s = "";\n const stack = [];\n let isInsideString = false;\n let escaped = false;\n // Process each character in the string one at a time.\n for (let char of s) {\n if (isInsideString) {\n if (char === \'"\' && !escaped) {\n isInsideString = false;\n }\n else if (char === "\\n" && !escaped) {\n char = "\\\\n"; // Replace the newline character with the escape sequence.\n }\n else if (char === "\\\\") {\n escaped = !escaped;\n }\n else {\n escaped = false;\n }\n }\n else {\n if (char === \'"\') {\n isInsideString = true;\n escaped = false;\n }\n else if (char === "{") {\n stack.push("}");\n }\n else if (char === "[") {\n stack.push("]");\n }\n else if (char === "}" || char === "]") {\n if (stack && stack[stack.length - 1] === char) {\n stack.pop();\n }\n else {\n // Mismatched closing character; the input is malformed.\n return null;\n }\n }\n }\n // Append the processed character to the new string.\n new_s += char;\n }\n // If we\'re still inside a string at the end of processing,\n // we need to close the string.\n if (isInsideString) {\n new_s += \'"\';\n }\n // Close any remaining open structures in the reverse order that they were opened.\n for (let i = stack.length - 1; i >= 0; i -= 1) {\n new_s += stack[i];\n }\n // Attempt to parse the modified string as JSON.\n try {\n return JSON.parse(new_s);\n }\n catch (error) {\n // If we still can\'t parse the string as JSON, return null to indicate failure.\n return null;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/json.js?');
|
|
601
|
+
/***/
|
|
602
|
+
},
|
|
603
|
+
/***/ "./node_modules/@langchain/core/dist/utils/stream.js":
|
|
604
|
+
/*!***********************************************************!*\
|
|
605
|
+
!*** ./node_modules/@langchain/core/dist/utils/stream.js ***!
|
|
606
|
+
\***********************************************************/
|
|
607
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
608
|
+
"use strict";
|
|
609
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncGeneratorWithSetup: () => (/* binding */ AsyncGeneratorWithSetup),\n/* harmony export */ IterableReadableStream: () => (/* binding */ IterableReadableStream),\n/* harmony export */ atee: () => (/* binding */ atee),\n/* harmony export */ concat: () => (/* binding */ concat),\n/* harmony export */ pipeGeneratorWithSetup: () => (/* binding */ pipeGeneratorWithSetup)\n/* harmony export */ });\n/* harmony import */ var _singletons_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../singletons/index.js */ "./node_modules/@langchain/core/dist/singletons/index.js");\n// Make this a type to override ReadableStream\'s async iterator type in case\n// the popular web-streams-polyfill is imported - the supplied types\n\n/*\n * Support async iterator syntax for ReadableStreams in all environments.\n * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nclass IterableReadableStream extends ReadableStream {\n constructor() {\n super(...arguments);\n Object.defineProperty(this, "reader", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n ensureReader() {\n if (!this.reader) {\n this.reader = this.getReader();\n }\n }\n async next() {\n this.ensureReader();\n try {\n const result = await this.reader.read();\n if (result.done) {\n this.reader.releaseLock(); // release lock when stream becomes closed\n return {\n done: true,\n value: undefined,\n };\n }\n else {\n return {\n done: false,\n value: result.value,\n };\n }\n }\n catch (e) {\n this.reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n }\n async return() {\n this.ensureReader();\n // If wrapped in a Node stream, cancel is already called.\n if (this.locked) {\n const cancelPromise = this.reader.cancel(); // cancel first, but don\'t await yet\n this.reader.releaseLock(); // release lock first\n await cancelPromise; // now await it\n }\n return { done: true, value: undefined };\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async throw(e) {\n this.ensureReader();\n if (this.locked) {\n const cancelPromise = this.reader.cancel(); // cancel first, but don\'t await yet\n this.reader.releaseLock(); // release lock first\n await cancelPromise; // now await it\n }\n throw e;\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n static fromReadableStream(stream) {\n // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream\n const reader = stream.getReader();\n return new IterableReadableStream({\n start(controller) {\n return pump();\n function pump() {\n return reader.read().then(({ done, value }) => {\n // When no more data needs to be consumed, close the stream\n if (done) {\n controller.close();\n return;\n }\n // Enqueue the next data chunk into our target stream\n controller.enqueue(value);\n return pump();\n });\n }\n },\n cancel() {\n reader.releaseLock();\n },\n });\n }\n static fromAsyncGenerator(generator) {\n return new IterableReadableStream({\n async pull(controller) {\n const { value, done } = await generator.next();\n // When no more data needs to be consumed, close the stream\n if (done) {\n controller.close();\n }\n // Fix: `else if (value)` will hang the streaming when nullish value (e.g. empty string) is pulled\n controller.enqueue(value);\n },\n async cancel(reason) {\n await generator.return(reason);\n },\n });\n }\n}\nfunction atee(iter, length = 2) {\n const buffers = Array.from({ length }, () => []);\n return buffers.map(async function* makeIter(buffer) {\n while (true) {\n if (buffer.length === 0) {\n const result = await iter.next();\n for (const buffer of buffers) {\n buffer.push(result);\n }\n }\n else if (buffer[0].done) {\n return;\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n yield buffer.shift().value;\n }\n }\n });\n}\nfunction concat(first, second) {\n if (Array.isArray(first) && Array.isArray(second)) {\n return first.concat(second);\n }\n else if (typeof first === "string" && typeof second === "string") {\n return (first + second);\n }\n else if (typeof first === "number" && typeof second === "number") {\n return (first + second);\n }\n else if (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n "concat" in first &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof first.concat === "function") {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return first.concat(second);\n }\n else if (typeof first === "object" && typeof second === "object") {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chunk = { ...first };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [key, value] of Object.entries(second)) {\n if (key in chunk && !Array.isArray(chunk[key])) {\n chunk[key] = concat(chunk[key], value);\n }\n else {\n chunk[key] = value;\n }\n }\n return chunk;\n }\n else {\n throw new Error(`Cannot concat ${typeof first} and ${typeof second}`);\n }\n}\nclass AsyncGeneratorWithSetup {\n constructor(params) {\n Object.defineProperty(this, "generator", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "setup", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "config", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "firstResult", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "firstResultUsed", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n this.generator = params.generator;\n this.config = params.config;\n // setup is a promise that resolves only after the first iterator value\n // is available. this is useful when setup of several piped generators\n // needs to happen in logical order, ie. in the order in which input to\n // to each generator is available.\n this.setup = new Promise((resolve, reject) => {\n const storage = _singletons_index_js__WEBPACK_IMPORTED_MODULE_0__.AsyncLocalStorageProviderSingleton.getInstance();\n void storage.run(params.config, async () => {\n this.firstResult = params.generator.next();\n if (params.startSetup) {\n this.firstResult.then(params.startSetup).then(resolve, reject);\n }\n else {\n this.firstResult.then((_result) => resolve(undefined), reject);\n }\n });\n });\n }\n async next(...args) {\n if (!this.firstResultUsed) {\n this.firstResultUsed = true;\n return this.firstResult;\n }\n const storage = _singletons_index_js__WEBPACK_IMPORTED_MODULE_0__.AsyncLocalStorageProviderSingleton.getInstance();\n return storage.run(this.config, async () => {\n return this.generator.next(...args);\n });\n }\n async return(value) {\n return this.generator.return(value);\n }\n async throw(e) {\n return this.generator.throw(e);\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n}\nasync function pipeGeneratorWithSetup(to, generator, startSetup, ...args) {\n const gen = new AsyncGeneratorWithSetup({ generator, startSetup });\n const setup = await gen.setup;\n return { output: to(gen, setup, ...args), setup };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/stream.js?');
|
|
610
|
+
/***/
|
|
611
|
+
},
|
|
612
|
+
/***/ "./node_modules/@langchain/core/dist/utils/tiktoken.js":
|
|
613
|
+
/*!*************************************************************!*\
|
|
614
|
+
!*** ./node_modules/@langchain/core/dist/utils/tiktoken.js ***!
|
|
615
|
+
\*************************************************************/
|
|
616
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
617
|
+
"use strict";
|
|
618
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ encodingForModel: () => (/* binding */ encodingForModel),\n/* harmony export */ getEncoding: () => (/* binding */ getEncoding)\n/* harmony export */ });\n/* harmony import */ var js_tiktoken_lite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! js-tiktoken/lite */ "./node_modules/js-tiktoken/dist/lite.js");\n/* harmony import */ var _async_caller_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./async_caller.js */ "./node_modules/@langchain/core/dist/utils/async_caller.js");\n\n\nconst cache = {};\nconst caller = /* #__PURE__ */ new _async_caller_js__WEBPACK_IMPORTED_MODULE_1__.AsyncCaller({});\nasync function getEncoding(encoding) {\n if (!(encoding in cache)) {\n cache[encoding] = caller\n .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`)\n .then((res) => res.json())\n .then((data) => new js_tiktoken_lite__WEBPACK_IMPORTED_MODULE_0__.Tiktoken(data))\n .catch((e) => {\n delete cache[encoding];\n throw e;\n });\n }\n return await cache[encoding];\n}\nasync function encodingForModel(model) {\n return getEncoding((0,js_tiktoken_lite__WEBPACK_IMPORTED_MODULE_0__.getEncodingNameForModel)(model));\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/tiktoken.js?');
|
|
619
|
+
/***/
|
|
620
|
+
},
|
|
621
|
+
/***/ "./node_modules/@langchain/core/dist/utils/types/is_zod_schema.js":
|
|
622
|
+
/*!************************************************************************!*\
|
|
623
|
+
!*** ./node_modules/@langchain/core/dist/utils/types/is_zod_schema.js ***!
|
|
624
|
+
\************************************************************************/
|
|
625
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
626
|
+
"use strict";
|
|
627
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isZodSchema: () => (/* binding */ isZodSchema)\n/* harmony export */ });\n/**\n * Given either a Zod schema, or plain object, determine if the input is a Zod schema.\n *\n * @param {z.ZodType<RunOutput> | Record<string, any>} input\n * @returns {boolean} Whether or not the provided input is a Zod schema.\n */\nfunction isZodSchema(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninput) {\n // Check for a characteristic method of Zod schemas\n return typeof input?.parse === "function";\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/dist/utils/types/is_zod_schema.js?');
|
|
628
|
+
/***/
|
|
629
|
+
},
|
|
630
|
+
/***/ "./node_modules/@langchain/core/language_models/chat_models.js":
|
|
631
|
+
/*!*********************************************************************!*\
|
|
632
|
+
!*** ./node_modules/@langchain/core/language_models/chat_models.js ***!
|
|
633
|
+
\*********************************************************************/
|
|
634
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
635
|
+
"use strict";
|
|
636
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BaseChatModel: () => (/* reexport safe */ _dist_language_models_chat_models_js__WEBPACK_IMPORTED_MODULE_0__.BaseChatModel),\n/* harmony export */ SimpleChatModel: () => (/* reexport safe */ _dist_language_models_chat_models_js__WEBPACK_IMPORTED_MODULE_0__.SimpleChatModel),\n/* harmony export */ createChatMessageChunkEncoderStream: () => (/* reexport safe */ _dist_language_models_chat_models_js__WEBPACK_IMPORTED_MODULE_0__.createChatMessageChunkEncoderStream)\n/* harmony export */ });\n/* harmony import */ var _dist_language_models_chat_models_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../dist/language_models/chat_models.js */ "./node_modules/@langchain/core/dist/language_models/chat_models.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/language_models/chat_models.js?');
|
|
637
|
+
/***/
|
|
638
|
+
},
|
|
639
|
+
/***/ "./node_modules/@langchain/core/messages.js":
|
|
640
|
+
/*!**************************************************!*\
|
|
641
|
+
!*** ./node_modules/@langchain/core/messages.js ***!
|
|
642
|
+
\**************************************************/
|
|
643
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
644
|
+
"use strict";
|
|
645
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AIMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.AIMessage),\n/* harmony export */ AIMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.AIMessageChunk),\n/* harmony export */ BaseMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessage),\n/* harmony export */ BaseMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.BaseMessageChunk),\n/* harmony export */ ChatMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.ChatMessage),\n/* harmony export */ ChatMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.ChatMessageChunk),\n/* harmony export */ FunctionMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.FunctionMessage),\n/* harmony export */ FunctionMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.FunctionMessageChunk),\n/* harmony export */ HumanMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.HumanMessage),\n/* harmony export */ HumanMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.HumanMessageChunk),\n/* harmony export */ SystemMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.SystemMessage),\n/* harmony export */ SystemMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.SystemMessageChunk),\n/* harmony export */ ToolMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.ToolMessage),\n/* harmony export */ ToolMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.ToolMessageChunk),\n/* harmony export */ _mergeDicts: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__._mergeDicts),\n/* harmony export */ _mergeLists: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__._mergeLists),\n/* harmony export */ coerceMessageLikeToMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.coerceMessageLikeToMessage),\n/* harmony export */ convertToChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.convertToChunk),\n/* harmony export */ defaultTextSplitter: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.defaultTextSplitter),\n/* harmony export */ filterMessages: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.filterMessages),\n/* harmony export */ getBufferString: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.getBufferString),\n/* harmony export */ isAIMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.isAIMessage),\n/* harmony export */ isBaseMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.isBaseMessage),\n/* harmony export */ isBaseMessageChunk: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.isBaseMessageChunk),\n/* harmony export */ isOpenAIToolCallArray: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.isOpenAIToolCallArray),\n/* harmony export */ mapChatMessagesToStoredMessages: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.mapChatMessagesToStoredMessages),\n/* harmony export */ mapStoredMessageToChatMessage: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.mapStoredMessageToChatMessage),\n/* harmony export */ mapStoredMessagesToChatMessages: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.mapStoredMessagesToChatMessages),\n/* harmony export */ mergeContent: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.mergeContent),\n/* harmony export */ mergeMessageRuns: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.mergeMessageRuns),\n/* harmony export */ trimMessages: () => (/* reexport safe */ _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__.trimMessages)\n/* harmony export */ });\n/* harmony import */ var _dist_messages_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dist/messages/index.js */ "./node_modules/@langchain/core/dist/messages/index.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/messages.js?');
|
|
646
|
+
/***/
|
|
647
|
+
},
|
|
648
|
+
/***/ "./node_modules/@langchain/core/outputs.js":
|
|
649
|
+
/*!*************************************************!*\
|
|
650
|
+
!*** ./node_modules/@langchain/core/outputs.js ***!
|
|
651
|
+
\*************************************************/
|
|
652
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
653
|
+
"use strict";
|
|
654
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ChatGenerationChunk: () => (/* reexport safe */ _dist_outputs_js__WEBPACK_IMPORTED_MODULE_0__.ChatGenerationChunk),\n/* harmony export */ GenerationChunk: () => (/* reexport safe */ _dist_outputs_js__WEBPACK_IMPORTED_MODULE_0__.GenerationChunk),\n/* harmony export */ RUN_KEY: () => (/* reexport safe */ _dist_outputs_js__WEBPACK_IMPORTED_MODULE_0__.RUN_KEY)\n/* harmony export */ });\n/* harmony import */ var _dist_outputs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dist/outputs.js */ "./node_modules/@langchain/core/dist/outputs.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/outputs.js?');
|
|
655
|
+
/***/
|
|
656
|
+
},
|
|
657
|
+
/***/ "./node_modules/@langchain/core/utils/stream.js":
|
|
658
|
+
/*!******************************************************!*\
|
|
659
|
+
!*** ./node_modules/@langchain/core/utils/stream.js ***!
|
|
660
|
+
\******************************************************/
|
|
661
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
662
|
+
"use strict";
|
|
663
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncGeneratorWithSetup: () => (/* reexport safe */ _dist_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.AsyncGeneratorWithSetup),\n/* harmony export */ IterableReadableStream: () => (/* reexport safe */ _dist_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.IterableReadableStream),\n/* harmony export */ atee: () => (/* reexport safe */ _dist_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.atee),\n/* harmony export */ concat: () => (/* reexport safe */ _dist_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.concat),\n/* harmony export */ pipeGeneratorWithSetup: () => (/* reexport safe */ _dist_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__.pipeGeneratorWithSetup)\n/* harmony export */ });\n/* harmony import */ var _dist_utils_stream_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../dist/utils/stream.js */ "./node_modules/@langchain/core/dist/utils/stream.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/utils/stream.js?');
|
|
664
|
+
/***/
|
|
665
|
+
},
|
|
666
|
+
/***/ "./node_modules/@langchain/core/utils/tiktoken.js":
|
|
667
|
+
/*!********************************************************!*\
|
|
668
|
+
!*** ./node_modules/@langchain/core/utils/tiktoken.js ***!
|
|
669
|
+
\********************************************************/
|
|
670
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
671
|
+
"use strict";
|
|
672
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ encodingForModel: () => (/* reexport safe */ _dist_utils_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__.encodingForModel),\n/* harmony export */ getEncoding: () => (/* reexport safe */ _dist_utils_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__.getEncoding)\n/* harmony export */ });\n/* harmony import */ var _dist_utils_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../dist/utils/tiktoken.js */ "./node_modules/@langchain/core/dist/utils/tiktoken.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/@langchain/core/utils/tiktoken.js?');
|
|
673
|
+
/***/
|
|
674
|
+
},
|
|
675
|
+
/***/ "./node_modules/js-tiktoken/dist/chunk-PEBACC3C.js":
|
|
676
|
+
/*!*********************************************************!*\
|
|
677
|
+
!*** ./node_modules/js-tiktoken/dist/chunk-PEBACC3C.js ***!
|
|
678
|
+
\*********************************************************/
|
|
679
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
680
|
+
"use strict";
|
|
681
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Tiktoken: () => (/* binding */ Tiktoken),\n/* harmony export */ getEncodingNameForModel: () => (/* binding */ getEncodingNameForModel),\n/* harmony export */ never: () => (/* binding */ never)\n/* harmony export */ });\n/* harmony import */ var base64_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! base64-js */ "./node_modules/base64-js/index.js");\n\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);\n return value;\n};\n\n// src/utils.ts\nfunction never(_) {\n}\nfunction bytePairMerge(piece, ranks) {\n let parts = Array.from(\n { length: piece.length },\n (_, i) => ({ start: i, end: i + 1 })\n );\n while (parts.length > 1) {\n let minRank = null;\n for (let i = 0; i < parts.length - 1; i++) {\n const slice = piece.slice(parts[i].start, parts[i + 1].end);\n const rank = ranks.get(slice.join(","));\n if (rank == null)\n continue;\n if (minRank == null || rank < minRank[0]) {\n minRank = [rank, i];\n }\n }\n if (minRank != null) {\n const i = minRank[1];\n parts[i] = { start: parts[i].start, end: parts[i + 1].end };\n parts.splice(i + 1, 1);\n } else {\n break;\n }\n }\n return parts;\n}\nfunction bytePairEncode(piece, ranks) {\n if (piece.length === 1)\n return [ranks.get(piece.join(","))];\n return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null);\n}\nfunction escapeRegex(str) {\n return str.replace(/[\\\\^$*+?.()|[\\]{}]/g, "\\\\$&");\n}\nvar _Tiktoken = class {\n /** @internal */\n specialTokens;\n /** @internal */\n inverseSpecialTokens;\n /** @internal */\n patStr;\n /** @internal */\n textEncoder = new TextEncoder();\n /** @internal */\n textDecoder = new TextDecoder("utf-8");\n /** @internal */\n rankMap = /* @__PURE__ */ new Map();\n /** @internal */\n textMap = /* @__PURE__ */ new Map();\n constructor(ranks, extendedSpecialTokens) {\n this.patStr = ranks.pat_str;\n const uncompressed = ranks.bpe_ranks.split("\\n").filter(Boolean).reduce((memo, x) => {\n const [_, offsetStr, ...tokens] = x.split(" ");\n const offset = Number.parseInt(offsetStr, 10);\n tokens.forEach((token, i) => memo[token] = offset + i);\n return memo;\n }, {});\n for (const [token, rank] of Object.entries(uncompressed)) {\n const bytes = base64_js__WEBPACK_IMPORTED_MODULE_0__.toByteArray(token);\n this.rankMap.set(bytes.join(","), rank);\n this.textMap.set(rank, bytes);\n }\n this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens };\n this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => {\n memo[rank] = this.textEncoder.encode(text);\n return memo;\n }, {});\n }\n encode(text, allowedSpecial = [], disallowedSpecial = "all") {\n const regexes = new RegExp(this.patStr, "ug");\n const specialRegex = _Tiktoken.specialTokenRegex(\n Object.keys(this.specialTokens)\n );\n const ret = [];\n const allowedSpecialSet = new Set(\n allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial\n );\n const disallowedSpecialSet = new Set(\n disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter(\n (x) => !allowedSpecialSet.has(x)\n ) : disallowedSpecial\n );\n if (disallowedSpecialSet.size > 0) {\n const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([\n ...disallowedSpecialSet\n ]);\n const specialMatch = text.match(disallowedSpecialRegex);\n if (specialMatch != null) {\n throw new Error(\n `The text contains a special token that is not allowed: ${specialMatch[0]}`\n );\n }\n }\n let start = 0;\n while (true) {\n let nextSpecial = null;\n let startFind = start;\n while (true) {\n specialRegex.lastIndex = startFind;\n nextSpecial = specialRegex.exec(text);\n if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0]))\n break;\n startFind = nextSpecial.index + 1;\n }\n const end = nextSpecial?.index ?? text.length;\n for (const match of text.substring(start, end).matchAll(regexes)) {\n const piece = this.textEncoder.encode(match[0]);\n const token2 = this.rankMap.get(piece.join(","));\n if (token2 != null) {\n ret.push(token2);\n continue;\n }\n ret.push(...bytePairEncode(piece, this.rankMap));\n }\n if (nextSpecial == null)\n break;\n let token = this.specialTokens[nextSpecial[0]];\n ret.push(token);\n start = nextSpecial.index + nextSpecial[0].length;\n }\n return ret;\n }\n decode(tokens) {\n const res = [];\n let length = 0;\n for (let i2 = 0; i2 < tokens.length; ++i2) {\n const token = tokens[i2];\n const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token];\n if (bytes != null) {\n res.push(bytes);\n length += bytes.length;\n }\n }\n const mergedArray = new Uint8Array(length);\n let i = 0;\n for (const bytes of res) {\n mergedArray.set(bytes, i);\n i += bytes.length;\n }\n return this.textDecoder.decode(mergedArray);\n }\n};\nvar Tiktoken = _Tiktoken;\n__publicField(Tiktoken, "specialTokenRegex", (tokens) => {\n return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g");\n});\nfunction getEncodingNameForModel(model) {\n switch (model) {\n case "gpt2": {\n return "gpt2";\n }\n case "code-cushman-001":\n case "code-cushman-002":\n case "code-davinci-001":\n case "code-davinci-002":\n case "cushman-codex":\n case "davinci-codex":\n case "davinci-002":\n case "text-davinci-002":\n case "text-davinci-003": {\n return "p50k_base";\n }\n case "code-davinci-edit-001":\n case "text-davinci-edit-001": {\n return "p50k_edit";\n }\n case "ada":\n case "babbage":\n case "babbage-002":\n case "code-search-ada-code-001":\n case "code-search-babbage-code-001":\n case "curie":\n case "davinci":\n case "text-ada-001":\n case "text-babbage-001":\n case "text-curie-001":\n case "text-davinci-001":\n case "text-search-ada-doc-001":\n case "text-search-babbage-doc-001":\n case "text-search-curie-doc-001":\n case "text-search-davinci-doc-001":\n case "text-similarity-ada-001":\n case "text-similarity-babbage-001":\n case "text-similarity-curie-001":\n case "text-similarity-davinci-001": {\n return "r50k_base";\n }\n case "gpt-3.5-turbo-instruct-0914":\n case "gpt-3.5-turbo-instruct":\n case "gpt-3.5-turbo-16k-0613":\n case "gpt-3.5-turbo-16k":\n case "gpt-3.5-turbo-0613":\n case "gpt-3.5-turbo-0301":\n case "gpt-3.5-turbo":\n case "gpt-4-32k-0613":\n case "gpt-4-32k-0314":\n case "gpt-4-32k":\n case "gpt-4-0613":\n case "gpt-4-0314":\n case "gpt-4":\n case "gpt-3.5-turbo-1106":\n case "gpt-35-turbo":\n case "gpt-4-1106-preview":\n case "gpt-4-vision-preview":\n case "gpt-3.5-turbo-0125":\n case "gpt-4-turbo":\n case "gpt-4-turbo-2024-04-09":\n case "gpt-4-turbo-preview":\n case "gpt-4-0125-preview":\n case "text-embedding-ada-002": {\n return "cl100k_base";\n }\n case "gpt-4o":\n case "gpt-4o-2024-05-13": {\n return "o200k_base";\n }\n default:\n throw new Error("Unknown model");\n }\n}\n\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/js-tiktoken/dist/chunk-PEBACC3C.js?');
|
|
682
|
+
/***/
|
|
683
|
+
},
|
|
684
|
+
/***/ "./node_modules/js-tiktoken/dist/lite.js":
|
|
685
|
+
/*!***********************************************!*\
|
|
686
|
+
!*** ./node_modules/js-tiktoken/dist/lite.js ***!
|
|
687
|
+
\***********************************************/
|
|
688
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
689
|
+
"use strict";
|
|
690
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Tiktoken: () => (/* reexport safe */ _chunk_PEBACC3C_js__WEBPACK_IMPORTED_MODULE_0__.Tiktoken),\n/* harmony export */ getEncodingNameForModel: () => (/* reexport safe */ _chunk_PEBACC3C_js__WEBPACK_IMPORTED_MODULE_0__.getEncodingNameForModel)\n/* harmony export */ });\n/* harmony import */ var _chunk_PEBACC3C_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./chunk-PEBACC3C.js */ "./node_modules/js-tiktoken/dist/chunk-PEBACC3C.js");\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/js-tiktoken/dist/lite.js?');
|
|
691
|
+
/***/
|
|
692
|
+
},
|
|
693
|
+
/***/ "./node_modules/langchain/dist/experimental/chrome_ai/chat_models.js":
|
|
694
|
+
/*!***************************************************************************!*\
|
|
695
|
+
!*** ./node_modules/langchain/dist/experimental/chrome_ai/chat_models.js ***!
|
|
696
|
+
\***************************************************************************/
|
|
697
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
698
|
+
"use strict";
|
|
699
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ChatChromeAI: () => (/* binding */ ChatChromeAI)\n/* harmony export */ });\n/* harmony import */ var _langchain_core_language_models_chat_models__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @langchain/core/language_models/chat_models */ "./node_modules/@langchain/core/language_models/chat_models.js");\n/* harmony import */ var _langchain_core_messages__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @langchain/core/messages */ "./node_modules/@langchain/core/messages.js");\n/* harmony import */ var _langchain_core_outputs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @langchain/core/outputs */ "./node_modules/@langchain/core/outputs.js");\n/* harmony import */ var _langchain_core_utils_stream__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @langchain/core/utils/stream */ "./node_modules/@langchain/core/utils/stream.js");\n\n\n\n\nfunction formatPrompt(messages) {\n return messages\n .map((message) => {\n if (typeof message.content !== "string") {\n throw new Error("ChatChromeAI does not support non-string message content.");\n }\n return `${message._getType()}: ${message.content}`;\n })\n .join("\\n");\n}\n/**\n * To use this model you need to have the `Built-in AI Early Preview Program`\n * for Chrome. You can find more information about the program here:\n * @link https://developer.chrome.com/docs/ai/built-in\n *\n * @example\n * ```typescript\n * // Initialize the ChatChromeAI model.\n * const model = new ChatChromeAI({\n * temperature: 0.5, // Optional. Default is 0.5.\n * topK: 40, // Optional. Default is 40.\n * });\n *\n * // Call the model with a message and await the response.\n * const response = await model.invoke([\n * new HumanMessage({ content: "My name is John." }),\n * ]);\n * ```\n */\nclass ChatChromeAI extends _langchain_core_language_models_chat_models__WEBPACK_IMPORTED_MODULE_0__.SimpleChatModel {\n static lc_name() {\n return "ChatChromeAI";\n }\n constructor(inputs) {\n super({\n callbacks: {},\n ...inputs,\n });\n Object.defineProperty(this, "session", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "temperature", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0.5\n });\n Object.defineProperty(this, "topK", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 40\n });\n this.temperature = inputs?.temperature ?? this.temperature;\n this.topK = inputs?.topK ?? this.topK;\n }\n _llmType() {\n return "chrome-ai";\n }\n /**\n * Initialize the model. This method must be called before calling `.invoke()`.\n */\n async initialize() {\n if (typeof window === "undefined") {\n throw new Error("ChatChromeAI can only be used in the browser.");\n }\n const { ai } = window;\n const canCreateTextSession = await ai.canCreateTextSession();\n if (canCreateTextSession === "no" /* AIModelAvailability.No */) {\n throw new Error("The AI model is not available.");\n }\n else if (canCreateTextSession === "after-download" /* AIModelAvailability.AfterDownload */) {\n throw new Error("The AI model is not yet downloaded.");\n }\n this.session = await ai.createTextSession({\n topK: this.topK,\n temperature: this.temperature,\n });\n }\n /**\n * Call `.destroy()` to free resources if you no longer need a session.\n * When a session is destroyed, it can no longer be used, and any ongoing\n * execution will be aborted. You may want to keep the session around if\n * you intend to prompt the model often since creating a session can take\n * some time.\n */\n destroy() {\n if (!this.session) {\n return console.log("No session found. Returning.");\n }\n this.session.destroy();\n }\n async *_streamResponseChunks(messages, _options, runManager) {\n if (!this.session) {\n throw new Error("Session not found. Please call `.initialize()` first.");\n }\n const textPrompt = formatPrompt(messages);\n const stream = this.session.promptStreaming(textPrompt);\n const iterableStream = _langchain_core_utils_stream__WEBPACK_IMPORTED_MODULE_3__.IterableReadableStream.fromReadableStream(stream);\n let previousContent = "";\n for await (const chunk of iterableStream) {\n const newContent = chunk.slice(previousContent.length);\n previousContent += newContent;\n yield new _langchain_core_outputs__WEBPACK_IMPORTED_MODULE_2__.ChatGenerationChunk({\n text: newContent,\n message: new _langchain_core_messages__WEBPACK_IMPORTED_MODULE_1__.AIMessageChunk({\n content: newContent,\n additional_kwargs: {},\n }),\n });\n await runManager?.handleLLMNewToken(newContent);\n }\n }\n async _call(messages, options, runManager) {\n const chunks = [];\n for await (const chunk of this._streamResponseChunks(messages, options, runManager)) {\n chunks.push(chunk.text);\n }\n return chunks.join("");\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langchain/dist/experimental/chrome_ai/chat_models.js?');
|
|
700
|
+
/***/
|
|
701
|
+
},
|
|
702
|
+
/***/ "./node_modules/langchain/experimental/chat_models/chrome_ai.js":
|
|
703
|
+
/*!**********************************************************************!*\
|
|
704
|
+
!*** ./node_modules/langchain/experimental/chat_models/chrome_ai.js ***!
|
|
705
|
+
\**********************************************************************/
|
|
706
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
707
|
+
"use strict";
|
|
708
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ChatChromeAI: () => (/* reexport safe */ _dist_experimental_chrome_ai_chat_models_js__WEBPACK_IMPORTED_MODULE_0__.ChatChromeAI)\n/* harmony export */ });\n/* harmony import */ var _dist_experimental_chrome_ai_chat_models_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../dist/experimental/chrome_ai/chat_models.js */ "./node_modules/langchain/dist/experimental/chrome_ai/chat_models.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langchain/experimental/chat_models/chrome_ai.js?');
|
|
709
|
+
/***/
|
|
710
|
+
},
|
|
711
|
+
/***/ "./node_modules/langsmith/dist/client.js":
|
|
712
|
+
/*!***********************************************!*\
|
|
713
|
+
!*** ./node_modules/langsmith/dist/client.js ***!
|
|
714
|
+
\***********************************************/
|
|
715
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
716
|
+
"use strict";
|
|
717
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Client: () => (/* binding */ Client),\n/* harmony export */ DEFAULT_BATCH_SIZE_LIMIT_BYTES: () => (/* binding */ DEFAULT_BATCH_SIZE_LIMIT_BYTES),\n/* harmony export */ Queue: () => (/* binding */ Queue)\n/* harmony export */ });\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");\n/* harmony import */ var _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/async_caller.js */ "./node_modules/langsmith/dist/utils/async_caller.js");\n/* harmony import */ var _utils_messages_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/messages.js */ "./node_modules/langsmith/dist/utils/messages.js");\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/env.js */ "./node_modules/langsmith/dist/utils/env.js");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./index.js */ "./node_modules/langsmith/dist/index.js");\n/* harmony import */ var _utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/_uuid.js */ "./node_modules/langsmith/dist/utils/_uuid.js");\n/* harmony import */ var _utils_warn_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/warn.js */ "./node_modules/langsmith/dist/utils/warn.js");\n\n\n\n\n\n\n\nasync function mergeRuntimeEnvIntoRunCreates(runs) {\n const runtimeEnv = await (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getRuntimeEnvironment)();\n const envVars = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getLangChainEnvVarsMetadata)();\n return runs.map((run) => {\n const extra = run.extra ?? {};\n const metadata = extra.metadata;\n run.extra = {\n ...extra,\n runtime: {\n ...runtimeEnv,\n ...extra?.runtime,\n },\n metadata: {\n ...envVars,\n ...(envVars.revision_id || run.revision_id\n ? { revision_id: run.revision_id ?? envVars.revision_id }\n : {}),\n ...metadata,\n },\n };\n return run;\n });\n}\nconst getTracingSamplingRate = () => {\n const samplingRateStr = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_TRACING_SAMPLING_RATE");\n if (samplingRateStr === undefined) {\n return undefined;\n }\n const samplingRate = parseFloat(samplingRateStr);\n if (samplingRate < 0 || samplingRate > 1) {\n throw new Error(`LANGCHAIN_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`);\n }\n return samplingRate;\n};\n// utility functions\nconst isLocalhost = (url) => {\n const strippedUrl = url.replace("http://", "").replace("https://", "");\n const hostname = strippedUrl.split("/")[0].split(":")[0];\n return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1");\n};\nconst raiseForStatus = async (response, operation) => {\n // consume the response body to release the connection\n // https://undici.nodejs.org/#/?id=garbage-collection\n const body = await response.text();\n if (!response.ok) {\n throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`);\n }\n};\nasync function toArray(iterable) {\n const result = [];\n for await (const item of iterable) {\n result.push(item);\n }\n return result;\n}\nfunction trimQuotes(str) {\n if (str === undefined) {\n return undefined;\n }\n return str\n .trim()\n .replace(/^"(.*)"$/, "$1")\n .replace(/^\'(.*)\'$/, "$1");\n}\nconst handle429 = async (response) => {\n if (response?.status === 429) {\n const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000;\n if (retryAfter > 0) {\n await new Promise((resolve) => setTimeout(resolve, retryAfter));\n // Return directly after calling this check\n return true;\n }\n }\n // Fall back to existing status checks\n return false;\n};\nclass Queue {\n constructor() {\n Object.defineProperty(this, "items", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: []\n });\n }\n get size() {\n return this.items.length;\n }\n push(item) {\n // this.items.push is synchronous with promise creation:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise\n return new Promise((resolve) => {\n this.items.push([item, resolve]);\n });\n }\n pop(upToN) {\n if (upToN < 1) {\n throw new Error("Number of items to pop off may not be less than 1.");\n }\n const popped = [];\n while (popped.length < upToN && this.items.length) {\n const item = this.items.shift();\n if (item) {\n popped.push(item);\n }\n else {\n break;\n }\n }\n return [popped.map((it) => it[0]), () => popped.forEach((it) => it[1]())];\n }\n}\n// 20 MB\nconst DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520;\nclass Client {\n constructor(config = {}) {\n Object.defineProperty(this, "apiKey", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "apiUrl", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "webUrl", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "caller", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "batchIngestCaller", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "timeout_ms", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "_tenantId", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: null\n });\n Object.defineProperty(this, "hideInputs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "hideOutputs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "tracingSampleRate", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "sampledPostUuids", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Set()\n });\n Object.defineProperty(this, "autoBatchTracing", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n Object.defineProperty(this, "batchEndpointSupported", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "autoBatchQueue", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Queue()\n });\n Object.defineProperty(this, "pendingAutoBatchedRunLimit", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 100\n });\n Object.defineProperty(this, "autoBatchTimeout", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "autoBatchInitialDelayMs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 250\n });\n Object.defineProperty(this, "autoBatchAggregationDelayMs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 50\n });\n Object.defineProperty(this, "serverInfo", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "fetchOptions", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n const defaultConfig = Client.getDefaultClientConfig();\n this.tracingSampleRate = getTracingSamplingRate();\n this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? "";\n this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey);\n this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl);\n this.timeout_ms = config.timeout_ms ?? 12_000;\n this.caller = new _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_0__.AsyncCaller(config.callerOptions ?? {});\n this.batchIngestCaller = new _utils_async_caller_js__WEBPACK_IMPORTED_MODULE_0__.AsyncCaller({\n ...(config.callerOptions ?? {}),\n onFailedResponseHook: handle429,\n });\n this.hideInputs =\n config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;\n this.hideOutputs =\n config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;\n this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;\n this.pendingAutoBatchedRunLimit =\n config.pendingAutoBatchedRunLimit ?? this.pendingAutoBatchedRunLimit;\n this.fetchOptions = config.fetchOptions || {};\n }\n static getDefaultClientConfig() {\n const apiKey = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_API_KEY");\n const apiUrl = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_ENDPOINT") ??\n "https://api.smith.langchain.com";\n const hideInputs = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_HIDE_INPUTS") === "true";\n const hideOutputs = (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_HIDE_OUTPUTS") === "true";\n return {\n apiUrl: apiUrl,\n apiKey: apiKey,\n webUrl: undefined,\n hideInputs: hideInputs,\n hideOutputs: hideOutputs,\n };\n }\n getHostUrl() {\n if (this.webUrl) {\n return this.webUrl;\n }\n else if (isLocalhost(this.apiUrl)) {\n this.webUrl = "http://localhost:3000";\n return this.webUrl;\n }\n else if (this.apiUrl.includes("/api") &&\n !this.apiUrl.split(".", 1)[0].endsWith("api")) {\n this.webUrl = this.apiUrl.replace("/api", "");\n return this.webUrl;\n }\n else if (this.apiUrl.split(".", 1)[0].includes("dev")) {\n this.webUrl = "https://dev.smith.langchain.com";\n return this.webUrl;\n }\n else {\n this.webUrl = "https://smith.langchain.com";\n return this.webUrl;\n }\n }\n get headers() {\n const headers = {\n "User-Agent": `langsmith-js/${_index_js__WEBPACK_IMPORTED_MODULE_3__.__version__}`,\n };\n if (this.apiKey) {\n headers["x-api-key"] = `${this.apiKey}`;\n }\n return headers;\n }\n processInputs(inputs) {\n if (this.hideInputs === false) {\n return inputs;\n }\n if (this.hideInputs === true) {\n return {};\n }\n if (typeof this.hideInputs === "function") {\n return this.hideInputs(inputs);\n }\n return inputs;\n }\n processOutputs(outputs) {\n if (this.hideOutputs === false) {\n return outputs;\n }\n if (this.hideOutputs === true) {\n return {};\n }\n if (typeof this.hideOutputs === "function") {\n return this.hideOutputs(outputs);\n }\n return outputs;\n }\n prepareRunCreateOrUpdateInputs(run) {\n const runParams = { ...run };\n if (runParams.inputs !== undefined) {\n runParams.inputs = this.processInputs(runParams.inputs);\n }\n if (runParams.outputs !== undefined) {\n runParams.outputs = this.processOutputs(runParams.outputs);\n }\n return runParams;\n }\n async _getResponse(path, queryParams) {\n const paramsString = queryParams?.toString() ?? "";\n const url = `${this.apiUrl}${path}?${paramsString}`;\n const response = await this.caller.call(fetch, url, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);\n }\n return response;\n }\n async _get(path, queryParams) {\n const response = await this._getResponse(path, queryParams);\n return response.json();\n }\n async *_getPaginated(path, queryParams = new URLSearchParams()) {\n let offset = Number(queryParams.get("offset")) || 0;\n const limit = Number(queryParams.get("limit")) || 100;\n while (true) {\n queryParams.set("offset", String(offset));\n queryParams.set("limit", String(limit));\n const url = `${this.apiUrl}${path}?${queryParams}`;\n const response = await this.caller.call(fetch, url, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`);\n }\n const items = await response.json();\n if (items.length === 0) {\n break;\n }\n yield items;\n if (items.length < limit) {\n break;\n }\n offset += items.length;\n }\n }\n async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") {\n const bodyParams = body ? { ...body } : {};\n while (true) {\n const response = await this.caller.call(fetch, `${this.apiUrl}${path}`, {\n method: requestMethod,\n headers: { ...this.headers, "Content-Type": "application/json" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n body: JSON.stringify(bodyParams),\n });\n const responseBody = await response.json();\n if (!responseBody) {\n break;\n }\n if (!responseBody[dataKey]) {\n break;\n }\n yield responseBody[dataKey];\n const cursors = responseBody.cursors;\n if (!cursors) {\n break;\n }\n if (!cursors.next) {\n break;\n }\n bodyParams.cursor = cursors.next;\n }\n }\n _filterForSampling(runs, patch = false) {\n if (this.tracingSampleRate === undefined) {\n return runs;\n }\n if (patch) {\n const sampled = [];\n for (const run of runs) {\n if (this.sampledPostUuids.has(run.id)) {\n sampled.push(run);\n this.sampledPostUuids.delete(run.id);\n }\n }\n return sampled;\n }\n else {\n const sampled = [];\n for (const run of runs) {\n if (Math.random() < this.tracingSampleRate) {\n sampled.push(run);\n this.sampledPostUuids.add(run.id);\n }\n }\n return sampled;\n }\n }\n async drainAutoBatchQueue() {\n while (this.autoBatchQueue.size >= 0) {\n const [batch, done] = this.autoBatchQueue.pop(this.pendingAutoBatchedRunLimit);\n if (!batch.length) {\n done();\n return;\n }\n try {\n await this.batchIngestRuns({\n runCreates: batch\n .filter((item) => item.action === "create")\n .map((item) => item.item),\n runUpdates: batch\n .filter((item) => item.action === "update")\n .map((item) => item.item),\n });\n }\n finally {\n done();\n }\n }\n }\n async processRunOperation(item, immediatelyTriggerBatch) {\n const oldTimeout = this.autoBatchTimeout;\n clearTimeout(this.autoBatchTimeout);\n this.autoBatchTimeout = undefined;\n const itemPromise = this.autoBatchQueue.push(item);\n if (immediatelyTriggerBatch ||\n this.autoBatchQueue.size > this.pendingAutoBatchedRunLimit) {\n await this.drainAutoBatchQueue();\n }\n if (this.autoBatchQueue.size > 0) {\n this.autoBatchTimeout = setTimeout(() => {\n this.autoBatchTimeout = undefined;\n // This error would happen in the background and is uncatchable\n // from the outside. So just log instead.\n void this.drainAutoBatchQueue().catch(console.error);\n }, oldTimeout\n ? this.autoBatchAggregationDelayMs\n : this.autoBatchInitialDelayMs);\n }\n return itemPromise;\n }\n async _getServerInfo() {\n const response = await fetch(`${this.apiUrl}/info`, {\n method: "GET",\n headers: { Accept: "application/json" },\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n // consume the response body to release the connection\n // https://undici.nodejs.org/#/?id=garbage-collection\n await response.text();\n throw new Error("Failed to retrieve server info.");\n }\n return response.json();\n }\n async batchEndpointIsSupported() {\n try {\n this.serverInfo = await this._getServerInfo();\n }\n catch (e) {\n return false;\n }\n return true;\n }\n async createRun(run) {\n if (!this._filterForSampling([run]).length) {\n return;\n }\n const headers = { ...this.headers, "Content-Type": "application/json" };\n const session_name = run.project_name;\n delete run.project_name;\n const runCreate = this.prepareRunCreateOrUpdateInputs({\n session_name,\n ...run,\n start_time: run.start_time ?? Date.now(),\n });\n if (this.autoBatchTracing &&\n runCreate.trace_id !== undefined &&\n runCreate.dotted_order !== undefined) {\n void this.processRunOperation({\n action: "create",\n item: runCreate,\n }).catch(console.error);\n return;\n }\n const mergedRunCreateParams = await mergeRuntimeEnvIntoRunCreates([\n runCreate,\n ]);\n const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, {\n method: "POST",\n headers,\n body: JSON.stringify(mergedRunCreateParams[0]),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "create run");\n }\n /**\n * Batch ingest/upsert multiple runs in the Langsmith system.\n * @param runs\n */\n async batchIngestRuns({ runCreates, runUpdates, }) {\n if (runCreates === undefined && runUpdates === undefined) {\n return;\n }\n let preparedCreateParams = runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? [];\n let preparedUpdateParams = runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? [];\n if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {\n const createById = preparedCreateParams.reduce((params, run) => {\n if (!run.id) {\n return params;\n }\n params[run.id] = run;\n return params;\n }, {});\n const standaloneUpdates = [];\n for (const updateParam of preparedUpdateParams) {\n if (updateParam.id !== undefined && createById[updateParam.id]) {\n createById[updateParam.id] = {\n ...createById[updateParam.id],\n ...updateParam,\n };\n }\n else {\n standaloneUpdates.push(updateParam);\n }\n }\n preparedCreateParams = Object.values(createById);\n preparedUpdateParams = standaloneUpdates;\n }\n const rawBatch = {\n post: this._filterForSampling(preparedCreateParams),\n patch: this._filterForSampling(preparedUpdateParams, true),\n };\n if (!rawBatch.post.length && !rawBatch.patch.length) {\n return;\n }\n preparedCreateParams = await mergeRuntimeEnvIntoRunCreates(preparedCreateParams);\n if (this.batchEndpointSupported === undefined) {\n this.batchEndpointSupported = await this.batchEndpointIsSupported();\n }\n if (!this.batchEndpointSupported) {\n this.autoBatchTracing = false;\n for (const preparedCreateParam of rawBatch.post) {\n await this.createRun(preparedCreateParam);\n }\n for (const preparedUpdateParam of rawBatch.patch) {\n if (preparedUpdateParam.id !== undefined) {\n await this.updateRun(preparedUpdateParam.id, preparedUpdateParam);\n }\n }\n return;\n }\n const sizeLimitBytes = this.serverInfo?.batch_ingest_config?.size_limit_bytes ??\n DEFAULT_BATCH_SIZE_LIMIT_BYTES;\n const batchChunks = {\n post: [],\n patch: [],\n };\n let currentBatchSizeBytes = 0;\n for (const k of ["post", "patch"]) {\n const key = k;\n const batchItems = rawBatch[key].reverse();\n let batchItem = batchItems.pop();\n while (batchItem !== undefined) {\n const stringifiedBatchItem = JSON.stringify(batchItem);\n if (currentBatchSizeBytes > 0 &&\n currentBatchSizeBytes + stringifiedBatchItem.length > sizeLimitBytes) {\n await this._postBatchIngestRuns(JSON.stringify(batchChunks));\n currentBatchSizeBytes = 0;\n batchChunks.post = [];\n batchChunks.patch = [];\n }\n currentBatchSizeBytes += stringifiedBatchItem.length;\n batchChunks[key].push(batchItem);\n batchItem = batchItems.pop();\n }\n }\n if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) {\n await this._postBatchIngestRuns(JSON.stringify(batchChunks));\n }\n }\n async _postBatchIngestRuns(body) {\n const headers = {\n ...this.headers,\n "Content-Type": "application/json",\n Accept: "application/json",\n };\n const response = await this.batchIngestCaller.call(fetch, `${this.apiUrl}/runs/batch`, {\n method: "POST",\n headers,\n body: body,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "batch create run");\n }\n async updateRun(runId, run) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(runId);\n if (run.inputs) {\n run.inputs = this.processInputs(run.inputs);\n }\n if (run.outputs) {\n run.outputs = this.processOutputs(run.outputs);\n }\n // TODO: Untangle types\n const data = { ...run, id: runId };\n if (!this._filterForSampling([data], true).length) {\n return;\n }\n if (this.autoBatchTracing &&\n data.trace_id !== undefined &&\n data.dotted_order !== undefined) {\n if (run.end_time !== undefined && data.parent_run_id === undefined) {\n // Trigger a batch as soon as a root trace ends and block to ensure trace finishes\n // in serverless environments.\n await this.processRunOperation({ action: "update", item: data }, true);\n return;\n }\n else {\n void this.processRunOperation({ action: "update", item: data }).catch(console.error);\n }\n return;\n }\n const headers = { ...this.headers, "Content-Type": "application/json" };\n const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, {\n method: "PATCH",\n headers,\n body: JSON.stringify(run),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "update run");\n }\n async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(runId);\n let run = await this._get(`/runs/${runId}`);\n if (loadChildRuns && run.child_run_ids) {\n run = await this._loadChildRuns(run);\n }\n return run;\n }\n async getRunUrl({ runId, run, projectOpts, }) {\n if (run !== undefined) {\n let sessionId;\n if (run.session_id) {\n sessionId = run.session_id;\n }\n else if (projectOpts?.projectName) {\n sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id;\n }\n else if (projectOpts?.projectId) {\n sessionId = projectOpts?.projectId;\n }\n else {\n const project = await this.readProject({\n projectName: (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_2__.getEnvironmentVariable)("LANGCHAIN_PROJECT") || "default",\n });\n sessionId = project.id;\n }\n const tenantId = await this._getTenantId();\n return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`;\n }\n else if (runId !== undefined) {\n const run_ = await this.readRun(runId);\n if (!run_.app_path) {\n throw new Error(`Run ${runId} has no app_path`);\n }\n const baseUrl = this.getHostUrl();\n return `${baseUrl}${run_.app_path}`;\n }\n else {\n throw new Error("Must provide either runId or run");\n }\n }\n async _loadChildRuns(run) {\n const childRuns = await toArray(this.listRuns({ id: run.child_run_ids }));\n const treemap = {};\n const runs = {};\n // TODO: make dotted order required when the migration finishes\n childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? ""));\n for (const childRun of childRuns) {\n if (childRun.parent_run_id === null ||\n childRun.parent_run_id === undefined) {\n throw new Error(`Child run ${childRun.id} has no parent`);\n }\n if (!(childRun.parent_run_id in treemap)) {\n treemap[childRun.parent_run_id] = [];\n }\n treemap[childRun.parent_run_id].push(childRun);\n runs[childRun.id] = childRun;\n }\n run.child_runs = treemap[run.id] || [];\n for (const runId in treemap) {\n if (runId !== run.id) {\n runs[runId].child_runs = treemap[runId];\n }\n }\n return run;\n }\n /**\n * List runs from the LangSmith server.\n * @param projectId - The ID of the project to filter by.\n * @param projectName - The name of the project to filter by.\n * @param parentRunId - The ID of the parent run to filter by.\n * @param traceId - The ID of the trace to filter by.\n * @param referenceExampleId - The ID of the reference example to filter by.\n * @param startTime - The start time to filter by.\n * @param isRoot - Indicates whether to only return root runs.\n * @param runType - The run type to filter by.\n * @param error - Indicates whether to filter by error runs.\n * @param id - The ID of the run to filter by.\n * @param query - The query string to filter by.\n * @param filter - The filter string to apply to the run spans.\n * @param traceFilter - The filter string to apply on the root run of the trace.\n * @param limit - The maximum number of runs to retrieve.\n * @returns {AsyncIterable<Run>} - The runs.\n *\n * @example\n * // List all runs in a project\n * const projectRuns = client.listRuns({ projectName: "<your_project>" });\n *\n * @example\n * // List LLM and Chat runs in the last 24 hours\n * const todaysLLMRuns = client.listRuns({\n * projectName: "<your_project>",\n * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),\n * run_type: "llm",\n * });\n *\n * @example\n * // List traces in a project\n * const rootRuns = client.listRuns({\n * projectName: "<your_project>",\n * execution_order: 1,\n * });\n *\n * @example\n * // List runs without errors\n * const correctRuns = client.listRuns({\n * projectName: "<your_project>",\n * error: false,\n * });\n *\n * @example\n * // List runs by run ID\n * const runIds = [\n * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",\n * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",\n * ];\n * const selectedRuns = client.listRuns({ run_ids: runIds });\n *\n * @example\n * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000\n * const chainRuns = client.listRuns({\n * projectName: "<your_project>",\n * filter: \'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))\',\n * });\n *\n * @example\n * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1\n * const goodExtractorRuns = client.listRuns({\n * projectName: "<your_project>",\n * filter: \'eq(name, "extractor")\',\n * traceFilter: \'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))\',\n * });\n *\n * @example\n * // 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\n * const complexRuns = client.listRuns({\n * projectName: "<your_project>",\n * filter: \'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))\',\n * });\n *\n * @example\n * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds\n * const taggedRuns = client.listRuns({\n * projectName: "<your_project>",\n * filter: \'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))\',\n * });\n */\n async *listRuns(props) {\n const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, } = props;\n let projectIds = [];\n if (projectId) {\n projectIds = Array.isArray(projectId) ? projectId : [projectId];\n }\n if (projectName) {\n const projectNames = Array.isArray(projectName)\n ? projectName\n : [projectName];\n const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));\n projectIds.push(...projectIds_);\n }\n const default_select = [\n "app_path",\n "child_run_ids",\n "completion_cost",\n "completion_tokens",\n "dotted_order",\n "end_time",\n "error",\n "events",\n "extra",\n "feedback_stats",\n "first_token_time",\n "id",\n "inputs",\n "name",\n "outputs",\n "parent_run_id",\n "parent_run_ids",\n "prompt_cost",\n "prompt_tokens",\n "reference_example_id",\n "run_type",\n "session_id",\n "start_time",\n "status",\n "tags",\n "total_cost",\n "total_tokens",\n "trace_id",\n ];\n const body = {\n session: projectIds.length ? projectIds : null,\n run_type: runType,\n reference_example: referenceExampleId,\n query,\n filter,\n trace_filter: traceFilter,\n tree_filter: treeFilter,\n execution_order: executionOrder,\n parent_run: parentRunId,\n start_time: startTime ? startTime.toISOString() : null,\n error,\n id,\n limit,\n trace: traceId,\n select: select ? select : default_select,\n is_root: isRoot,\n };\n let runsYielded = 0;\n for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {\n if (limit) {\n if (runsYielded >= limit) {\n break;\n }\n if (runs.length + runsYielded > limit) {\n const newRuns = runs.slice(0, limit - runsYielded);\n yield* newRuns;\n break;\n }\n runsYielded += runs.length;\n yield* runs;\n }\n else {\n yield* runs;\n }\n }\n }\n async shareRun(runId, { shareId } = {}) {\n const data = {\n run_id: runId,\n share_token: shareId || uuid__WEBPACK_IMPORTED_MODULE_6__["default"](),\n };\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(runId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, {\n method: "PUT",\n headers: this.headers,\n body: JSON.stringify(data),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const result = await response.json();\n if (result === null || !("share_token" in result)) {\n throw new Error("Invalid response from server");\n }\n return `${this.getHostUrl()}/public/${result["share_token"]}/r`;\n }\n async unshareRun(runId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(runId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, {\n method: "DELETE",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "unshare run");\n }\n async readRunSharedLink(runId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(runId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const result = await response.json();\n if (result === null || !("share_token" in result)) {\n return undefined;\n }\n return `${this.getHostUrl()}/public/${result["share_token"]}/r`;\n }\n async listSharedRuns(shareToken, { runIds, } = {}) {\n const queryParams = new URLSearchParams({\n share_token: shareToken,\n });\n if (runIds !== undefined) {\n for (const runId of runIds) {\n queryParams.append("id", runId);\n }\n }\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(shareToken);\n const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const runs = await response.json();\n return runs;\n }\n async readDatasetSharedSchema(datasetId, datasetName) {\n if (!datasetId && !datasetName) {\n throw new Error("Either datasetId or datasetName must be given");\n }\n if (!datasetId) {\n const dataset = await this.readDataset({ datasetName });\n datasetId = dataset.id;\n }\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(datasetId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const shareSchema = await response.json();\n shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;\n return shareSchema;\n }\n async shareDataset(datasetId, datasetName) {\n if (!datasetId && !datasetName) {\n throw new Error("Either datasetId or datasetName must be given");\n }\n if (!datasetId) {\n const dataset = await this.readDataset({ datasetName });\n datasetId = dataset.id;\n }\n const data = {\n dataset_id: datasetId,\n };\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(datasetId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, {\n method: "PUT",\n headers: this.headers,\n body: JSON.stringify(data),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const shareSchema = await response.json();\n shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;\n return shareSchema;\n }\n async unshareDataset(datasetId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(datasetId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${datasetId}/share`, {\n method: "DELETE",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "unshare dataset");\n }\n async readSharedDataset(shareToken) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(shareToken);\n const response = await this.caller.call(fetch, `${this.apiUrl}/public/${shareToken}/datasets`, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const dataset = await response.json();\n return dataset;\n }\n async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) {\n const upsert_ = upsert ? `?upsert=true` : "";\n const endpoint = `${this.apiUrl}/sessions${upsert_}`;\n const extra = projectExtra || {};\n if (metadata) {\n extra["metadata"] = metadata;\n }\n const body = {\n name: projectName,\n extra,\n description,\n };\n if (referenceDatasetId !== null) {\n body["reference_dataset_id"] = referenceDatasetId;\n }\n const response = await this.caller.call(fetch, endpoint, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const result = await response.json();\n if (!response.ok) {\n throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`);\n }\n return result;\n }\n async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) {\n const endpoint = `${this.apiUrl}/sessions/${projectId}`;\n let extra = projectExtra;\n if (metadata) {\n extra = { ...(extra || {}), metadata };\n }\n const body = {\n name,\n extra,\n description,\n end_time: endTime ? new Date(endTime).toISOString() : null,\n };\n const response = await this.caller.call(fetch, endpoint, {\n method: "PATCH",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const result = await response.json();\n if (!response.ok) {\n throw new Error(`Failed to update project ${projectId}: ${response.status} ${response.statusText}`);\n }\n return result;\n }\n async hasProject({ projectId, projectName, }) {\n // TODO: Add a head request\n let path = "/sessions";\n const params = new URLSearchParams();\n if (projectId !== undefined && projectName !== undefined) {\n throw new Error("Must provide either projectName or projectId, not both");\n }\n else if (projectId !== undefined) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(projectId);\n path += `/${projectId}`;\n }\n else if (projectName !== undefined) {\n params.append("name", projectName);\n }\n else {\n throw new Error("Must provide projectName or projectId");\n }\n const response = await this.caller.call(fetch, `${this.apiUrl}${path}?${params}`, {\n method: "GET",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n // consume the response body to release the connection\n // https://undici.nodejs.org/#/?id=garbage-collection\n try {\n const result = await response.json();\n if (!response.ok) {\n return false;\n }\n // If it\'s OK and we\'re querying by name, need to check the list is not empty\n if (Array.isArray(result)) {\n return result.length > 0;\n }\n // projectId querying\n return true;\n }\n catch (e) {\n return false;\n }\n }\n async readProject({ projectId, projectName, includeStats, }) {\n let path = "/sessions";\n const params = new URLSearchParams();\n if (projectId !== undefined && projectName !== undefined) {\n throw new Error("Must provide either projectName or projectId, not both");\n }\n else if (projectId !== undefined) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(projectId);\n path += `/${projectId}`;\n }\n else if (projectName !== undefined) {\n params.append("name", projectName);\n }\n else {\n throw new Error("Must provide projectName or projectId");\n }\n if (includeStats !== undefined) {\n params.append("include_stats", includeStats.toString());\n }\n const response = await this._get(path, params);\n let result;\n if (Array.isArray(response)) {\n if (response.length === 0) {\n throw new Error(`Project[id=${projectId}, name=${projectName}] not found`);\n }\n result = response[0];\n }\n else {\n result = response;\n }\n return result;\n }\n async getProjectUrl({ projectId, projectName, }) {\n if (projectId === undefined && projectName === undefined) {\n throw new Error("Must provide either projectName or projectId");\n }\n const project = await this.readProject({ projectId, projectName });\n const tenantId = await this._getTenantId();\n return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`;\n }\n async getDatasetUrl({ datasetId, datasetName, }) {\n if (datasetId === undefined && datasetName === undefined) {\n throw new Error("Must provide either datasetName or datasetId");\n }\n const dataset = await this.readDataset({ datasetId, datasetName });\n const tenantId = await this._getTenantId();\n return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`;\n }\n async _getTenantId() {\n if (this._tenantId !== null) {\n return this._tenantId;\n }\n const queryParams = new URLSearchParams({ limit: "1" });\n for await (const projects of this._getPaginated("/sessions", queryParams)) {\n this._tenantId = projects[0].tenant_id;\n return projects[0].tenant_id;\n }\n throw new Error("No projects found to resolve tenant.");\n }\n async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, } = {}) {\n const params = new URLSearchParams();\n if (projectIds !== undefined) {\n for (const projectId of projectIds) {\n params.append("id", projectId);\n }\n }\n if (name !== undefined) {\n params.append("name", name);\n }\n if (nameContains !== undefined) {\n params.append("name_contains", nameContains);\n }\n if (referenceDatasetId !== undefined) {\n params.append("reference_dataset", referenceDatasetId);\n }\n else if (referenceDatasetName !== undefined) {\n const dataset = await this.readDataset({\n datasetName: referenceDatasetName,\n });\n params.append("reference_dataset", dataset.id);\n }\n if (referenceFree !== undefined) {\n params.append("reference_free", referenceFree.toString());\n }\n for await (const projects of this._getPaginated("/sessions", params)) {\n yield* projects;\n }\n }\n async deleteProject({ projectId, projectName, }) {\n let projectId_;\n if (projectId === undefined && projectName === undefined) {\n throw new Error("Must provide projectName or projectId");\n }\n else if (projectId !== undefined && projectName !== undefined) {\n throw new Error("Must provide either projectName or projectId, not both");\n }\n else if (projectId === undefined) {\n projectId_ = (await this.readProject({ projectName })).id;\n }\n else {\n projectId_ = projectId;\n }\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(projectId_);\n const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, {\n method: "DELETE",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, `delete session ${projectId_} (${projectName})`);\n }\n async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) {\n const url = `${this.apiUrl}/datasets/upload`;\n const formData = new FormData();\n formData.append("file", csvFile, fileName);\n inputKeys.forEach((key) => {\n formData.append("input_keys", key);\n });\n outputKeys.forEach((key) => {\n formData.append("output_keys", key);\n });\n if (description) {\n formData.append("description", description);\n }\n if (dataType) {\n formData.append("data_type", dataType);\n }\n if (name) {\n formData.append("name", name);\n }\n const response = await this.caller.call(fetch, url, {\n method: "POST",\n headers: this.headers,\n body: formData,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n const result = await response.json();\n if (result.detail && result.detail.includes("already exists")) {\n throw new Error(`Dataset ${fileName} already exists`);\n }\n throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`);\n }\n const result = await response.json();\n return result;\n }\n async createDataset(name, { description, dataType, } = {}) {\n const body = {\n name,\n description,\n };\n if (dataType) {\n body.data_type = dataType;\n }\n const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n const result = await response.json();\n if (result.detail && result.detail.includes("already exists")) {\n throw new Error(`Dataset ${name} already exists`);\n }\n throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`);\n }\n const result = await response.json();\n return result;\n }\n async readDataset({ datasetId, datasetName, }) {\n let path = "/datasets";\n // limit to 1 result\n const params = new URLSearchParams({ limit: "1" });\n if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error("Must provide either datasetName or datasetId, not both");\n }\n else if (datasetId !== undefined) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(datasetId);\n path += `/${datasetId}`;\n }\n else if (datasetName !== undefined) {\n params.append("name", datasetName);\n }\n else {\n throw new Error("Must provide datasetName or datasetId");\n }\n const response = await this._get(path, params);\n let result;\n if (Array.isArray(response)) {\n if (response.length === 0) {\n throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`);\n }\n result = response[0];\n }\n else {\n result = response;\n }\n return result;\n }\n async hasDataset({ datasetId, datasetName, }) {\n try {\n await this.readDataset({ datasetId, datasetName });\n return true;\n }\n catch (e) {\n if (\n // eslint-disable-next-line no-instanceof/no-instanceof\n e instanceof Error &&\n e.message.toLocaleLowerCase().includes("not found")) {\n return false;\n }\n throw e;\n }\n }\n async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) {\n let datasetId_ = datasetId;\n if (datasetId_ === undefined && datasetName === undefined) {\n throw new Error("Must provide either datasetName or datasetId");\n }\n else if (datasetId_ !== undefined && datasetName !== undefined) {\n throw new Error("Must provide either datasetName or datasetId, not both");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n const urlParams = new URLSearchParams({\n from_version: typeof fromVersion === "string"\n ? fromVersion\n : fromVersion.toISOString(),\n to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(),\n });\n const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams);\n return response;\n }\n async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) {\n const path = "/datasets";\n if (datasetId !== undefined) {\n // do nothing\n }\n else if (datasetName !== undefined) {\n datasetId = (await this.readDataset({ datasetName })).id;\n }\n else {\n throw new Error("Must provide datasetName or datasetId");\n }\n const response = await this._getResponse(`${path}/${datasetId}/openai_ft`);\n const datasetText = await response.text();\n const dataset = datasetText\n .trim()\n .split("\\n")\n .map((line) => JSON.parse(line));\n return dataset;\n }\n async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, } = {}) {\n const path = "/datasets";\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n if (datasetIds !== undefined) {\n for (const id_ of datasetIds) {\n params.append("id", id_);\n }\n }\n if (datasetName !== undefined) {\n params.append("name", datasetName);\n }\n if (datasetNameContains !== undefined) {\n params.append("name_contains", datasetNameContains);\n }\n for await (const datasets of this._getPaginated(path, params)) {\n yield* datasets;\n }\n }\n /**\n * Update a dataset\n * @param props The dataset details to update\n * @returns The updated dataset\n */\n async updateDataset(props) {\n const { datasetId, datasetName, ...update } = props;\n if (!datasetId && !datasetName) {\n throw new Error("Must provide either datasetName or datasetId");\n }\n const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id;\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(_datasetId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/${_datasetId}`, {\n method: "PATCH",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(update),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to update dataset ${_datasetId}: ${response.status} ${response.statusText}`);\n }\n return (await response.json());\n }\n async deleteDataset({ datasetId, datasetName, }) {\n let path = "/datasets";\n let datasetId_ = datasetId;\n if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error("Must provide either datasetName or datasetId, not both");\n }\n else if (datasetName !== undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n if (datasetId_ !== undefined) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(datasetId_);\n path += `/${datasetId_}`;\n }\n else {\n throw new Error("Must provide datasetName or datasetId");\n }\n const response = await this.caller.call(fetch, this.apiUrl + path, {\n method: "DELETE",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);\n }\n await response.json();\n }\n async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId, metadata, split, }) {\n let datasetId_ = datasetId;\n if (datasetId_ === undefined && datasetName === undefined) {\n throw new Error("Must provide either datasetName or datasetId");\n }\n else if (datasetId_ !== undefined && datasetName !== undefined) {\n throw new Error("Must provide either datasetName or datasetId, not both");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n const createdAt_ = createdAt || new Date();\n const data = {\n dataset_id: datasetId_,\n inputs,\n outputs,\n created_at: createdAt_?.toISOString(),\n id: exampleId,\n metadata,\n split,\n };\n const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(data),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to create example: ${response.status} ${response.statusText}`);\n }\n const result = await response.json();\n return result;\n }\n async createExamples(props) {\n const { inputs, outputs, metadata, sourceRunIds, exampleIds, datasetId, datasetName, } = props;\n let datasetId_ = datasetId;\n if (datasetId_ === undefined && datasetName === undefined) {\n throw new Error("Must provide either datasetName or datasetId");\n }\n else if (datasetId_ !== undefined && datasetName !== undefined) {\n throw new Error("Must provide either datasetName or datasetId, not both");\n }\n else if (datasetId_ === undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n const formattedExamples = inputs.map((input, idx) => {\n return {\n dataset_id: datasetId_,\n inputs: input,\n outputs: outputs ? outputs[idx] : undefined,\n metadata: metadata ? metadata[idx] : undefined,\n split: props.splits ? props.splits[idx] : undefined,\n id: exampleIds ? exampleIds[idx] : undefined,\n source_run_id: sourceRunIds ? sourceRunIds[idx] : undefined,\n };\n });\n const response = await this.caller.call(fetch, `${this.apiUrl}/examples/bulk`, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(formattedExamples),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to create examples: ${response.status} ${response.statusText}`);\n }\n const result = await response.json();\n return result;\n }\n async createLLMExample(input, generation, options) {\n return this.createExample({ input }, { output: generation }, options);\n }\n async createChatExample(input, generations, options) {\n const finalInput = input.map((message) => {\n if ((0,_utils_messages_js__WEBPACK_IMPORTED_MODULE_1__.isLangChainMessage)(message)) {\n return (0,_utils_messages_js__WEBPACK_IMPORTED_MODULE_1__.convertLangChainMessageToExample)(message);\n }\n return message;\n });\n const finalOutput = (0,_utils_messages_js__WEBPACK_IMPORTED_MODULE_1__.isLangChainMessage)(generations)\n ? (0,_utils_messages_js__WEBPACK_IMPORTED_MODULE_1__.convertLangChainMessageToExample)(generations)\n : generations;\n return this.createExample({ input: finalInput }, { output: finalOutput }, options);\n }\n async readExample(exampleId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(exampleId);\n const path = `/examples/${exampleId}`;\n return await this._get(path);\n }\n async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, } = {}) {\n let datasetId_;\n if (datasetId !== undefined && datasetName !== undefined) {\n throw new Error("Must provide either datasetName or datasetId, not both");\n }\n else if (datasetId !== undefined) {\n datasetId_ = datasetId;\n }\n else if (datasetName !== undefined) {\n const dataset = await this.readDataset({ datasetName });\n datasetId_ = dataset.id;\n }\n else {\n throw new Error("Must provide a datasetName or datasetId");\n }\n const params = new URLSearchParams({ dataset: datasetId_ });\n const dataset_version = asOf\n ? typeof asOf === "string"\n ? asOf\n : asOf?.toISOString()\n : undefined;\n if (dataset_version) {\n params.append("as_of", dataset_version);\n }\n const inlineS3Urls_ = inlineS3Urls ?? true;\n params.append("inline_s3_urls", inlineS3Urls_.toString());\n if (exampleIds !== undefined) {\n for (const id_ of exampleIds) {\n params.append("id", id_);\n }\n }\n if (splits !== undefined) {\n for (const split of splits) {\n params.append("splits", split);\n }\n }\n if (metadata !== undefined) {\n const serializedMetadata = JSON.stringify(metadata);\n params.append("metadata", serializedMetadata);\n }\n for await (const examples of this._getPaginated("/examples", params)) {\n yield* examples;\n }\n }\n async deleteExample(exampleId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(exampleId);\n const path = `/examples/${exampleId}`;\n const response = await this.caller.call(fetch, this.apiUrl + path, {\n method: "DELETE",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);\n }\n await response.json();\n }\n async updateExample(exampleId, update) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(exampleId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, {\n method: "PATCH",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(update),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`);\n }\n const result = await response.json();\n return result;\n }\n /**\n * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.\n */\n async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) {\n (0,_utils_warn_js__WEBPACK_IMPORTED_MODULE_5__.warnOnce)("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");\n let run_;\n if (typeof run === "string") {\n run_ = await this.readRun(run, { loadChildRuns });\n }\n else if (typeof run === "object" && "id" in run) {\n run_ = run;\n }\n else {\n throw new Error(`Invalid run type: ${typeof run}`);\n }\n if (run_.reference_example_id !== null &&\n run_.reference_example_id !== undefined) {\n referenceExample = await this.readExample(run_.reference_example_id);\n }\n const feedbackResult = await evaluator.evaluateRun(run_, referenceExample);\n const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo);\n return feedbacks[0];\n }\n async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) {\n if (!runId && !projectId) {\n throw new Error("One of runId or projectId must be provided");\n }\n if (runId && projectId) {\n throw new Error("Only one of runId or projectId can be provided");\n }\n const feedback_source = {\n type: feedbackSourceType ?? "api",\n metadata: sourceInfo ?? {},\n };\n if (sourceRunId !== undefined &&\n feedback_source?.metadata !== undefined &&\n !feedback_source.metadata["__run"]) {\n feedback_source.metadata["__run"] = { run_id: sourceRunId };\n }\n if (feedback_source?.metadata !== undefined &&\n feedback_source.metadata["__run"]?.run_id !== undefined) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(feedback_source.metadata["__run"].run_id);\n }\n const feedback = {\n id: feedbackId ?? uuid__WEBPACK_IMPORTED_MODULE_6__["default"](),\n run_id: runId,\n key,\n score,\n value,\n correction,\n comment,\n feedback_source: feedback_source,\n comparative_experiment_id: comparativeExperimentId,\n feedbackConfig,\n session_id: projectId,\n };\n const url = `${this.apiUrl}/feedback`;\n const response = await this.caller.call(fetch, url, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(feedback),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "create feedback");\n return feedback;\n }\n async updateFeedback(feedbackId, { score, value, correction, comment, }) {\n const feedbackUpdate = {};\n if (score !== undefined && score !== null) {\n feedbackUpdate["score"] = score;\n }\n if (value !== undefined && value !== null) {\n feedbackUpdate["value"] = value;\n }\n if (correction !== undefined && correction !== null) {\n feedbackUpdate["correction"] = correction;\n }\n if (comment !== undefined && comment !== null) {\n feedbackUpdate["comment"] = comment;\n }\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(feedbackId);\n const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/${feedbackId}`, {\n method: "PATCH",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(feedbackUpdate),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n await raiseForStatus(response, "update feedback");\n }\n async readFeedback(feedbackId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(feedbackId);\n const path = `/feedback/${feedbackId}`;\n const response = await this._get(path);\n return response;\n }\n async deleteFeedback(feedbackId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(feedbackId);\n const path = `/feedback/${feedbackId}`;\n const response = await this.caller.call(fetch, this.apiUrl + path, {\n method: "DELETE",\n headers: this.headers,\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n if (!response.ok) {\n throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`);\n }\n await response.json();\n }\n async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) {\n const queryParams = new URLSearchParams();\n if (runIds) {\n queryParams.append("run", runIds.join(","));\n }\n if (feedbackKeys) {\n for (const key of feedbackKeys) {\n queryParams.append("key", key);\n }\n }\n if (feedbackSourceTypes) {\n for (const type of feedbackSourceTypes) {\n queryParams.append("source", type);\n }\n }\n for await (const feedbacks of this._getPaginated("/feedback", queryParams)) {\n yield* feedbacks;\n }\n }\n /**\n * Creates a presigned feedback token and URL.\n *\n * The token can be used to authorize feedback metrics without\n * needing an API key. This is useful for giving browser-based\n * applications the ability to submit feedback without needing\n * to expose an API key.\n *\n * @param runId - The ID of the run.\n * @param feedbackKey - The feedback key.\n * @param options - Additional options for the token.\n * @param options.expiration - The expiration time for the token.\n *\n * @returns A promise that resolves to a FeedbackIngestToken.\n */\n async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) {\n const body = {\n run_id: runId,\n feedback_key: feedbackKey,\n feedback_config: feedbackConfig,\n };\n if (expiration) {\n if (typeof expiration === "string") {\n body["expires_at"] = expiration;\n }\n else if (expiration?.hours || expiration?.minutes || expiration?.days) {\n body["expires_in"] = expiration;\n }\n }\n else {\n body["expires_in"] = {\n hours: 3,\n };\n }\n const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/tokens`, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n const result = await response.json();\n return result;\n }\n async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) {\n if (experimentIds.length === 0) {\n throw new Error("At least one experiment is required");\n }\n if (!referenceDatasetId) {\n referenceDatasetId = (await this.readProject({\n projectId: experimentIds[0],\n })).reference_dataset_id;\n }\n if (!referenceDatasetId == null) {\n throw new Error("A reference dataset is required");\n }\n const body = {\n id,\n name,\n experiment_ids: experimentIds,\n reference_dataset_id: referenceDatasetId,\n description,\n created_at: (createdAt ?? new Date())?.toISOString(),\n extra: {},\n };\n if (metadata)\n body.extra["metadata"] = metadata;\n const response = await this.caller.call(fetch, `${this.apiUrl}/datasets/comparative`, {\n method: "POST",\n headers: { ...this.headers, "Content-Type": "application/json" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(this.timeout_ms),\n ...this.fetchOptions,\n });\n return await response.json();\n }\n /**\n * Retrieves a list of presigned feedback tokens for a given run ID.\n * @param runId The ID of the run.\n * @returns An async iterable of FeedbackIngestToken objects.\n */\n async *listPresignedFeedbackTokens(runId) {\n (0,_utils_uuid_js__WEBPACK_IMPORTED_MODULE_4__.assertUuid)(runId);\n const params = new URLSearchParams({ run_id: runId });\n for await (const tokens of this._getPaginated("/feedback/tokens", params)) {\n yield* tokens;\n }\n }\n _selectEvalResults(results) {\n let results_;\n if ("results" in results) {\n results_ = results.results;\n }\n else {\n results_ = [results];\n }\n return results_;\n }\n async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {\n const evalResults = this._selectEvalResults(evaluatorResponse);\n const feedbacks = [];\n for (const res of evalResults) {\n let sourceInfo_ = sourceInfo || {};\n if (res.evaluatorInfo) {\n sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ };\n }\n let runId_ = null;\n if (res.targetRunId) {\n runId_ = res.targetRunId;\n }\n else if (run) {\n runId_ = run.id;\n }\n feedbacks.push(await this.createFeedback(runId_, res.key, {\n score: res.score,\n value: res.value,\n comment: res.comment,\n correction: res.correction,\n sourceInfo: sourceInfo_,\n sourceRunId: res.sourceRunId,\n feedbackConfig: res.feedbackConfig,\n feedbackSourceType: "model",\n }));\n }\n return [evalResults, feedbacks];\n }\n async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {\n const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo);\n return results;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/client.js?');
|
|
718
|
+
/***/
|
|
719
|
+
},
|
|
720
|
+
/***/ "./node_modules/langsmith/dist/env.js":
|
|
721
|
+
/*!********************************************!*\
|
|
722
|
+
!*** ./node_modules/langsmith/dist/env.js ***!
|
|
723
|
+
\********************************************/
|
|
724
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
725
|
+
"use strict";
|
|
726
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isTracingEnabled: () => (/* binding */ isTracingEnabled)\n/* harmony export */ });\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/env.js */ "./node_modules/langsmith/dist/utils/env.js");\n\nconst isTracingEnabled = (tracingEnabled) => {\n if (tracingEnabled !== undefined) {\n return tracingEnabled;\n }\n const envVars = [\n "LANGSMITH_TRACING_V2",\n "LANGCHAIN_TRACING_V2",\n "LANGSMITH_TRACING",\n "LANGCHAIN_TRACING",\n ];\n return !!envVars.find((envVar) => (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_0__.getEnvironmentVariable)(envVar) === "true");\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/env.js?');
|
|
727
|
+
/***/
|
|
728
|
+
},
|
|
729
|
+
/***/ "./node_modules/langsmith/dist/index.js":
|
|
730
|
+
/*!**********************************************!*\
|
|
731
|
+
!*** ./node_modules/langsmith/dist/index.js ***!
|
|
732
|
+
\**********************************************/
|
|
733
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
734
|
+
"use strict";
|
|
735
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Client: () => (/* reexport safe */ _client_js__WEBPACK_IMPORTED_MODULE_0__.Client),\n/* harmony export */ RunTree: () => (/* reexport safe */ _run_trees_js__WEBPACK_IMPORTED_MODULE_1__.RunTree),\n/* harmony export */ __version__: () => (/* binding */ __version__)\n/* harmony export */ });\n/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./client.js */ "./node_modules/langsmith/dist/client.js");\n/* harmony import */ var _run_trees_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./run_trees.js */ "./node_modules/langsmith/dist/run_trees.js");\n\n\n// Update using yarn bump-version\nconst __version__ = "0.1.34";\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/index.js?');
|
|
736
|
+
/***/
|
|
737
|
+
},
|
|
738
|
+
/***/ "./node_modules/langsmith/dist/run_trees.js":
|
|
739
|
+
/*!**************************************************!*\
|
|
740
|
+
!*** ./node_modules/langsmith/dist/run_trees.js ***!
|
|
741
|
+
\**************************************************/
|
|
742
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
743
|
+
"use strict";
|
|
744
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RunTree: () => (/* binding */ RunTree),\n/* harmony export */ convertToDottedOrderFormat: () => (/* binding */ convertToDottedOrderFormat),\n/* harmony export */ isRunTree: () => (/* binding */ isRunTree),\n/* harmony export */ isRunnableConfigLike: () => (/* binding */ isRunnableConfigLike)\n/* harmony export */ });\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/v4.js");\n/* harmony import */ var _utils_env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/env.js */ "./node_modules/langsmith/dist/utils/env.js");\n/* harmony import */ var _client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./client.js */ "./node_modules/langsmith/dist/client.js");\n/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./env.js */ "./node_modules/langsmith/dist/env.js");\n/* harmony import */ var _utils_warn_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/warn.js */ "./node_modules/langsmith/dist/utils/warn.js");\n\n\n\n\n\nfunction stripNonAlphanumeric(input) {\n return input.replace(/[-:.]/g, "");\n}\nfunction convertToDottedOrderFormat(epoch, runId, executionOrder = 1) {\n // Date only has millisecond precision, so we use the microseconds to break\n // possible ties, avoiding incorrect run order\n const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0");\n return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId);\n}\n/**\n * Baggage header information\n */\nclass Baggage {\n constructor(metadata, tags) {\n Object.defineProperty(this, "metadata", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "tags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.metadata = metadata;\n this.tags = tags;\n }\n static fromHeader(value) {\n const items = value.split(",");\n let metadata = {};\n let tags = [];\n for (const item of items) {\n const [key, uriValue] = item.split("=");\n const value = decodeURIComponent(uriValue);\n if (key === "langsmith-metadata") {\n metadata = JSON.parse(value);\n }\n else if (key === "langsmith-tags") {\n tags = value.split(",");\n }\n }\n return new Baggage(metadata, tags);\n }\n toHeader() {\n const items = [];\n if (this.metadata && Object.keys(this.metadata).length > 0) {\n items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);\n }\n if (this.tags && this.tags.length > 0) {\n items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);\n }\n return items.join(",");\n }\n}\nclass RunTree {\n constructor(originalConfig) {\n Object.defineProperty(this, "id", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "run_type", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "project_name", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "parent_run", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "child_runs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "start_time", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "end_time", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "extra", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "tags", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "error", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "serialized", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "inputs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "outputs", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "reference_example_id", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "client", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "events", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "trace_id", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "dotted_order", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "tracingEnabled", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "execution_order", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "child_execution_order", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n const defaultConfig = RunTree.getDefaultConfig();\n const { metadata, ...config } = originalConfig;\n const client = config.client ?? new _client_js__WEBPACK_IMPORTED_MODULE_1__.Client();\n const dedupedMetadata = {\n ...metadata,\n ...config?.extra?.metadata,\n };\n config.extra = { ...config.extra, metadata: dedupedMetadata };\n Object.assign(this, { ...defaultConfig, ...config, client });\n if (!this.trace_id) {\n if (this.parent_run) {\n this.trace_id = this.parent_run.trace_id ?? this.id;\n }\n else {\n this.trace_id = this.id;\n }\n }\n this.execution_order ??= 1;\n this.child_execution_order ??= 1;\n if (!this.dotted_order) {\n const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order);\n if (this.parent_run) {\n this.dotted_order =\n this.parent_run.dotted_order + "." + currentDottedOrder;\n }\n else {\n this.dotted_order = currentDottedOrder;\n }\n }\n }\n static getDefaultConfig() {\n return {\n id: uuid__WEBPACK_IMPORTED_MODULE_4__["default"](),\n run_type: "chain",\n project_name: (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_0__.getEnvironmentVariable)("LANGCHAIN_PROJECT") ??\n (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_0__.getEnvironmentVariable)("LANGCHAIN_SESSION") ?? // TODO: Deprecate\n "default",\n child_runs: [],\n api_url: (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_0__.getEnvironmentVariable)("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984",\n api_key: (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_0__.getEnvironmentVariable)("LANGCHAIN_API_KEY"),\n caller_options: {},\n start_time: Date.now(),\n serialized: {},\n inputs: {},\n extra: {},\n };\n }\n createChild(config) {\n const child_execution_order = this.child_execution_order + 1;\n const child = new RunTree({\n ...config,\n parent_run: this,\n project_name: this.project_name,\n client: this.client,\n tracingEnabled: this.tracingEnabled,\n execution_order: child_execution_order,\n child_execution_order: child_execution_order,\n });\n // propagate child_execution_order upwards\n const visited = new Set();\n let current = this;\n while (current != null && !visited.has(current.id)) {\n visited.add(current.id);\n current.child_execution_order = Math.max(current.child_execution_order, child_execution_order);\n current = current.parent_run;\n }\n this.child_runs.push(child);\n return child;\n }\n async end(outputs, error, endTime = Date.now()) {\n this.outputs = this.outputs ?? outputs;\n this.error = this.error ?? error;\n this.end_time = this.end_time ?? endTime;\n }\n _convertToCreate(run, runtimeEnv, excludeChildRuns = true) {\n const runExtra = run.extra ?? {};\n if (!runExtra.runtime) {\n runExtra.runtime = {};\n }\n if (runtimeEnv) {\n for (const [k, v] of Object.entries(runtimeEnv)) {\n if (!runExtra.runtime[k]) {\n runExtra.runtime[k] = v;\n }\n }\n }\n let child_runs;\n let parent_run_id;\n if (!excludeChildRuns) {\n child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns));\n parent_run_id = undefined;\n }\n else {\n parent_run_id = run.parent_run?.id;\n child_runs = [];\n }\n const persistedRun = {\n id: run.id,\n name: run.name,\n start_time: run.start_time,\n end_time: run.end_time,\n run_type: run.run_type,\n reference_example_id: run.reference_example_id,\n extra: runExtra,\n serialized: run.serialized,\n error: run.error,\n inputs: run.inputs,\n outputs: run.outputs,\n session_name: run.project_name,\n child_runs: child_runs,\n parent_run_id: parent_run_id,\n trace_id: run.trace_id,\n dotted_order: run.dotted_order,\n tags: run.tags,\n };\n return persistedRun;\n }\n async postRun(excludeChildRuns = true) {\n const runtimeEnv = await (0,_utils_env_js__WEBPACK_IMPORTED_MODULE_0__.getRuntimeEnvironment)();\n const runCreate = await this._convertToCreate(this, runtimeEnv, true);\n await this.client.createRun(runCreate);\n if (!excludeChildRuns) {\n (0,_utils_warn_js__WEBPACK_IMPORTED_MODULE_3__.warnOnce)("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");\n for (const childRun of this.child_runs) {\n await childRun.postRun(false);\n }\n }\n }\n async patchRun() {\n const runUpdate = {\n end_time: this.end_time,\n error: this.error,\n inputs: this.inputs,\n outputs: this.outputs,\n parent_run_id: this.parent_run?.id,\n reference_example_id: this.reference_example_id,\n extra: this.extra,\n events: this.events,\n dotted_order: this.dotted_order,\n trace_id: this.trace_id,\n tags: this.tags,\n };\n await this.client.updateRun(this.id, runUpdate);\n }\n toJSON() {\n return this._convertToCreate(this, undefined, false);\n }\n static fromRunnableConfig(parentConfig, props) {\n // We only handle the callback manager case for now\n const callbackManager = parentConfig?.callbacks;\n let parentRun;\n let projectName;\n let client;\n let tracingEnabled = (0,_env_js__WEBPACK_IMPORTED_MODULE_2__.isTracingEnabled)();\n if (callbackManager) {\n const parentRunId = callbackManager?.getParentRunId?.() ?? "";\n const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer");\n parentRun = langChainTracer?.getRun?.(parentRunId);\n projectName = langChainTracer?.projectName;\n client = langChainTracer?.client;\n tracingEnabled = tracingEnabled || !!langChainTracer;\n }\n if (!parentRun) {\n return new RunTree({\n ...props,\n client,\n tracingEnabled,\n project_name: projectName,\n });\n }\n const parentRunTree = new RunTree({\n name: parentRun.name,\n id: parentRun.id,\n client,\n tracingEnabled,\n project_name: projectName,\n tags: [\n ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])),\n ],\n extra: {\n metadata: {\n ...parentRun?.extra?.metadata,\n ...parentConfig?.metadata,\n },\n },\n });\n return parentRunTree.createChild(props);\n }\n static fromDottedOrder(dottedOrder) {\n return this.fromHeaders({ "langsmith-trace": dottedOrder });\n }\n static fromHeaders(headers, inheritArgs) {\n const rawHeaders = "get" in headers && typeof headers.get === "function"\n ? {\n "langsmith-trace": headers.get("langsmith-trace"),\n baggage: headers.get("baggage"),\n }\n : headers;\n const headerTrace = rawHeaders["langsmith-trace"];\n if (!headerTrace || typeof headerTrace !== "string")\n return undefined;\n const parentDottedOrder = headerTrace.trim();\n const parsedDottedOrder = parentDottedOrder.split(".").map((part) => {\n const [strTime, uuid] = part.split("Z");\n return { strTime, time: Date.parse(strTime + "Z"), uuid };\n });\n const traceId = parsedDottedOrder[0].uuid;\n const config = {\n ...inheritArgs,\n name: inheritArgs?.["name"] ?? "parent",\n run_type: inheritArgs?.["run_type"] ?? "chain",\n start_time: inheritArgs?.["start_time"] ?? Date.now(),\n id: parsedDottedOrder.at(-1)?.uuid,\n trace_id: traceId,\n dotted_order: parentDottedOrder,\n };\n if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") {\n const baggage = Baggage.fromHeader(rawHeaders["baggage"]);\n config.metadata = baggage.metadata;\n config.tags = baggage.tags;\n }\n return new RunTree(config);\n }\n toHeaders(headers) {\n const result = {\n "langsmith-trace": this.dotted_order,\n baggage: new Baggage(this.extra?.metadata, this.tags).toHeader(),\n };\n if (headers) {\n for (const [key, value] of Object.entries(result)) {\n headers.set(key, value);\n }\n }\n return result;\n }\n}\nfunction isRunTree(x) {\n return (x !== undefined &&\n typeof x.createChild === "function" &&\n typeof x.postRun === "function");\n}\nfunction containsLangChainTracerLike(x) {\n return (Array.isArray(x) &&\n x.some((callback) => {\n return (typeof callback.name === "string" &&\n callback.name === "langchain_tracer");\n }));\n}\nfunction isRunnableConfigLike(x) {\n // Check that it\'s an object with a callbacks arg\n // that has either a CallbackManagerLike object with a langchain tracer within it\n // or an array with a LangChainTracerLike object within it\n return (x !== undefined &&\n typeof x.callbacks === "object" &&\n // Callback manager with a langchain tracer\n (containsLangChainTracerLike(x.callbacks?.handlers) ||\n // Or it\'s an array with a LangChainTracerLike object within it\n containsLangChainTracerLike(x.callbacks)));\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/run_trees.js?');
|
|
745
|
+
/***/
|
|
746
|
+
},
|
|
747
|
+
/***/ "./node_modules/langsmith/dist/singletons/traceable.js":
|
|
748
|
+
/*!*************************************************************!*\
|
|
749
|
+
!*** ./node_modules/langsmith/dist/singletons/traceable.js ***!
|
|
750
|
+
\*************************************************************/
|
|
751
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
752
|
+
"use strict";
|
|
753
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncLocalStorageProviderSingleton: () => (/* binding */ AsyncLocalStorageProviderSingleton),\n/* harmony export */ ROOT: () => (/* binding */ ROOT),\n/* harmony export */ getCurrentRunTree: () => (/* binding */ getCurrentRunTree),\n/* harmony export */ isTraceableFunction: () => (/* binding */ isTraceableFunction),\n/* harmony export */ withRunTree: () => (/* binding */ withRunTree)\n/* harmony export */ });\nclass MockAsyncLocalStorage {\n getStore() {\n return undefined;\n }\n run(_, callback) {\n return callback();\n }\n}\nclass AsyncLocalStorageProvider {\n constructor() {\n Object.defineProperty(this, "asyncLocalStorage", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new MockAsyncLocalStorage()\n });\n Object.defineProperty(this, "hasBeenInitialized", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n }\n getInstance() {\n return this.asyncLocalStorage;\n }\n initializeGlobalInstance(instance) {\n if (!this.hasBeenInitialized) {\n this.hasBeenInitialized = true;\n this.asyncLocalStorage = instance;\n }\n }\n}\nconst AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider();\n/**\n * Return the current run tree from within a traceable-wrapped function.\n * Will throw an error if called outside of a traceable function.\n *\n * @returns The run tree for the given context.\n */\nconst getCurrentRunTree = () => {\n const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore();\n if (runTree === undefined) {\n throw new Error([\n "Could not get the current run tree.",\n "",\n "Please make sure you are calling this method within a traceable function or the tracing is enabled.",\n ].join("\\n"));\n }\n return runTree;\n};\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction withRunTree(runTree, fn) {\n const storage = AsyncLocalStorageProviderSingleton.getInstance();\n return new Promise((resolve, reject) => {\n storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject));\n });\n}\nconst ROOT = Symbol.for("langsmith:traceable:root");\nfunction isTraceableFunction(x\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n return typeof x === "function" && "langsmith:traceable" in x;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/singletons/traceable.js?');
|
|
754
|
+
/***/
|
|
755
|
+
},
|
|
756
|
+
/***/ "./node_modules/langsmith/dist/utils/_uuid.js":
|
|
757
|
+
/*!****************************************************!*\
|
|
758
|
+
!*** ./node_modules/langsmith/dist/utils/_uuid.js ***!
|
|
759
|
+
\****************************************************/
|
|
760
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
761
|
+
"use strict";
|
|
762
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ assertUuid: () => (/* binding */ assertUuid)\n/* harmony export */ });\n/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uuid */ "./node_modules/uuid/dist/esm-browser/validate.js");\n\nfunction assertUuid(str) {\n if (!uuid__WEBPACK_IMPORTED_MODULE_0__["default"](str)) {\n throw new Error(`Invalid UUID: ${str}`);\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/utils/_uuid.js?');
|
|
763
|
+
/***/
|
|
764
|
+
},
|
|
765
|
+
/***/ "./node_modules/langsmith/dist/utils/async_caller.js":
|
|
766
|
+
/*!***********************************************************!*\
|
|
767
|
+
!*** ./node_modules/langsmith/dist/utils/async_caller.js ***!
|
|
768
|
+
\***********************************************************/
|
|
769
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
770
|
+
"use strict";
|
|
771
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncCaller: () => (/* binding */ AsyncCaller)\n/* harmony export */ });\n/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-retry */ "./node_modules/p-retry/index.js");\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-queue */ "./node_modules/p-queue/dist/index.js");\n\n\nconst STATUS_NO_RETRY = [\n 400, // Bad Request\n 401, // Unauthorized\n 403, // Forbidden\n 404, // Not Found\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 407, // Proxy Authentication Required\n 408, // Request Timeout\n];\nconst STATUS_IGNORE = [\n 409, // Conflict\n];\n/**\n * A class that can be used to make async calls with concurrency and retry logic.\n *\n * This is useful for making calls to any kind of "expensive" external resource,\n * be it because it\'s rate-limited, subject to network issues, etc.\n *\n * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults\n * to `Infinity`. This means that by default, all calls will be made in parallel.\n *\n * Retries are limited by the `maxRetries` parameter, which defaults to 6. This\n * means that by default, each call will be retried up to 6 times, with an\n * exponential backoff between each attempt.\n */\nclass AsyncCaller {\n constructor(params) {\n Object.defineProperty(this, "maxConcurrency", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "maxRetries", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "queue", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, "onFailedResponseHook", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxConcurrency = params.maxConcurrency ?? Infinity;\n this.maxRetries = params.maxRetries ?? 6;\n if ( true) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.queue = new p_queue__WEBPACK_IMPORTED_MODULE_1__["default"]({\n concurrency: this.maxConcurrency,\n });\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.queue = new p_queue__WEBPACK_IMPORTED_MODULE_1__({ concurrency: this.maxConcurrency });\n }\n this.onFailedResponseHook = params?.onFailedResponseHook;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n call(callable, ...args) {\n const onFailedResponseHook = this.onFailedResponseHook;\n return this.queue.add(() => p_retry__WEBPACK_IMPORTED_MODULE_0__(() => callable(...args).catch((error) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (error instanceof Error) {\n throw error;\n }\n else {\n throw new Error(error);\n }\n }), {\n async onFailedAttempt(error) {\n if (error.message.startsWith("Cancel") ||\n error.message.startsWith("TimeoutError") ||\n error.message.startsWith("AbortError")) {\n throw error;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (error?.code === "ECONNABORTED") {\n throw error;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const response = error?.response;\n const status = response?.status;\n if (status) {\n if (STATUS_NO_RETRY.includes(+status)) {\n throw error;\n }\n else if (STATUS_IGNORE.includes(+status)) {\n return;\n }\n if (onFailedResponseHook) {\n await onFailedResponseHook(response);\n }\n }\n },\n // If needed we can change some of the defaults here,\n // but they\'re quite sensible.\n retries: this.maxRetries,\n randomize: true,\n }), { throwOnTimeout: true });\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callWithOptions(options, callable, ...args) {\n // Note this doesn\'t cancel the underlying request,\n // when available prefer to use the signal option of the underlying call\n if (options.signal) {\n return Promise.race([\n this.call(callable, ...args),\n new Promise((_, reject) => {\n options.signal?.addEventListener("abort", () => {\n reject(new Error("AbortError"));\n });\n }),\n ]);\n }\n return this.call(callable, ...args);\n }\n fetch(...args) {\n return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res))));\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/utils/async_caller.js?');
|
|
772
|
+
/***/
|
|
773
|
+
},
|
|
774
|
+
/***/ "./node_modules/langsmith/dist/utils/env.js":
|
|
775
|
+
/*!**************************************************!*\
|
|
776
|
+
!*** ./node_modules/langsmith/dist/utils/env.js ***!
|
|
777
|
+
\**************************************************/
|
|
778
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
779
|
+
"use strict";
|
|
780
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getEnv: () => (/* binding */ getEnv),\n/* harmony export */ getEnvironmentVariable: () => (/* binding */ getEnvironmentVariable),\n/* harmony export */ getEnvironmentVariables: () => (/* binding */ getEnvironmentVariables),\n/* harmony export */ getLangChainEnvVars: () => (/* binding */ getLangChainEnvVars),\n/* harmony export */ getLangChainEnvVarsMetadata: () => (/* binding */ getLangChainEnvVarsMetadata),\n/* harmony export */ getRuntimeEnvironment: () => (/* binding */ getRuntimeEnvironment),\n/* harmony export */ getShas: () => (/* binding */ getShas),\n/* harmony export */ isBrowser: () => (/* binding */ isBrowser),\n/* harmony export */ isDeno: () => (/* binding */ isDeno),\n/* harmony export */ isJsDom: () => (/* binding */ isJsDom),\n/* harmony export */ isNode: () => (/* binding */ isNode),\n/* harmony export */ isWebWorker: () => (/* binding */ isWebWorker),\n/* harmony export */ setEnvironmentVariable: () => (/* binding */ setEnvironmentVariable)\n/* harmony export */ });\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ "./node_modules/langsmith/dist/index.js");\n// Inlined from https://github.com/flexdinesh/browser-or-node\n\nlet globalEnv;\nconst isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";\nconst isWebWorker = () => typeof globalThis === "object" &&\n globalThis.constructor &&\n globalThis.constructor.name === "DedicatedWorkerGlobalScope";\nconst isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") ||\n (typeof navigator !== "undefined" &&\n (navigator.userAgent.includes("Node.js") ||\n navigator.userAgent.includes("jsdom")));\n// Supabase Edge Function provides a `Deno` global object\n// without `version` property\nconst isDeno = () => typeof Deno !== "undefined";\n// Mark not-as-node if in Supabase Edge Function\nconst isNode = () => typeof process !== "undefined" &&\n typeof process.versions !== "undefined" &&\n typeof process.versions.node !== "undefined" &&\n !isDeno();\nconst getEnv = () => {\n if (globalEnv) {\n return globalEnv;\n }\n if (isBrowser()) {\n globalEnv = "browser";\n }\n else if (isNode()) {\n globalEnv = "node";\n }\n else if (isWebWorker()) {\n globalEnv = "webworker";\n }\n else if (isJsDom()) {\n globalEnv = "jsdom";\n }\n else if (isDeno()) {\n globalEnv = "deno";\n }\n else {\n globalEnv = "other";\n }\n return globalEnv;\n};\nlet runtimeEnvironment;\nasync function getRuntimeEnvironment() {\n if (runtimeEnvironment === undefined) {\n const env = getEnv();\n const releaseEnv = getShas();\n runtimeEnvironment = {\n library: "langsmith",\n runtime: env,\n sdk: "langsmith-js",\n sdk_version: _index_js__WEBPACK_IMPORTED_MODULE_0__.__version__,\n ...releaseEnv,\n };\n }\n return runtimeEnvironment;\n}\n/**\n * Retrieves the LangChain-specific environment variables from the current runtime environment.\n * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security.\n *\n * @returns {Record<string, string>}\n * - A record of LangChain-specific environment variables.\n */\nfunction getLangChainEnvVars() {\n const allEnvVars = getEnvironmentVariables() || {};\n const envVars = {};\n for (const [key, value] of Object.entries(allEnvVars)) {\n if (key.startsWith("LANGCHAIN_") && typeof value === "string") {\n envVars[key] = value;\n }\n }\n for (const key in envVars) {\n if ((key.toLowerCase().includes("key") ||\n key.toLowerCase().includes("secret") ||\n key.toLowerCase().includes("token")) &&\n typeof envVars[key] === "string") {\n const value = envVars[key];\n envVars[key] =\n value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2);\n }\n }\n return envVars;\n}\n/**\n * Retrieves the LangChain-specific metadata from the current runtime environment.\n *\n * @returns {Record<string, string>}\n * - A record of LangChain-specific metadata environment variables.\n */\nfunction getLangChainEnvVarsMetadata() {\n const allEnvVars = getEnvironmentVariables() || {};\n const envVars = {};\n const excluded = [\n "LANGCHAIN_API_KEY",\n "LANGCHAIN_ENDPOINT",\n "LANGCHAIN_TRACING_V2",\n "LANGCHAIN_PROJECT",\n "LANGCHAIN_SESSION",\n ];\n for (const [key, value] of Object.entries(allEnvVars)) {\n if (key.startsWith("LANGCHAIN_") &&\n typeof value === "string" &&\n !excluded.includes(key) &&\n !key.toLowerCase().includes("key") &&\n !key.toLowerCase().includes("secret") &&\n !key.toLowerCase().includes("token")) {\n if (key === "LANGCHAIN_REVISION_ID") {\n envVars["revision_id"] = value;\n }\n else {\n envVars[key] = value;\n }\n }\n }\n return envVars;\n}\n/**\n * Retrieves the environment variables from the current runtime environment.\n *\n * This function is designed to operate in a variety of JS environments,\n * including Node.js, Deno, browsers, etc.\n *\n * @returns {Record<string, string> | undefined}\n * - A record of environment variables if available.\n * - `undefined` if the environment does not support or allows access to environment variables.\n */\nfunction getEnvironmentVariables() {\n try {\n // Check for Node.js environment\n // eslint-disable-next-line no-process-env\n if (typeof process !== "undefined" && process.env) {\n // eslint-disable-next-line no-process-env\n return Object.entries(process.env).reduce((acc, [key, value]) => {\n acc[key] = String(value);\n return acc;\n }, {});\n }\n // For browsers and other environments, we may not have direct access to env variables\n // Return undefined or any other fallback as required.\n return undefined;\n }\n catch (e) {\n // Catch any errors that might occur while trying to access environment variables\n return undefined;\n }\n}\nfunction getEnvironmentVariable(name) {\n // Certain Deno setups will throw an error if you try to access environment variables\n // https://github.com/hwchase17/langchainjs/issues/1412\n try {\n return typeof process !== "undefined"\n ? // eslint-disable-next-line no-process-env\n process.env?.[name]\n : undefined;\n }\n catch (e) {\n return undefined;\n }\n}\nfunction setEnvironmentVariable(name, value) {\n if (typeof process !== "undefined") {\n // eslint-disable-next-line no-process-env\n process.env[name] = value;\n }\n}\nlet cachedCommitSHAs;\n/**\n * Get the Git commit SHA from common environment variables\n * used by different CI/CD platforms.\n * @returns {string | undefined} The Git commit SHA or undefined if not found.\n */\nfunction getShas() {\n if (cachedCommitSHAs !== undefined) {\n return cachedCommitSHAs;\n }\n const common_release_envs = [\n "VERCEL_GIT_COMMIT_SHA",\n "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",\n "COMMIT_REF",\n "RENDER_GIT_COMMIT",\n "CI_COMMIT_SHA",\n "CIRCLE_SHA1",\n "CF_PAGES_COMMIT_SHA",\n "REACT_APP_GIT_SHA",\n "SOURCE_VERSION",\n "GITHUB_SHA",\n "TRAVIS_COMMIT",\n "GIT_COMMIT",\n "BUILD_VCS_NUMBER",\n "bamboo_planRepository_revision",\n "Build.SourceVersion",\n "BITBUCKET_COMMIT",\n "DRONE_COMMIT_SHA",\n "SEMAPHORE_GIT_SHA",\n "BUILDKITE_COMMIT",\n ];\n const shas = {};\n for (const env of common_release_envs) {\n const envVar = getEnvironmentVariable(env);\n if (envVar !== undefined) {\n shas[env] = envVar;\n }\n }\n cachedCommitSHAs = shas;\n return shas;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/utils/env.js?');
|
|
781
|
+
/***/
|
|
782
|
+
},
|
|
783
|
+
/***/ "./node_modules/langsmith/dist/utils/messages.js":
|
|
784
|
+
/*!*******************************************************!*\
|
|
785
|
+
!*** ./node_modules/langsmith/dist/utils/messages.js ***!
|
|
786
|
+
\*******************************************************/
|
|
787
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
788
|
+
"use strict";
|
|
789
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ convertLangChainMessageToExample: () => (/* binding */ convertLangChainMessageToExample),\n/* harmony export */ isLangChainMessage: () => (/* binding */ isLangChainMessage)\n/* harmony export */ });\nfunction isLangChainMessage(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nmessage) {\n return typeof message?._getType === "function";\n}\nfunction convertLangChainMessageToExample(message) {\n const converted = {\n type: message._getType(),\n data: { content: message.content },\n };\n // Check for presence of keys in additional_kwargs\n if (message?.additional_kwargs &&\n Object.keys(message.additional_kwargs).length > 0) {\n converted.data.additional_kwargs = { ...message.additional_kwargs };\n }\n return converted;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/utils/messages.js?');
|
|
790
|
+
/***/
|
|
791
|
+
},
|
|
792
|
+
/***/ "./node_modules/langsmith/dist/utils/warn.js":
|
|
793
|
+
/*!***************************************************!*\
|
|
794
|
+
!*** ./node_modules/langsmith/dist/utils/warn.js ***!
|
|
795
|
+
\***************************************************/
|
|
796
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
797
|
+
"use strict";
|
|
798
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ warnOnce: () => (/* binding */ warnOnce)\n/* harmony export */ });\nconst warnedMessages = {};\nfunction warnOnce(message) {\n if (!warnedMessages[message]) {\n console.warn(message);\n warnedMessages[message] = true;\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/dist/utils/warn.js?");
|
|
799
|
+
/***/
|
|
800
|
+
},
|
|
801
|
+
/***/ "./node_modules/langsmith/index.js":
|
|
802
|
+
/*!*****************************************!*\
|
|
803
|
+
!*** ./node_modules/langsmith/index.js ***!
|
|
804
|
+
\*****************************************/
|
|
805
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
806
|
+
"use strict";
|
|
807
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Client: () => (/* reexport safe */ _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.Client),\n/* harmony export */ RunTree: () => (/* reexport safe */ _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.RunTree),\n/* harmony export */ __version__: () => (/* reexport safe */ _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.__version__)\n/* harmony export */ });\n/* harmony import */ var _dist_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dist/index.js */ "./node_modules/langsmith/dist/index.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/index.js?');
|
|
808
|
+
/***/
|
|
809
|
+
},
|
|
810
|
+
/***/ "./node_modules/langsmith/singletons/traceable.js":
|
|
811
|
+
/*!********************************************************!*\
|
|
812
|
+
!*** ./node_modules/langsmith/singletons/traceable.js ***!
|
|
813
|
+
\********************************************************/
|
|
814
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
815
|
+
"use strict";
|
|
816
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AsyncLocalStorageProviderSingleton: () => (/* reexport safe */ _dist_singletons_traceable_js__WEBPACK_IMPORTED_MODULE_0__.AsyncLocalStorageProviderSingleton),\n/* harmony export */ ROOT: () => (/* reexport safe */ _dist_singletons_traceable_js__WEBPACK_IMPORTED_MODULE_0__.ROOT),\n/* harmony export */ getCurrentRunTree: () => (/* reexport safe */ _dist_singletons_traceable_js__WEBPACK_IMPORTED_MODULE_0__.getCurrentRunTree),\n/* harmony export */ isTraceableFunction: () => (/* reexport safe */ _dist_singletons_traceable_js__WEBPACK_IMPORTED_MODULE_0__.isTraceableFunction),\n/* harmony export */ withRunTree: () => (/* reexport safe */ _dist_singletons_traceable_js__WEBPACK_IMPORTED_MODULE_0__.withRunTree)\n/* harmony export */ });\n/* harmony import */ var _dist_singletons_traceable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../dist/singletons/traceable.js */ "./node_modules/langsmith/dist/singletons/traceable.js");\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/langsmith/singletons/traceable.js?');
|
|
817
|
+
/***/
|
|
818
|
+
},
|
|
819
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/Options.js":
|
|
820
|
+
/*!*************************************************************!*\
|
|
821
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/Options.js ***!
|
|
822
|
+
\*************************************************************/
|
|
823
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
824
|
+
"use strict";
|
|
825
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ defaultOptions: () => (/* binding */ defaultOptions),\n/* harmony export */ getDefaultOptions: () => (/* binding */ getDefaultOptions),\n/* harmony export */ ignoreOverride: () => (/* binding */ ignoreOverride)\n/* harmony export */ });\nconst ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");\nconst defaultOptions = {\n name: undefined,\n $refStrategy: "root",\n basePath: ["#"],\n effectStrategy: "input",\n pipeStrategy: "all",\n dateStrategy: "format:date-time",\n mapStrategy: "entries",\n removeAdditionalStrategy: "passthrough",\n definitionPath: "definitions",\n target: "jsonSchema7",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: "escape",\n applyRegexFlags: false,\n emailStrategy: "format:email",\n base64Strategy: "contentEncoding:base64",\n nameStrategy: "ref"\n};\nconst getDefaultOptions = (options) => (typeof options === "string"\n ? {\n ...defaultOptions,\n name: options,\n }\n : {\n ...defaultOptions,\n ...options,\n });\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/Options.js?');
|
|
826
|
+
/***/
|
|
827
|
+
},
|
|
828
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/Refs.js":
|
|
829
|
+
/*!**********************************************************!*\
|
|
830
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/Refs.js ***!
|
|
831
|
+
\**********************************************************/
|
|
832
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
833
|
+
"use strict";
|
|
834
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getRefs: () => (/* binding */ getRefs)\n/* harmony export */ });\n/* harmony import */ var _Options_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Options.js */ "./node_modules/zod-to-json-schema/dist/esm/Options.js");\n\nconst getRefs = (options) => {\n const _options = (0,_Options_js__WEBPACK_IMPORTED_MODULE_0__.getDefaultOptions)(options);\n const currentPath = _options.name !== undefined\n ? [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n currentPath: currentPath,\n propertyPath: undefined,\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it\'s ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/Refs.js?');
|
|
835
|
+
/***/
|
|
836
|
+
},
|
|
837
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js":
|
|
838
|
+
/*!*******************************************************************!*\
|
|
839
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/errorMessages.js ***!
|
|
840
|
+
\*******************************************************************/
|
|
841
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
842
|
+
"use strict";
|
|
843
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ addErrorMessage: () => (/* binding */ addErrorMessage),\n/* harmony export */ setResponseValueAndErrors: () => (/* binding */ setResponseValueAndErrors)\n/* harmony export */ });\nfunction addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nfunction setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/errorMessages.js?");
|
|
844
|
+
/***/
|
|
845
|
+
},
|
|
846
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/index.js":
|
|
847
|
+
/*!***********************************************************!*\
|
|
848
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/index.js ***!
|
|
849
|
+
\***********************************************************/
|
|
850
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
851
|
+
"use strict";
|
|
852
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ addErrorMessage: () => (/* reexport safe */ _errorMessages_js__WEBPACK_IMPORTED_MODULE_2__.addErrorMessage),\n/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ defaultOptions: () => (/* reexport safe */ _Options_js__WEBPACK_IMPORTED_MODULE_0__.defaultOptions),\n/* harmony export */ getDefaultOptions: () => (/* reexport safe */ _Options_js__WEBPACK_IMPORTED_MODULE_0__.getDefaultOptions),\n/* harmony export */ getRefs: () => (/* reexport safe */ _Refs_js__WEBPACK_IMPORTED_MODULE_1__.getRefs),\n/* harmony export */ ignoreOverride: () => (/* reexport safe */ _Options_js__WEBPACK_IMPORTED_MODULE_0__.ignoreOverride),\n/* harmony export */ parseAnyDef: () => (/* reexport safe */ _parsers_any_js__WEBPACK_IMPORTED_MODULE_4__.parseAnyDef),\n/* harmony export */ parseArrayDef: () => (/* reexport safe */ _parsers_array_js__WEBPACK_IMPORTED_MODULE_5__.parseArrayDef),\n/* harmony export */ parseBigintDef: () => (/* reexport safe */ _parsers_bigint_js__WEBPACK_IMPORTED_MODULE_6__.parseBigintDef),\n/* harmony export */ parseBooleanDef: () => (/* reexport safe */ _parsers_boolean_js__WEBPACK_IMPORTED_MODULE_7__.parseBooleanDef),\n/* harmony export */ parseBrandedDef: () => (/* reexport safe */ _parsers_branded_js__WEBPACK_IMPORTED_MODULE_8__.parseBrandedDef),\n/* harmony export */ parseCatchDef: () => (/* reexport safe */ _parsers_catch_js__WEBPACK_IMPORTED_MODULE_9__.parseCatchDef),\n/* harmony export */ parseDateDef: () => (/* reexport safe */ _parsers_date_js__WEBPACK_IMPORTED_MODULE_10__.parseDateDef),\n/* harmony export */ parseDef: () => (/* reexport safe */ _parseDef_js__WEBPACK_IMPORTED_MODULE_3__.parseDef),\n/* harmony export */ parseDefaultDef: () => (/* reexport safe */ _parsers_default_js__WEBPACK_IMPORTED_MODULE_11__.parseDefaultDef),\n/* harmony export */ parseEffectsDef: () => (/* reexport safe */ _parsers_effects_js__WEBPACK_IMPORTED_MODULE_12__.parseEffectsDef),\n/* harmony export */ parseEnumDef: () => (/* reexport safe */ _parsers_enum_js__WEBPACK_IMPORTED_MODULE_13__.parseEnumDef),\n/* harmony export */ parseIntersectionDef: () => (/* reexport safe */ _parsers_intersection_js__WEBPACK_IMPORTED_MODULE_14__.parseIntersectionDef),\n/* harmony export */ parseLiteralDef: () => (/* reexport safe */ _parsers_literal_js__WEBPACK_IMPORTED_MODULE_15__.parseLiteralDef),\n/* harmony export */ parseMapDef: () => (/* reexport safe */ _parsers_map_js__WEBPACK_IMPORTED_MODULE_16__.parseMapDef),\n/* harmony export */ parseNativeEnumDef: () => (/* reexport safe */ _parsers_nativeEnum_js__WEBPACK_IMPORTED_MODULE_17__.parseNativeEnumDef),\n/* harmony export */ parseNeverDef: () => (/* reexport safe */ _parsers_never_js__WEBPACK_IMPORTED_MODULE_18__.parseNeverDef),\n/* harmony export */ parseNullDef: () => (/* reexport safe */ _parsers_null_js__WEBPACK_IMPORTED_MODULE_19__.parseNullDef),\n/* harmony export */ parseNullableDef: () => (/* reexport safe */ _parsers_nullable_js__WEBPACK_IMPORTED_MODULE_20__.parseNullableDef),\n/* harmony export */ parseNumberDef: () => (/* reexport safe */ _parsers_number_js__WEBPACK_IMPORTED_MODULE_21__.parseNumberDef),\n/* harmony export */ parseObjectDef: () => (/* reexport safe */ _parsers_object_js__WEBPACK_IMPORTED_MODULE_22__.parseObjectDef),\n/* harmony export */ parseObjectDefX: () => (/* reexport safe */ _parsers_object_js__WEBPACK_IMPORTED_MODULE_22__.parseObjectDefX),\n/* harmony export */ parseOptionalDef: () => (/* reexport safe */ _parsers_optional_js__WEBPACK_IMPORTED_MODULE_23__.parseOptionalDef),\n/* harmony export */ parsePipelineDef: () => (/* reexport safe */ _parsers_pipeline_js__WEBPACK_IMPORTED_MODULE_24__.parsePipelineDef),\n/* harmony export */ parsePromiseDef: () => (/* reexport safe */ _parsers_promise_js__WEBPACK_IMPORTED_MODULE_25__.parsePromiseDef),\n/* harmony export */ parseReadonlyDef: () => (/* reexport safe */ _parsers_readonly_js__WEBPACK_IMPORTED_MODULE_26__.parseReadonlyDef),\n/* harmony export */ parseRecordDef: () => (/* reexport safe */ _parsers_record_js__WEBPACK_IMPORTED_MODULE_27__.parseRecordDef),\n/* harmony export */ parseSetDef: () => (/* reexport safe */ _parsers_set_js__WEBPACK_IMPORTED_MODULE_28__.parseSetDef),\n/* harmony export */ parseStringDef: () => (/* reexport safe */ _parsers_string_js__WEBPACK_IMPORTED_MODULE_29__.parseStringDef),\n/* harmony export */ parseTupleDef: () => (/* reexport safe */ _parsers_tuple_js__WEBPACK_IMPORTED_MODULE_30__.parseTupleDef),\n/* harmony export */ parseUndefinedDef: () => (/* reexport safe */ _parsers_undefined_js__WEBPACK_IMPORTED_MODULE_31__.parseUndefinedDef),\n/* harmony export */ parseUnionDef: () => (/* reexport safe */ _parsers_union_js__WEBPACK_IMPORTED_MODULE_32__.parseUnionDef),\n/* harmony export */ parseUnknownDef: () => (/* reexport safe */ _parsers_unknown_js__WEBPACK_IMPORTED_MODULE_33__.parseUnknownDef),\n/* harmony export */ primitiveMappings: () => (/* reexport safe */ _parsers_union_js__WEBPACK_IMPORTED_MODULE_32__.primitiveMappings),\n/* harmony export */ setResponseValueAndErrors: () => (/* reexport safe */ _errorMessages_js__WEBPACK_IMPORTED_MODULE_2__.setResponseValueAndErrors),\n/* harmony export */ zodPatterns: () => (/* reexport safe */ _parsers_string_js__WEBPACK_IMPORTED_MODULE_29__.zodPatterns),\n/* harmony export */ zodToJsonSchema: () => (/* reexport safe */ _zodToJsonSchema_js__WEBPACK_IMPORTED_MODULE_34__.zodToJsonSchema)\n/* harmony export */ });\n/* harmony import */ var _Options_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Options.js */ "./node_modules/zod-to-json-schema/dist/esm/Options.js");\n/* harmony import */ var _Refs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Refs.js */ "./node_modules/zod-to-json-schema/dist/esm/Refs.js");\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n/* harmony import */ var _parsers_any_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./parsers/any.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/any.js");\n/* harmony import */ var _parsers_array_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./parsers/array.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/array.js");\n/* harmony import */ var _parsers_bigint_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./parsers/bigint.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js");\n/* harmony import */ var _parsers_boolean_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./parsers/boolean.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js");\n/* harmony import */ var _parsers_branded_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./parsers/branded.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js");\n/* harmony import */ var _parsers_catch_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./parsers/catch.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js");\n/* harmony import */ var _parsers_date_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./parsers/date.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/date.js");\n/* harmony import */ var _parsers_default_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./parsers/default.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/default.js");\n/* harmony import */ var _parsers_effects_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./parsers/effects.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js");\n/* harmony import */ var _parsers_enum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./parsers/enum.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js");\n/* harmony import */ var _parsers_intersection_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./parsers/intersection.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js");\n/* harmony import */ var _parsers_literal_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./parsers/literal.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js");\n/* harmony import */ var _parsers_map_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./parsers/map.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/map.js");\n/* harmony import */ var _parsers_nativeEnum_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./parsers/nativeEnum.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js");\n/* harmony import */ var _parsers_never_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./parsers/never.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/never.js");\n/* harmony import */ var _parsers_null_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./parsers/null.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/null.js");\n/* harmony import */ var _parsers_nullable_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./parsers/nullable.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js");\n/* harmony import */ var _parsers_number_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./parsers/number.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/number.js");\n/* harmony import */ var _parsers_object_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./parsers/object.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/object.js");\n/* harmony import */ var _parsers_optional_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./parsers/optional.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js");\n/* harmony import */ var _parsers_pipeline_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./parsers/pipeline.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js");\n/* harmony import */ var _parsers_promise_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./parsers/promise.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js");\n/* harmony import */ var _parsers_readonly_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./parsers/readonly.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js");\n/* harmony import */ var _parsers_record_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./parsers/record.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/record.js");\n/* harmony import */ var _parsers_set_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./parsers/set.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/set.js");\n/* harmony import */ var _parsers_string_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./parsers/string.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/string.js");\n/* harmony import */ var _parsers_tuple_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./parsers/tuple.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js");\n/* harmony import */ var _parsers_undefined_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./parsers/undefined.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js");\n/* harmony import */ var _parsers_union_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./parsers/union.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/union.js");\n/* harmony import */ var _parsers_unknown_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./parsers/unknown.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js");\n/* harmony import */ var _zodToJsonSchema_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./zodToJsonSchema.js */ "./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_zodToJsonSchema_js__WEBPACK_IMPORTED_MODULE_34__.zodToJsonSchema);\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/index.js?');
|
|
853
|
+
/***/
|
|
854
|
+
},
|
|
855
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js":
|
|
856
|
+
/*!**************************************************************!*\
|
|
857
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parseDef.js ***!
|
|
858
|
+
\**************************************************************/
|
|
859
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
860
|
+
"use strict";
|
|
861
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseDef: () => (/* binding */ parseDef)\n/* harmony export */ });\n/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! zod */ "./node_modules/zod/lib/index.mjs");\n/* harmony import */ var _parsers_any_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./parsers/any.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/any.js");\n/* harmony import */ var _parsers_array_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./parsers/array.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/array.js");\n/* harmony import */ var _parsers_bigint_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./parsers/bigint.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js");\n/* harmony import */ var _parsers_boolean_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./parsers/boolean.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js");\n/* harmony import */ var _parsers_branded_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./parsers/branded.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js");\n/* harmony import */ var _parsers_catch_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./parsers/catch.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js");\n/* harmony import */ var _parsers_date_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./parsers/date.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/date.js");\n/* harmony import */ var _parsers_default_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./parsers/default.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/default.js");\n/* harmony import */ var _parsers_effects_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./parsers/effects.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js");\n/* harmony import */ var _parsers_enum_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./parsers/enum.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js");\n/* harmony import */ var _parsers_intersection_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./parsers/intersection.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js");\n/* harmony import */ var _parsers_literal_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./parsers/literal.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js");\n/* harmony import */ var _parsers_map_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./parsers/map.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/map.js");\n/* harmony import */ var _parsers_nativeEnum_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./parsers/nativeEnum.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js");\n/* harmony import */ var _parsers_never_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./parsers/never.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/never.js");\n/* harmony import */ var _parsers_null_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./parsers/null.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/null.js");\n/* harmony import */ var _parsers_nullable_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./parsers/nullable.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js");\n/* harmony import */ var _parsers_number_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./parsers/number.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/number.js");\n/* harmony import */ var _parsers_object_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./parsers/object.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/object.js");\n/* harmony import */ var _parsers_optional_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./parsers/optional.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js");\n/* harmony import */ var _parsers_pipeline_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./parsers/pipeline.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js");\n/* harmony import */ var _parsers_promise_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./parsers/promise.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js");\n/* harmony import */ var _parsers_record_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./parsers/record.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/record.js");\n/* harmony import */ var _parsers_set_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./parsers/set.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/set.js");\n/* harmony import */ var _parsers_string_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./parsers/string.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/string.js");\n/* harmony import */ var _parsers_tuple_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./parsers/tuple.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js");\n/* harmony import */ var _parsers_undefined_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./parsers/undefined.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js");\n/* harmony import */ var _parsers_union_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./parsers/union.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/union.js");\n/* harmony import */ var _parsers_unknown_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./parsers/unknown.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js");\n/* harmony import */ var _parsers_readonly_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./parsers/readonly.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js");\n/* harmony import */ var _Options_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Options.js */ "./node_modules/zod-to-json-schema/dist/esm/Options.js");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunction parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== _Options_js__WEBPACK_IMPORTED_MODULE_30__.ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchema = selectParser(def, def.typeName, refs);\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case "root":\n return { $ref: item.path.join("/") };\n case "relative":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case "none":\n case "seen": {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);\n return {};\n }\n return refs.$refStrategy === "seen" ? {} : undefined;\n }\n }\n};\nconst getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");\n};\nconst selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodString:\n return (0,_parsers_string_js__WEBPACK_IMPORTED_MODULE_24__.parseStringDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodNumber:\n return (0,_parsers_number_js__WEBPACK_IMPORTED_MODULE_17__.parseNumberDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodObject:\n return (0,_parsers_object_js__WEBPACK_IMPORTED_MODULE_18__.parseObjectDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodBigInt:\n return (0,_parsers_bigint_js__WEBPACK_IMPORTED_MODULE_2__.parseBigintDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodBoolean:\n return (0,_parsers_boolean_js__WEBPACK_IMPORTED_MODULE_3__.parseBooleanDef)();\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodDate:\n return (0,_parsers_date_js__WEBPACK_IMPORTED_MODULE_6__.parseDateDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodUndefined:\n return (0,_parsers_undefined_js__WEBPACK_IMPORTED_MODULE_26__.parseUndefinedDef)();\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodNull:\n return (0,_parsers_null_js__WEBPACK_IMPORTED_MODULE_15__.parseNullDef)(refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodArray:\n return (0,_parsers_array_js__WEBPACK_IMPORTED_MODULE_1__.parseArrayDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodUnion:\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return (0,_parsers_union_js__WEBPACK_IMPORTED_MODULE_27__.parseUnionDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodIntersection:\n return (0,_parsers_intersection_js__WEBPACK_IMPORTED_MODULE_10__.parseIntersectionDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodTuple:\n return (0,_parsers_tuple_js__WEBPACK_IMPORTED_MODULE_25__.parseTupleDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodRecord:\n return (0,_parsers_record_js__WEBPACK_IMPORTED_MODULE_22__.parseRecordDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodLiteral:\n return (0,_parsers_literal_js__WEBPACK_IMPORTED_MODULE_11__.parseLiteralDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodEnum:\n return (0,_parsers_enum_js__WEBPACK_IMPORTED_MODULE_9__.parseEnumDef)(def);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodNativeEnum:\n return (0,_parsers_nativeEnum_js__WEBPACK_IMPORTED_MODULE_13__.parseNativeEnumDef)(def);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodNullable:\n return (0,_parsers_nullable_js__WEBPACK_IMPORTED_MODULE_16__.parseNullableDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodOptional:\n return (0,_parsers_optional_js__WEBPACK_IMPORTED_MODULE_19__.parseOptionalDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodMap:\n return (0,_parsers_map_js__WEBPACK_IMPORTED_MODULE_12__.parseMapDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodSet:\n return (0,_parsers_set_js__WEBPACK_IMPORTED_MODULE_23__.parseSetDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodLazy:\n return parseDef(def.getter()._def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodPromise:\n return (0,_parsers_promise_js__WEBPACK_IMPORTED_MODULE_21__.parsePromiseDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodNaN:\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodNever:\n return (0,_parsers_never_js__WEBPACK_IMPORTED_MODULE_14__.parseNeverDef)();\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodEffects:\n return (0,_parsers_effects_js__WEBPACK_IMPORTED_MODULE_8__.parseEffectsDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodAny:\n return (0,_parsers_any_js__WEBPACK_IMPORTED_MODULE_0__.parseAnyDef)();\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodUnknown:\n return (0,_parsers_unknown_js__WEBPACK_IMPORTED_MODULE_28__.parseUnknownDef)();\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodDefault:\n return (0,_parsers_default_js__WEBPACK_IMPORTED_MODULE_7__.parseDefaultDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodBranded:\n return (0,_parsers_branded_js__WEBPACK_IMPORTED_MODULE_4__.parseBrandedDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodReadonly:\n return (0,_parsers_readonly_js__WEBPACK_IMPORTED_MODULE_29__.parseReadonlyDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodCatch:\n return (0,_parsers_catch_js__WEBPACK_IMPORTED_MODULE_5__.parseCatchDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodPipeline:\n return (0,_parsers_pipeline_js__WEBPACK_IMPORTED_MODULE_20__.parsePipelineDef)(def, refs);\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodFunction:\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodVoid:\n case zod__WEBPACK_IMPORTED_MODULE_31__.ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parseDef.js?');
|
|
862
|
+
/***/
|
|
863
|
+
},
|
|
864
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/any.js":
|
|
865
|
+
/*!*****************************************************************!*\
|
|
866
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/any.js ***!
|
|
867
|
+
\*****************************************************************/
|
|
868
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
869
|
+
"use strict";
|
|
870
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseAnyDef: () => (/* binding */ parseAnyDef)\n/* harmony export */ });\nfunction parseAnyDef() {\n return {};\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/any.js?");
|
|
871
|
+
/***/
|
|
872
|
+
},
|
|
873
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/array.js":
|
|
874
|
+
/*!*******************************************************************!*\
|
|
875
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/array.js ***!
|
|
876
|
+
\*******************************************************************/
|
|
877
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
878
|
+
"use strict";
|
|
879
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseArrayDef: () => (/* binding */ parseArrayDef)\n/* harmony export */ });\n/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! zod */ "./node_modules/zod/lib/index.mjs");\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\n\n\nfunction parseArrayDef(def, refs) {\n const res = {\n type: "array",\n };\n if (def.type?._def?.typeName !== zod__WEBPACK_IMPORTED_MODULE_2__.ZodFirstPartyTypeKind.ZodAny) {\n res.items = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_1__.parseDef)(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, "items"],\n });\n }\n if (def.minLength) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs);\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/array.js?');
|
|
880
|
+
/***/
|
|
881
|
+
},
|
|
882
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js":
|
|
883
|
+
/*!********************************************************************!*\
|
|
884
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js ***!
|
|
885
|
+
\********************************************************************/
|
|
886
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
887
|
+
"use strict";
|
|
888
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseBigintDef: () => (/* binding */ parseBigintDef)\n/* harmony export */ });\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n\nfunction parseBigintDef(def, refs) {\n const res = {\n type: "integer",\n format: "int64",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case "min":\n if (refs.target === "jsonSchema7") {\n if (check.inclusive) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);\n }\n else {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);\n }\n break;\n case "max":\n if (refs.target === "jsonSchema7") {\n if (check.inclusive) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);\n }\n else {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);\n }\n break;\n case "multipleOf":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js?');
|
|
889
|
+
/***/
|
|
890
|
+
},
|
|
891
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js":
|
|
892
|
+
/*!*********************************************************************!*\
|
|
893
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js ***!
|
|
894
|
+
\*********************************************************************/
|
|
895
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
896
|
+
"use strict";
|
|
897
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseBooleanDef: () => (/* binding */ parseBooleanDef)\n/* harmony export */ });\nfunction parseBooleanDef() {\n return {\n type: "boolean",\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js?');
|
|
898
|
+
/***/
|
|
899
|
+
},
|
|
900
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js":
|
|
901
|
+
/*!*********************************************************************!*\
|
|
902
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js ***!
|
|
903
|
+
\*********************************************************************/
|
|
904
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
905
|
+
"use strict";
|
|
906
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseBrandedDef: () => (/* binding */ parseBrandedDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nfunction parseBrandedDef(_def, refs) {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(_def.type._def, refs);\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js?');
|
|
907
|
+
/***/
|
|
908
|
+
},
|
|
909
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js":
|
|
910
|
+
/*!*******************************************************************!*\
|
|
911
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js ***!
|
|
912
|
+
\*******************************************************************/
|
|
913
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
914
|
+
"use strict";
|
|
915
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseCatchDef: () => (/* binding */ parseCatchDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nconst parseCatchDef = (def, refs) => {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.innerType._def, refs);\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js?');
|
|
916
|
+
/***/
|
|
917
|
+
},
|
|
918
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/date.js":
|
|
919
|
+
/*!******************************************************************!*\
|
|
920
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/date.js ***!
|
|
921
|
+
\******************************************************************/
|
|
922
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
923
|
+
"use strict";
|
|
924
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseDateDef: () => (/* binding */ parseDateDef)\n/* harmony export */ });\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case "string":\n case "format:date-time":\n return {\n type: "string",\n format: "date-time",\n };\n case "format:date":\n return {\n type: "string",\n format: "date",\n };\n case "integer":\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: "integer",\n format: "unix-time",\n };\n if (refs.target === "openApi3") {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case "min":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minimum", check.value, // This is in milliseconds\n check.message, refs);\n break;\n case "max":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maximum", check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/date.js?');
|
|
925
|
+
/***/
|
|
926
|
+
},
|
|
927
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/default.js":
|
|
928
|
+
/*!*********************************************************************!*\
|
|
929
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/default.js ***!
|
|
930
|
+
\*********************************************************************/
|
|
931
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
932
|
+
"use strict";
|
|
933
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseDefaultDef: () => (/* binding */ parseDefaultDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nfunction parseDefaultDef(_def, refs) {\n return {\n ...(0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/default.js?');
|
|
934
|
+
/***/
|
|
935
|
+
},
|
|
936
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js":
|
|
937
|
+
/*!*********************************************************************!*\
|
|
938
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js ***!
|
|
939
|
+
\*********************************************************************/
|
|
940
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
941
|
+
"use strict";
|
|
942
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseEffectsDef: () => (/* binding */ parseEffectsDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nfunction parseEffectsDef(_def, refs) {\n return refs.effectStrategy === "input"\n ? (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(_def.schema._def, refs)\n : {};\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js?');
|
|
943
|
+
/***/
|
|
944
|
+
},
|
|
945
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js":
|
|
946
|
+
/*!******************************************************************!*\
|
|
947
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js ***!
|
|
948
|
+
\******************************************************************/
|
|
949
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
950
|
+
"use strict";
|
|
951
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseEnumDef: () => (/* binding */ parseEnumDef)\n/* harmony export */ });\nfunction parseEnumDef(def) {\n return {\n type: "string",\n enum: def.values,\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js?');
|
|
952
|
+
/***/
|
|
953
|
+
},
|
|
954
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js":
|
|
955
|
+
/*!**************************************************************************!*\
|
|
956
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js ***!
|
|
957
|
+
\**************************************************************************/
|
|
958
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
959
|
+
"use strict";
|
|
960
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseIntersectionDef: () => (/* binding */ parseIntersectionDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nconst isJsonSchema7AllOfType = (type) => {\n if ("type" in type && type.type === "string")\n return false;\n return "allOf" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n const allOf = [\n (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, "allOf", "0"],\n }),\n (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, "allOf", "1"],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === "jsonSchema2019-09"\n ? { unevaluatedProperties: false }\n : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if ("additionalProperties" in schema &&\n schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length\n ? {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js?');
|
|
961
|
+
/***/
|
|
962
|
+
},
|
|
963
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js":
|
|
964
|
+
/*!*********************************************************************!*\
|
|
965
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js ***!
|
|
966
|
+
\*********************************************************************/
|
|
967
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
968
|
+
"use strict";
|
|
969
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseLiteralDef: () => (/* binding */ parseLiteralDef)\n/* harmony export */ });\nfunction parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== "bigint" &&\n parsedType !== "number" &&\n parsedType !== "boolean" &&\n parsedType !== "string") {\n return {\n type: Array.isArray(def.value) ? "array" : "object",\n };\n }\n if (refs.target === "openApi3") {\n return {\n type: parsedType === "bigint" ? "integer" : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === "bigint" ? "integer" : parsedType,\n const: def.value,\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js?');
|
|
970
|
+
/***/
|
|
971
|
+
},
|
|
972
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/map.js":
|
|
973
|
+
/*!*****************************************************************!*\
|
|
974
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/map.js ***!
|
|
975
|
+
\*****************************************************************/
|
|
976
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
977
|
+
"use strict";
|
|
978
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseMapDef: () => (/* binding */ parseMapDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n/* harmony import */ var _record_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./record.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/record.js");\n\n\nfunction parseMapDef(def, refs) {\n if (refs.mapStrategy === "record") {\n return (0,_record_js__WEBPACK_IMPORTED_MODULE_1__.parseRecordDef)(def, refs);\n }\n const keys = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "items", "items", "0"],\n }) || {};\n const values = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "items", "items", "1"],\n }) || {};\n return {\n type: "array",\n maxItems: 125,\n items: {\n type: "array",\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/map.js?');
|
|
979
|
+
/***/
|
|
980
|
+
},
|
|
981
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js":
|
|
982
|
+
/*!************************************************************************!*\
|
|
983
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js ***!
|
|
984
|
+
\************************************************************************/
|
|
985
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
986
|
+
"use strict";
|
|
987
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseNativeEnumDef: () => (/* binding */ parseNativeEnumDef)\n/* harmony export */ });\nfunction parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== "number";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1\n ? parsedTypes[0] === "string"\n ? "string"\n : "number"\n : ["string", "number"],\n enum: actualValues,\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js?');
|
|
988
|
+
/***/
|
|
989
|
+
},
|
|
990
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/never.js":
|
|
991
|
+
/*!*******************************************************************!*\
|
|
992
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/never.js ***!
|
|
993
|
+
\*******************************************************************/
|
|
994
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
995
|
+
"use strict";
|
|
996
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseNeverDef: () => (/* binding */ parseNeverDef)\n/* harmony export */ });\nfunction parseNeverDef() {\n return {\n not: {},\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/never.js?");
|
|
997
|
+
/***/
|
|
998
|
+
},
|
|
999
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/null.js":
|
|
1000
|
+
/*!******************************************************************!*\
|
|
1001
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/null.js ***!
|
|
1002
|
+
\******************************************************************/
|
|
1003
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1004
|
+
"use strict";
|
|
1005
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseNullDef: () => (/* binding */ parseNullDef)\n/* harmony export */ });\nfunction parseNullDef(refs) {\n return refs.target === "openApi3"\n ? {\n enum: ["null"],\n nullable: true,\n }\n : {\n type: "null",\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/null.js?');
|
|
1006
|
+
/***/
|
|
1007
|
+
},
|
|
1008
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js":
|
|
1009
|
+
/*!**********************************************************************!*\
|
|
1010
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js ***!
|
|
1011
|
+
\**********************************************************************/
|
|
1012
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1013
|
+
"use strict";
|
|
1014
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseNullableDef: () => (/* binding */ parseNullableDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n/* harmony import */ var _union_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./union.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/union.js");\n\n\nfunction parseNullableDef(def, refs) {\n if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === "openApi3") {\n return {\n type: _union_js__WEBPACK_IMPORTED_MODULE_1__.primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [\n _union_js__WEBPACK_IMPORTED_MODULE_1__.primitiveMappings[def.innerType._def.typeName],\n "null",\n ],\n };\n }\n if (refs.target === "openApi3") {\n const base = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && \'$ref\' in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "anyOf", "0"],\n });\n return base && { anyOf: [base, { type: "null" }] };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js?');
|
|
1015
|
+
/***/
|
|
1016
|
+
},
|
|
1017
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/number.js":
|
|
1018
|
+
/*!********************************************************************!*\
|
|
1019
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/number.js ***!
|
|
1020
|
+
\********************************************************************/
|
|
1021
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1022
|
+
"use strict";
|
|
1023
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseNumberDef: () => (/* binding */ parseNumberDef)\n/* harmony export */ });\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n\nfunction parseNumberDef(def, refs) {\n const res = {\n type: "number",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case "int":\n res.type = "integer";\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.addErrorMessage)(res, "type", check.message, refs);\n break;\n case "min":\n if (refs.target === "jsonSchema7") {\n if (check.inclusive) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);\n }\n else {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs);\n }\n break;\n case "max":\n if (refs.target === "jsonSchema7") {\n if (check.inclusive) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);\n }\n else {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs);\n }\n break;\n case "multipleOf":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/number.js?');
|
|
1024
|
+
/***/
|
|
1025
|
+
},
|
|
1026
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/object.js":
|
|
1027
|
+
/*!********************************************************************!*\
|
|
1028
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/object.js ***!
|
|
1029
|
+
\********************************************************************/
|
|
1030
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1031
|
+
"use strict";
|
|
1032
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseObjectDef: () => (/* binding */ parseObjectDef),\n/* harmony export */ parseObjectDefX: () => (/* binding */ parseObjectDefX)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nfunction decideAdditionalProperties(def, refs) {\n if (refs.removeAdditionalStrategy === "strict") {\n return def.catchall._def.typeName === "ZodNever"\n ? def.unknownKeys !== "strict"\n : (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, "additionalProperties"],\n }) ?? true;\n }\n else {\n return def.catchall._def.typeName === "ZodNever"\n ? def.unknownKeys === "passthrough"\n : (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, "additionalProperties"],\n }) ?? true;\n }\n}\n;\nfunction parseObjectDefX(def, refs) {\n Object.keys(def.shape()).reduce((schema, key) => {\n let prop = def.shape()[key];\n const isOptional = prop.isOptional();\n if (!isOptional) {\n prop = { ...prop._def.innerSchema };\n }\n const propSchema = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(prop._def, {\n ...refs,\n currentPath: [...refs.currentPath, "properties", key],\n propertyPath: [...refs.currentPath, "properties", key],\n });\n if (propSchema !== undefined) {\n schema.properties[key] = propSchema;\n if (!isOptional) {\n if (!schema.required) {\n schema.required = [];\n }\n schema.required.push(key);\n }\n }\n return schema;\n }, {\n type: "object",\n properties: {},\n additionalProperties: decideAdditionalProperties(def, refs),\n });\n const result = {\n type: "object",\n ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {\n if (propDef === undefined || propDef._def === undefined)\n return acc;\n const parsedDef = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, "properties", propName],\n propertyPath: [...refs.currentPath, "properties", propName],\n });\n if (parsedDef === undefined)\n return acc;\n return {\n properties: { ...acc.properties, [propName]: parsedDef },\n required: propDef.isOptional()\n ? acc.required\n : [...acc.required, propName],\n };\n }, { properties: {}, required: [] }),\n additionalProperties: decideAdditionalProperties(def, refs),\n };\n if (!result.required.length)\n delete result.required;\n return result;\n}\nfunction parseObjectDef(def, refs) {\n const result = {\n type: "object",\n ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {\n if (propDef === undefined || propDef._def === undefined)\n return acc;\n const parsedDef = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, "properties", propName],\n propertyPath: [...refs.currentPath, "properties", propName],\n });\n if (parsedDef === undefined)\n return acc;\n return {\n properties: { ...acc.properties, [propName]: parsedDef },\n required: propDef.isOptional()\n ? acc.required\n : [...acc.required, propName],\n };\n }, { properties: {}, required: [] }),\n additionalProperties: decideAdditionalProperties(def, refs),\n };\n if (!result.required.length)\n delete result.required;\n return result;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/object.js?');
|
|
1033
|
+
/***/
|
|
1034
|
+
},
|
|
1035
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js":
|
|
1036
|
+
/*!**********************************************************************!*\
|
|
1037
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js ***!
|
|
1038
|
+
\**********************************************************************/
|
|
1039
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1040
|
+
"use strict";
|
|
1041
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseOptionalDef: () => (/* binding */ parseOptionalDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nconst parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.innerType._def, refs);\n }\n const innerSchema = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "anyOf", "1"],\n });\n return innerSchema\n ? {\n anyOf: [\n {\n not: {},\n },\n innerSchema,\n ],\n }\n : {};\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js?');
|
|
1042
|
+
/***/
|
|
1043
|
+
},
|
|
1044
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js":
|
|
1045
|
+
/*!**********************************************************************!*\
|
|
1046
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js ***!
|
|
1047
|
+
\**********************************************************************/
|
|
1048
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1049
|
+
"use strict";
|
|
1050
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parsePipelineDef: () => (/* binding */ parsePipelineDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nconst parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === "input") {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.in._def, refs);\n }\n else if (refs.pipeStrategy === "output") {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.out._def, refs);\n }\n const a = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, "allOf", "0"],\n });\n const b = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js?');
|
|
1051
|
+
/***/
|
|
1052
|
+
},
|
|
1053
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js":
|
|
1054
|
+
/*!*********************************************************************!*\
|
|
1055
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js ***!
|
|
1056
|
+
\*********************************************************************/
|
|
1057
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1058
|
+
"use strict";
|
|
1059
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parsePromiseDef: () => (/* binding */ parsePromiseDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nfunction parsePromiseDef(def, refs) {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.type._def, refs);\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js?');
|
|
1060
|
+
/***/
|
|
1061
|
+
},
|
|
1062
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js":
|
|
1063
|
+
/*!**********************************************************************!*\
|
|
1064
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js ***!
|
|
1065
|
+
\**********************************************************************/
|
|
1066
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1067
|
+
"use strict";
|
|
1068
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseReadonlyDef: () => (/* binding */ parseReadonlyDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nconst parseReadonlyDef = (def, refs) => {\n return (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.innerType._def, refs);\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js?');
|
|
1069
|
+
/***/
|
|
1070
|
+
},
|
|
1071
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/record.js":
|
|
1072
|
+
/*!********************************************************************!*\
|
|
1073
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/record.js ***!
|
|
1074
|
+
\********************************************************************/
|
|
1075
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1076
|
+
"use strict";
|
|
1077
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseRecordDef: () => (/* binding */ parseRecordDef)\n/* harmony export */ });\n/* harmony import */ var zod__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! zod */ "./node_modules/zod/lib/index.mjs");\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./string.js */ "./node_modules/zod-to-json-schema/dist/esm/parsers/string.js");\n\n\n\nfunction parseRecordDef(def, refs) {\n if (refs.target === "openApi3" &&\n def.keyType?._def.typeName === zod__WEBPACK_IMPORTED_MODULE_2__.ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: "object",\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "properties", key],\n }) ?? {},\n }), {}),\n additionalProperties: false,\n };\n }\n const schema = {\n type: "object",\n additionalProperties: (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "additionalProperties"],\n }) ?? {},\n };\n if (refs.target === "openApi3") {\n return schema;\n }\n if (def.keyType?._def.typeName === zod__WEBPACK_IMPORTED_MODULE_2__.ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.checks?.length) {\n const keyType = Object.entries((0,_string_js__WEBPACK_IMPORTED_MODULE_1__.parseStringDef)(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === "type" ? acc : { ...acc, [key]: value }), {});\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === zod__WEBPACK_IMPORTED_MODULE_2__.ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n return schema;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/record.js?');
|
|
1078
|
+
/***/
|
|
1079
|
+
},
|
|
1080
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/set.js":
|
|
1081
|
+
/*!*****************************************************************!*\
|
|
1082
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/set.js ***!
|
|
1083
|
+
\*****************************************************************/
|
|
1084
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1085
|
+
"use strict";
|
|
1086
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseSetDef: () => (/* binding */ parseSetDef)\n/* harmony export */ });\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\n\nfunction parseSetDef(def, refs) {\n const items = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_1__.parseDef)(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, "items"],\n });\n const schema = {\n type: "array",\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/set.js?');
|
|
1087
|
+
/***/
|
|
1088
|
+
},
|
|
1089
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/string.js":
|
|
1090
|
+
/*!********************************************************************!*\
|
|
1091
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/string.js ***!
|
|
1092
|
+
\********************************************************************/
|
|
1093
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1094
|
+
"use strict";
|
|
1095
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseStringDef: () => (/* binding */ parseStringDef),\n/* harmony export */ zodPatterns: () => (/* binding */ zodPatterns)\n/* harmony export */ });\n/* harmony import */ var _errorMessages_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errorMessages.js */ "./node_modules/zod-to-json-schema/dist/esm/errorMessages.js");\n\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nconst zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_\'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n */\n emoji: RegExp("^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$", "u"),\n /**\n * Unused\n */\n 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}$/,\n /**\n * Unused\n */\n 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])$/,\n /**\n * Unused\n */\n 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})))$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n};\nfunction parseStringDef(def, refs) {\n const res = {\n type: "string",\n };\n function processPattern(value) {\n return refs.patternStrategy === "escape"\n ? escapeNonAlphaNumeric(value)\n : value;\n }\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case "min":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case "max":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case "email":\n switch (refs.emailStrategy) {\n case "format:email":\n addFormat(res, "email", check.message, refs);\n break;\n case "format:idn-email":\n addFormat(res, "idn-email", check.message, refs);\n break;\n case "pattern:zod":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case "url":\n addFormat(res, "uri", check.message, refs);\n break;\n case "uuid":\n addFormat(res, "uuid", check.message, refs);\n break;\n case "regex":\n addPattern(res, check.regex, check.message, refs);\n break;\n case "cuid":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case "cuid2":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case "startsWith":\n addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs);\n break;\n case "endsWith":\n addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs);\n break;\n case "datetime":\n addFormat(res, "date-time", check.message, refs);\n break;\n case "date":\n addFormat(res, "date", check.message, refs);\n break;\n case "time":\n addFormat(res, "time", check.message, refs);\n break;\n case "duration":\n addFormat(res, "duration", check.message, refs);\n break;\n case "length":\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case "includes": {\n addPattern(res, RegExp(processPattern(check.value)), check.message, refs);\n break;\n }\n case "ip": {\n if (check.version !== "v6") {\n addFormat(res, "ipv4", check.message, refs);\n }\n if (check.version !== "v4") {\n addFormat(res, "ipv6", check.message, refs);\n }\n break;\n }\n case "emoji":\n addPattern(res, zodPatterns.emoji, check.message, refs);\n break;\n case "ulid": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case "base64": {\n switch (refs.base64Strategy) {\n case "format:binary": {\n addFormat(res, "binary", check.message, refs);\n break;\n }\n case "contentEncoding:base64": {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(res, "contentEncoding", "base64", check.message, refs);\n break;\n }\n case "pattern:zod": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case "nanoid": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case "toLowerCase":\n case "toUpperCase":\n case "trim":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nconst escapeNonAlphaNumeric = (value) => Array.from(value)\n .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\\\${c}`))\n .join("");\nconst addFormat = (schema, value, message, refs) => {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(schema, "format", value, message, refs);\n }\n};\nconst addPattern = (schema, regex, message, refs) => {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: processRegExp(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n (0,_errorMessages_js__WEBPACK_IMPORTED_MODULE_0__.setResponseValueAndErrors)(schema, "pattern", processRegExp(regex, refs), message, refs);\n }\n};\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nconst processRegExp = (regex, refs) => {\n if (!refs.applyRegexFlags || !regex.flags)\n return regex.source;\n // Currently handled flags\n const flags = {\n i: regex.flags.includes("i"),\n m: regex.flags.includes("m"),\n s: regex.flags.includes("s"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it\'s inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = "";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === "^") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === "$") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === ".") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === "\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === "]") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === "[") {\n inCharGroup = true;\n }\n }\n try {\n const regexTest = new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/string.js?');
|
|
1096
|
+
/***/
|
|
1097
|
+
},
|
|
1098
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js":
|
|
1099
|
+
/*!*******************************************************************!*\
|
|
1100
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js ***!
|
|
1101
|
+
\*******************************************************************/
|
|
1102
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1103
|
+
"use strict";
|
|
1104
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseTupleDef: () => (/* binding */ parseTupleDef)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nfunction parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: "array",\n minItems: def.items.length,\n items: def.items\n .map((x, i) => (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, "items", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, "additionalItems"],\n }),\n };\n }\n else {\n return {\n type: "array",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, "items", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js?');
|
|
1105
|
+
/***/
|
|
1106
|
+
},
|
|
1107
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js":
|
|
1108
|
+
/*!***********************************************************************!*\
|
|
1109
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js ***!
|
|
1110
|
+
\***********************************************************************/
|
|
1111
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1112
|
+
"use strict";
|
|
1113
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseUndefinedDef: () => (/* binding */ parseUndefinedDef)\n/* harmony export */ });\nfunction parseUndefinedDef() {\n return {\n not: {},\n };\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js?");
|
|
1114
|
+
/***/
|
|
1115
|
+
},
|
|
1116
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/union.js":
|
|
1117
|
+
/*!*******************************************************************!*\
|
|
1118
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/union.js ***!
|
|
1119
|
+
\*******************************************************************/
|
|
1120
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1121
|
+
"use strict";
|
|
1122
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseUnionDef: () => (/* binding */ parseUnionDef),\n/* harmony export */ primitiveMappings: () => (/* binding */ primitiveMappings)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n\nconst primitiveMappings = {\n ZodString: "string",\n ZodNumber: "number",\n ZodBigInt: "integer",\n ZodBoolean: "boolean",\n ZodNull: "null",\n};\nfunction parseUnionDef(def, refs) {\n if (refs.target === "openApi3")\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings &&\n (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case "string":\n case "number":\n case "boolean":\n return [...acc, type];\n case "bigint":\n return [...acc, "integer"];\n case "object":\n if (x._def.value === null)\n return [...acc, "null"];\n case "symbol":\n case "undefined":\n case "function":\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === "ZodEnum")) {\n return {\n type: "string",\n enum: options.reduce((acc, x) => [\n ...acc,\n ...x._def.values.filter((x) => !acc.includes(x)),\n ], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map\n ? Array.from(def.options.values())\n : def.options)\n .map((x, i) => (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, "anyOf", `${i}`],\n }))\n .filter((x) => !!x &&\n (!refs.strictUnions ||\n (typeof x === "object" && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/union.js?');
|
|
1123
|
+
/***/
|
|
1124
|
+
},
|
|
1125
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js":
|
|
1126
|
+
/*!*********************************************************************!*\
|
|
1127
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js ***!
|
|
1128
|
+
\*********************************************************************/
|
|
1129
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1130
|
+
"use strict";
|
|
1131
|
+
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ parseUnknownDef: () => (/* binding */ parseUnknownDef)\n/* harmony export */ });\nfunction parseUnknownDef() {\n return {};\n}\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js?");
|
|
1132
|
+
/***/
|
|
1133
|
+
},
|
|
1134
|
+
/***/ "./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js":
|
|
1135
|
+
/*!*********************************************************************!*\
|
|
1136
|
+
!*** ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js ***!
|
|
1137
|
+
\*********************************************************************/
|
|
1138
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1139
|
+
"use strict";
|
|
1140
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ zodToJsonSchema: () => (/* binding */ zodToJsonSchema)\n/* harmony export */ });\n/* harmony import */ var _parseDef_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./parseDef.js */ "./node_modules/zod-to-json-schema/dist/esm/parseDef.js");\n/* harmony import */ var _Refs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Refs.js */ "./node_modules/zod-to-json-schema/dist/esm/Refs.js");\n\n\nconst zodToJsonSchema = (schema, options) => {\n const refs = (0,_Refs_js__WEBPACK_IMPORTED_MODULE_1__.getRefs)(options);\n const definitions = typeof options === "object" && options.definitions\n ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({\n ...acc,\n [name]: (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(schema._def, {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, true) ?? {},\n }), {})\n : undefined;\n const name = typeof options === "string"\n ? options\n : options?.nameStrategy === "title"\n ? undefined\n : options?.name;\n const main = (0,_parseDef_js__WEBPACK_IMPORTED_MODULE_0__.parseDef)(schema._def, name === undefined\n ? refs\n : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, false) ?? {};\n const title = typeof options === "object" &&\n options.name !== undefined &&\n options.nameStrategy === "title"\n ? options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n const combined = name === undefined\n ? definitions\n ? {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : {\n $ref: [\n ...(refs.$refStrategy === "relative" ? [] : refs.basePath),\n refs.definitionPath,\n name,\n ].join("/"),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === "jsonSchema7") {\n combined.$schema = "http://json-schema.org/draft-07/schema#";\n }\n else if (refs.target === "jsonSchema2019-09") {\n combined.$schema = "https://json-schema.org/draft/2019-09/schema#";\n }\n return combined;\n};\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js?');
|
|
1141
|
+
/***/
|
|
1142
|
+
},
|
|
1143
|
+
/***/ "./node_modules/zod/lib/index.mjs":
|
|
1144
|
+
/*!****************************************!*\
|
|
1145
|
+
!*** ./node_modules/zod/lib/index.mjs ***!
|
|
1146
|
+
\****************************************/
|
|
1147
|
+
/***/ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
|
|
1148
|
+
"use strict";
|
|
1149
|
+
eval('__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ BRAND: () => (/* binding */ BRAND),\n/* harmony export */ DIRTY: () => (/* binding */ DIRTY),\n/* harmony export */ EMPTY_PATH: () => (/* binding */ EMPTY_PATH),\n/* harmony export */ INVALID: () => (/* binding */ INVALID),\n/* harmony export */ NEVER: () => (/* binding */ NEVER),\n/* harmony export */ OK: () => (/* binding */ OK),\n/* harmony export */ ParseStatus: () => (/* binding */ ParseStatus),\n/* harmony export */ Schema: () => (/* binding */ ZodType),\n/* harmony export */ ZodAny: () => (/* binding */ ZodAny),\n/* harmony export */ ZodArray: () => (/* binding */ ZodArray),\n/* harmony export */ ZodBigInt: () => (/* binding */ ZodBigInt),\n/* harmony export */ ZodBoolean: () => (/* binding */ ZodBoolean),\n/* harmony export */ ZodBranded: () => (/* binding */ ZodBranded),\n/* harmony export */ ZodCatch: () => (/* binding */ ZodCatch),\n/* harmony export */ ZodDate: () => (/* binding */ ZodDate),\n/* harmony export */ ZodDefault: () => (/* binding */ ZodDefault),\n/* harmony export */ ZodDiscriminatedUnion: () => (/* binding */ ZodDiscriminatedUnion),\n/* harmony export */ ZodEffects: () => (/* binding */ ZodEffects),\n/* harmony export */ ZodEnum: () => (/* binding */ ZodEnum),\n/* harmony export */ ZodError: () => (/* binding */ ZodError),\n/* harmony export */ ZodFirstPartyTypeKind: () => (/* binding */ ZodFirstPartyTypeKind),\n/* harmony export */ ZodFunction: () => (/* binding */ ZodFunction),\n/* harmony export */ ZodIntersection: () => (/* binding */ ZodIntersection),\n/* harmony export */ ZodIssueCode: () => (/* binding */ ZodIssueCode),\n/* harmony export */ ZodLazy: () => (/* binding */ ZodLazy),\n/* harmony export */ ZodLiteral: () => (/* binding */ ZodLiteral),\n/* harmony export */ ZodMap: () => (/* binding */ ZodMap),\n/* harmony export */ ZodNaN: () => (/* binding */ ZodNaN),\n/* harmony export */ ZodNativeEnum: () => (/* binding */ ZodNativeEnum),\n/* harmony export */ ZodNever: () => (/* binding */ ZodNever),\n/* harmony export */ ZodNull: () => (/* binding */ ZodNull),\n/* harmony export */ ZodNullable: () => (/* binding */ ZodNullable),\n/* harmony export */ ZodNumber: () => (/* binding */ ZodNumber),\n/* harmony export */ ZodObject: () => (/* binding */ ZodObject),\n/* harmony export */ ZodOptional: () => (/* binding */ ZodOptional),\n/* harmony export */ ZodParsedType: () => (/* binding */ ZodParsedType),\n/* harmony export */ ZodPipeline: () => (/* binding */ ZodPipeline),\n/* harmony export */ ZodPromise: () => (/* binding */ ZodPromise),\n/* harmony export */ ZodReadonly: () => (/* binding */ ZodReadonly),\n/* harmony export */ ZodRecord: () => (/* binding */ ZodRecord),\n/* harmony export */ ZodSchema: () => (/* binding */ ZodType),\n/* harmony export */ ZodSet: () => (/* binding */ ZodSet),\n/* harmony export */ ZodString: () => (/* binding */ ZodString),\n/* harmony export */ ZodSymbol: () => (/* binding */ ZodSymbol),\n/* harmony export */ ZodTransformer: () => (/* binding */ ZodEffects),\n/* harmony export */ ZodTuple: () => (/* binding */ ZodTuple),\n/* harmony export */ ZodType: () => (/* binding */ ZodType),\n/* harmony export */ ZodUndefined: () => (/* binding */ ZodUndefined),\n/* harmony export */ ZodUnion: () => (/* binding */ ZodUnion),\n/* harmony export */ ZodUnknown: () => (/* binding */ ZodUnknown),\n/* harmony export */ ZodVoid: () => (/* binding */ ZodVoid),\n/* harmony export */ addIssueToContext: () => (/* binding */ addIssueToContext),\n/* harmony export */ any: () => (/* binding */ anyType),\n/* harmony export */ array: () => (/* binding */ arrayType),\n/* harmony export */ bigint: () => (/* binding */ bigIntType),\n/* harmony export */ boolean: () => (/* binding */ booleanType),\n/* harmony export */ coerce: () => (/* binding */ coerce),\n/* harmony export */ custom: () => (/* binding */ custom),\n/* harmony export */ date: () => (/* binding */ dateType),\n/* harmony export */ datetimeRegex: () => (/* binding */ datetimeRegex),\n/* harmony export */ "default": () => (/* binding */ z),\n/* harmony export */ defaultErrorMap: () => (/* binding */ errorMap),\n/* harmony export */ discriminatedUnion: () => (/* binding */ discriminatedUnionType),\n/* harmony export */ effect: () => (/* binding */ effectsType),\n/* harmony export */ "enum": () => (/* binding */ enumType),\n/* harmony export */ "function": () => (/* binding */ functionType),\n/* harmony export */ getErrorMap: () => (/* binding */ getErrorMap),\n/* harmony export */ getParsedType: () => (/* binding */ getParsedType),\n/* harmony export */ "instanceof": () => (/* binding */ instanceOfType),\n/* harmony export */ intersection: () => (/* binding */ intersectionType),\n/* harmony export */ isAborted: () => (/* binding */ isAborted),\n/* harmony export */ isAsync: () => (/* binding */ isAsync),\n/* harmony export */ isDirty: () => (/* binding */ isDirty),\n/* harmony export */ isValid: () => (/* binding */ isValid),\n/* harmony export */ late: () => (/* binding */ late),\n/* harmony export */ lazy: () => (/* binding */ lazyType),\n/* harmony export */ literal: () => (/* binding */ literalType),\n/* harmony export */ makeIssue: () => (/* binding */ makeIssue),\n/* harmony export */ map: () => (/* binding */ mapType),\n/* harmony export */ nan: () => (/* binding */ nanType),\n/* harmony export */ nativeEnum: () => (/* binding */ nativeEnumType),\n/* harmony export */ never: () => (/* binding */ neverType),\n/* harmony export */ "null": () => (/* binding */ nullType),\n/* harmony export */ nullable: () => (/* binding */ nullableType),\n/* harmony export */ number: () => (/* binding */ numberType),\n/* harmony export */ object: () => (/* binding */ objectType),\n/* harmony export */ objectUtil: () => (/* binding */ objectUtil),\n/* harmony export */ oboolean: () => (/* binding */ oboolean),\n/* harmony export */ onumber: () => (/* binding */ onumber),\n/* harmony export */ optional: () => (/* binding */ optionalType),\n/* harmony export */ ostring: () => (/* binding */ ostring),\n/* harmony export */ pipeline: () => (/* binding */ pipelineType),\n/* harmony export */ preprocess: () => (/* binding */ preprocessType),\n/* harmony export */ promise: () => (/* binding */ promiseType),\n/* harmony export */ quotelessJson: () => (/* binding */ quotelessJson),\n/* harmony export */ record: () => (/* binding */ recordType),\n/* harmony export */ set: () => (/* binding */ setType),\n/* harmony export */ setErrorMap: () => (/* binding */ setErrorMap),\n/* harmony export */ strictObject: () => (/* binding */ strictObjectType),\n/* harmony export */ string: () => (/* binding */ stringType),\n/* harmony export */ symbol: () => (/* binding */ symbolType),\n/* harmony export */ transformer: () => (/* binding */ effectsType),\n/* harmony export */ tuple: () => (/* binding */ tupleType),\n/* harmony export */ undefined: () => (/* binding */ undefinedType),\n/* harmony export */ union: () => (/* binding */ unionType),\n/* harmony export */ unknown: () => (/* binding */ unknownType),\n/* harmony export */ util: () => (/* binding */ util),\n/* harmony export */ "void": () => (/* binding */ voidType),\n/* harmony export */ z: () => (/* binding */ z)\n/* harmony export */ });\nvar util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === "function"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = " | ") {\n return array\n .map((val) => (typeof val === "string" ? `\'${val}\'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === "bigint") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n "string",\n "nan",\n "number",\n "integer",\n "float",\n "boolean",\n "date",\n "bigint",\n "symbol",\n "function",\n "undefined",\n "null",\n "array",\n "object",\n "unknown",\n "promise",\n "void",\n "never",\n "map",\n "set",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case "undefined":\n return ZodParsedType.undefined;\n case "string":\n return ZodParsedType.string;\n case "number":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case "boolean":\n return ZodParsedType.boolean;\n case "function":\n return ZodParsedType.function;\n case "bigint":\n return ZodParsedType.bigint;\n case "symbol":\n return ZodParsedType.symbol;\n case "object":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === "function" &&\n data.catch &&\n typeof data.catch === "function") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== "undefined" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== "undefined" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== "undefined" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n "invalid_type",\n "invalid_literal",\n "custom",\n "invalid_union",\n "invalid_union_discriminator",\n "invalid_enum_value",\n "unrecognized_keys",\n "invalid_arguments",\n "invalid_return_type",\n "invalid_date",\n "invalid_string",\n "too_small",\n "too_big",\n "invalid_intersection_types",\n "not_multiple_of",\n "not_finite",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/"([^"]+)":/g, "$1:");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = "ZodError";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === "invalid_union") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === "invalid_return_type") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === "invalid_arguments") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === "string") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === "number") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = "Required";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received \'${issue.received}\'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === "object") {\n if ("includes" in issue.validation) {\n message = `Invalid input: must include "${issue.validation.includes}"`;\n if (typeof issue.validation.position === "number") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if ("startsWith" in issue.validation) {\n message = `Invalid input: must start with "${issue.validation.startsWith}"`;\n }\n else if ("endsWith" in issue.validation) {\n message = `Invalid input: must end with "${issue.validation.endsWith}"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== "regex") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = "Invalid";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === "array")\n message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === "string")\n message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === "number")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === "date")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = "Invalid input";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === "array")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === "string")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === "number")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === "bigint")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === "date")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = "Invalid input";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = "Number must be finite";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = "";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n overrideMap,\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = "valid";\n }\n dirty() {\n if (this.value === "valid")\n this.value = "dirty";\n }\n abort() {\n if (this.value !== "aborted")\n this.value = "aborted";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === "aborted")\n return INVALID;\n if (s.status === "dirty")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === "aborted")\n return INVALID;\n if (value.status === "aborted")\n return INVALID;\n if (key.status === "dirty")\n status.dirty();\n if (value.status === "dirty")\n status.dirty();\n if (key.value !== "__proto__" &&\n (typeof value.value !== "undefined" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: "aborted",\n});\nconst DIRTY = (value) => ({ status: "dirty", value });\nconst OK = (value) => ({ status: "valid", value });\nconst isAborted = (x) => x.status === "aborted";\nconst isDirty = (x) => x.status === "dirty";\nconst isValid = (x) => x.status === "valid";\nconst isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");\r\n if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");\r\n return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === "m") throw new TypeError("Private method is not writable");\r\n if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");\r\n if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");\r\n return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error("Validation failed but no issues detected.");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === "invalid_enum_value") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === "undefined") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== "invalid_type")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error("Synchronous parse encountered promise.");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === "string" || typeof message === "undefined") {\n return { message };\n }\n else if (typeof message === "function") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== "undefined" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === "function"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: "refinement", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: "transform", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === "function" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === "function" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst 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;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst 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)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn\'t support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&\'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&\'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@"]+(\\.[^<>()[\\].,;:\\s@"]+)*)|(".+"))@((?!-)([^<>()[\\].,;:\\s@"]+\\.)+[^<>()[\\].,;:\\s@"]{1,})[^-<>()[\\].,;:\\s@"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\"]+)*)|(\\".+\\"))@((\\[(((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}))\\])|(\\[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})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_\'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst 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])$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst 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])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join("|")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === "v4" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === "v6" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "string",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "max") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "string",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "length") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "string",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "string",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === "email") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "email",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "emoji") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, "u");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "emoji",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "uuid") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "uuid",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "nanoid") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "nanoid",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "cuid") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cuid",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "cuid2") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "cuid2",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "ulid") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "ulid",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "url") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "url",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "regex") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "regex",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "trim") {\n input.data = input.data.trim();\n }\n else if (check.kind === "includes") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "toLowerCase") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === "toUpperCase") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === "startsWith") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "endsWith") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "datetime") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "datetime",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "date") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "date",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "time") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: "time",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "duration") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "duration",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "ip") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "ip",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "base64") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: "base64",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === "string") {\n return this._addCheck({\n kind: "datetime",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: "datetime",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: "date", message });\n }\n time(options) {\n if (typeof options === "string") {\n return this._addCheck({\n kind: "time",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: "time",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: "regex",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: "includes",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: "startsWith",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: "endsWith",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: "min",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: "max",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: "length",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "trim" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "toLowerCase" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: "toUpperCase" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === "datetime");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === "date");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === "time");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === "duration");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === "email");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === "url");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === "emoji");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === "uuid");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === "nanoid");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === "cuid");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === "cuid2");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === "ulid");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === "ip");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === "base64");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(".")[1] || "").length;\n const stepDecCount = (step.toString().split(".")[1] || "").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(".", ""));\n const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === "int") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: "integer",\n received: "float",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "min") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: "number",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "max") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: "number",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "multipleOf") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "finite") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit("min", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit("min", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit("max", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit("max", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: "int",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: "min",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: "max",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: "max",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: "min",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: "multipleOf",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: "finite",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: "min",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: "max",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === "int" ||\n (ch.kind === "multipleOf" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "finite" ||\n ch.kind === "int" ||\n ch.kind === "multipleOf") {\n return true;\n }\n else if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: "bigint",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "max") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: "bigint",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === "multipleOf") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit("min", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit("min", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit("max", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit("max", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: "min",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: "max",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: "max",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: "min",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: "multipleOf",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === "min") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: "date",\n });\n status.dirty();\n }\n }\n else if (check.kind === "max") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: "date",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: "min",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: "max",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "min") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === "max") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: "array",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: "array",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: "array",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k]["_output"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k]["_input"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === "strip")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: "valid", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === "passthrough") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: "valid", value: key },\n value: { status: "valid", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === "strict") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === "strip") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: "valid", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: "strict",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === "unrecognized_keys")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: "strip",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: "passthrough",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def["shape"]>, Augmentation>,\n // Def["unknownKeys"],\n // Def["catchall"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming["shape"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k]["_output"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k]["_input"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,\n // Incoming["_def"]["unknownKeys"],\n // Incoming["_def"]["catchall"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,\n // Incoming["_def"]["unknownKeys"],\n // Incoming["_def"]["catchall"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: "strip",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: "strict",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: "strip",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === "valid") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === "dirty") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === "valid") {\n return result;\n }\n else if (result.status === "dirty" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: "array",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: "array",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error("You must pass an array of schemas to z.tuple([ ... ])");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === "aborted" || value.status === "aborted") {\n return INVALID;\n }\n if (key.status === "dirty" || value.status === "dirty") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === "aborted" || value.status === "aborted") {\n return INVALID;\n }\n if (key.status === "dirty" || value.status === "dirty") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: "set",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: "set",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === "aborted")\n return INVALID;\n if (element.status === "dirty")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: "valid", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== "string") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === "preprocess") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === "aborted")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === "aborted")\n return INVALID;\n if (result.status === "dirty")\n return DIRTY(result.value);\n if (status.value === "dirty")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === "aborted")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === "aborted")\n return INVALID;\n if (result.status === "dirty")\n return DIRTY(result.value);\n if (status.value === "dirty")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === "refinement") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === "aborted")\n return INVALID;\n if (inner.status === "dirty")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === "aborted")\n return INVALID;\n if (inner.status === "dirty")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === "transform") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: "preprocess", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === "function"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: "valid",\n value: result.status === "valid"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: "valid",\n value: result.status === "valid"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: "valid", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol("zod_brand");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === "aborted")\n return INVALID;\n if (inResult.status === "dirty") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === "aborted")\n return INVALID;\n if (inResult.status === "dirty") {\n status.dirty();\n return {\n status: "dirty",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === "function"\n ? params(data)\n : typeof params === "string"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === "string" ? { message: p } : p;\n ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind["ZodString"] = "ZodString";\n ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";\n ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";\n ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";\n ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";\n ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";\n ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";\n ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";\n ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";\n ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";\n ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";\n ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";\n ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";\n ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";\n ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";\n ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";\n ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";\n ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";\n ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";\n ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";\n ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";\n ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";\n ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";\n ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";\n ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";\n ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";\n ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";\n ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";\n ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";\n ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";\n ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";\n ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";\n ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";\n ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";\n ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";\n ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n \'enum\': enumType,\n \'function\': functionType,\n \'instanceof\': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n \'null\': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n \'undefined\': undefinedType,\n union: unionType,\n unknown: unknownType,\n \'void\': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\n\n\n\n//# sourceURL=webpack://chrome_ai/./node_modules/zod/lib/index.mjs?');
|
|
1150
|
+
/***/
|
|
1151
|
+
},
|
|
1152
|
+
/******/
|
|
1153
|
+
};
|
|
1154
|
+
/************************************************************************/
|
|
1155
|
+
/******/ // The module cache
|
|
1156
|
+
/******/ var __webpack_module_cache__ = {};
|
|
1157
|
+
/******/
|
|
1158
|
+
/******/ // The require function
|
|
1159
|
+
/******/ function __webpack_require__(moduleId) {
|
|
1160
|
+
/******/ // Check if module is in cache
|
|
1161
|
+
/******/ var cachedModule = __webpack_module_cache__[moduleId];
|
|
1162
|
+
/******/ if (cachedModule !== undefined) {
|
|
1163
|
+
/******/ return cachedModule.exports;
|
|
1164
|
+
/******/
|
|
1165
|
+
}
|
|
1166
|
+
/******/ // Create a new module (and put it into the cache)
|
|
1167
|
+
/******/ var module = (__webpack_module_cache__[moduleId] = {
|
|
1168
|
+
/******/ id: moduleId,
|
|
1169
|
+
/******/ loaded: false,
|
|
1170
|
+
/******/ exports: {},
|
|
1171
|
+
/******/
|
|
1172
|
+
});
|
|
1173
|
+
/******/
|
|
1174
|
+
/******/ // Execute the module function
|
|
1175
|
+
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
|
|
1176
|
+
/******/
|
|
1177
|
+
/******/ // Flag the module as loaded
|
|
1178
|
+
/******/ module.loaded = true;
|
|
1179
|
+
/******/
|
|
1180
|
+
/******/ // Return the exports of the module
|
|
1181
|
+
/******/ return module.exports;
|
|
1182
|
+
/******/
|
|
1183
|
+
}
|
|
1184
|
+
/******/
|
|
1185
|
+
/************************************************************************/
|
|
1186
|
+
/******/ /* webpack/runtime/define property getters */
|
|
1187
|
+
/******/ (() => {
|
|
1188
|
+
/******/ // define getter functions for harmony exports
|
|
1189
|
+
/******/ __webpack_require__.d = (exports, definition) => {
|
|
1190
|
+
/******/ for (var key in definition) {
|
|
1191
|
+
/******/ if (__webpack_require__.o(definition, key) &&
|
|
1192
|
+
!__webpack_require__.o(exports, key)) {
|
|
1193
|
+
/******/ Object.defineProperty(exports, key, {
|
|
1194
|
+
enumerable: true,
|
|
1195
|
+
get: definition[key],
|
|
1196
|
+
});
|
|
1197
|
+
/******/
|
|
1198
|
+
}
|
|
1199
|
+
/******/
|
|
1200
|
+
}
|
|
1201
|
+
/******/
|
|
1202
|
+
};
|
|
1203
|
+
/******/
|
|
1204
|
+
})();
|
|
1205
|
+
/******/
|
|
1206
|
+
/******/ /* webpack/runtime/hasOwnProperty shorthand */
|
|
1207
|
+
/******/ (() => {
|
|
1208
|
+
/******/ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
|
|
1209
|
+
/******/
|
|
1210
|
+
})();
|
|
1211
|
+
/******/
|
|
1212
|
+
/******/ /* webpack/runtime/make namespace object */
|
|
1213
|
+
/******/ (() => {
|
|
1214
|
+
/******/ // define __esModule on exports
|
|
1215
|
+
/******/ __webpack_require__.r = (exports) => {
|
|
1216
|
+
/******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
|
|
1217
|
+
/******/ Object.defineProperty(exports, Symbol.toStringTag, {
|
|
1218
|
+
value: "Module",
|
|
1219
|
+
});
|
|
1220
|
+
/******/
|
|
1221
|
+
}
|
|
1222
|
+
/******/ Object.defineProperty(exports, "__esModule", { value: true });
|
|
1223
|
+
/******/
|
|
1224
|
+
};
|
|
1225
|
+
/******/
|
|
1226
|
+
})();
|
|
1227
|
+
/******/
|
|
1228
|
+
/******/ /* webpack/runtime/node module decorator */
|
|
1229
|
+
/******/ (() => {
|
|
1230
|
+
/******/ __webpack_require__.nmd = (module) => {
|
|
1231
|
+
/******/ module.paths = [];
|
|
1232
|
+
/******/ if (!module.children)
|
|
1233
|
+
module.children = [];
|
|
1234
|
+
/******/ return module;
|
|
1235
|
+
/******/
|
|
1236
|
+
};
|
|
1237
|
+
/******/
|
|
1238
|
+
})();
|
|
1239
|
+
/******/
|
|
1240
|
+
/************************************************************************/
|
|
1241
|
+
/******/
|
|
1242
|
+
/******/ // startup
|
|
1243
|
+
/******/ // Load entry module and return exports
|
|
1244
|
+
/******/ // This entry module can't be inlined because the eval devtool is used.
|
|
1245
|
+
/******/ var __webpack_exports__ = __webpack_require__("./src/index.js");
|
|
1246
|
+
/******/
|
|
1247
|
+
/******/
|
|
1248
|
+
})();
|
|
1249
|
+
export {};
|