diff --git a/dist/130.index.js b/dist/130.index.js new file mode 100644 index 0000000..b1109a3 --- /dev/null +++ b/dist/130.index.js @@ -0,0 +1,635 @@ +export const id = 130; +export const ids = [130,197,273]; +export const modules = { + +/***/ 3197: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "l": () => (/* binding */ BaseChain) +/* harmony export */ }); +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6009); +/* harmony import */ var _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7679); + + + +/** + * Base interface that all chains must implement. + */ +class BaseChain extends _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__/* .BaseLangChain */ .BD { + get lc_namespace() { + return ["langchain", "chains", this._chainType()]; + } + constructor(fields, + /** @deprecated */ + verbose, + /** @deprecated */ + callbacks) { + if (arguments.length === 1 && + typeof fields === "object" && + !("saveContext" in fields)) { + // fields is not a BaseMemory + const { memory, callbackManager, ...rest } = fields; + super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); + this.memory = memory; + } + else { + // fields is a BaseMemory + super({ verbose, callbacks }); + this.memory = fields; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = { ...values }; + if ("signal" in valuesForMemory) { + delete valuesForMemory.signal; + } + if ("timeout" in valuesForMemory) { + delete valuesForMemory.timeout; + } + return valuesForMemory; + } + /** + * Invoke the chain with the provided input and returns the output. + * @param input Input values for the chain run. + * @param config Optional configuration for the Runnable. + * @returns Promise that resolves with the output of the chain run. + */ + async invoke(input, config) { + return this.call(input, config); + } + /** + * Return a json-like object representing this chain. + */ + serialize() { + throw new Error("Method not implemented."); + } + async run( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, config) { + const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); + const isKeylessInput = inputKeys.length <= 1; + if (!isKeylessInput) { + throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; + const returnValues = await this.call(values, config); + const keys = Object.keys(returnValues); + if (keys.length === 1) { + return returnValues[keys[0]]; + } + throw new Error("return values have multiple keys, `run` only supported when one key currently"); + } + async _formatValues(values) { + const fullValues = { ...values }; + if (fullValues.timeout && !fullValues.signal) { + fullValues.signal = AbortSignal.timeout(fullValues.timeout); + delete fullValues.timeout; + } + if (!(this.memory == null)) { + const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); + for (const [key, value] of Object.entries(newValues)) { + fullValues[key] = value; + } + } + return fullValues; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + async call(values, config, + /** @deprecated */ + tags) { + const fullValues = await this._formatValues(values); + const parsedConfig = (0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .parseCallbackConfigArg */ .QH)(config); + const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .CallbackManager.configure */ .Ye.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); + let outputValues; + try { + outputValues = await (values.signal + ? Promise.race([ + this._call(fullValues, runManager), + new Promise((_, reject) => { + values.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]) + : this._call(fullValues, runManager)); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + if (!(this.memory == null)) { + await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + } + await runManager?.handleChainEnd(outputValues); + // add the runManager's currentRunId to the outputValues + Object.defineProperty(outputValues, _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .RUN_KEY */ .WH, { + value: runManager ? { runId: runManager?.runId } : undefined, + configurable: true, + }); + return outputValues; + } + /** + * Call the chain on all inputs in the list + */ + async apply(inputs, config) { + return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + } + /** + * Load a chain from a json-like object describing it. + */ + static async deserialize(data, values = {}) { + switch (data._type) { + case "llm_chain": { + const { LLMChain } = await __webpack_require__.e(/* import() */ 273).then(__webpack_require__.bind(__webpack_require__, 7273)); + return LLMChain.deserialize(data); + } + case "sequential_chain": { + const { SequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SequentialChain.deserialize(data); + } + case "simple_sequential_chain": { + const { SimpleSequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SimpleSequentialChain.deserialize(data); + } + case "stuff_documents_chain": { + const { StuffDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return StuffDocumentsChain.deserialize(data); + } + case "map_reduce_documents_chain": { + const { MapReduceDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return MapReduceDocumentsChain.deserialize(data); + } + case "refine_documents_chain": { + const { RefineDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return RefineDocumentsChain.deserialize(data); + } + case "vector_db_qa": { + const { VectorDBQAChain } = await Promise.all(/* import() */[__webpack_require__.e(608), __webpack_require__.e(214)]).then(__webpack_require__.bind(__webpack_require__, 5214)); + return VectorDBQAChain.deserialize(data, values); + } + case "api_chain": { + const { APIChain } = await __webpack_require__.e(/* import() */ 159).then(__webpack_require__.bind(__webpack_require__, 6159)); + return APIChain.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } +} + + +/***/ }), + +/***/ 7273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "LLMChain": () => (/* binding */ LLMChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules +var runnable = __webpack_require__(1972); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/output_parser.js + +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends runnable/* Runnable */.eq { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input) => this.parseResult([{ text: input }]), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input) => this.parseResult([{ message: input, text: input.content }]), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Class to parse the output of an LLM call that also allows streaming inputs. + */ +class BaseTransformOutputParser extends (/* unused pure expression or super */ null && (BaseOutputParser)) { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) { + if (typeof chunk === "string") { + yield this.parseResult([{ text: chunk }]); + } + else { + yield this.parseResult([{ message: chunk, text: chunk.content }]); + } + } + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser", + }); + } +} +/** + * OutputParser that parses LLMResult into the top likely string. + */ +class StringOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "StrOutputParser"; + } + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } +} +/** + * OutputParser that parses LLMResult into the top likely string and + * encodes it into bytes. + */ +class BytesOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "textEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: new TextEncoder() + }); + } + static lc_name() { + return "BytesOutputParser"; + } + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/output_parsers/noop.js + +/** + * The NoOpOutputParser class is a type of output parser that does not + * perform any operations on the output. It extends the BaseOutputParser + * class and is part of the LangChain's output parsers module. This class + * is useful in scenarios where the raw output of the Large Language + * Models (LLMs) is required. + */ +class NoOpOutputParser extends BaseOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "output_parsers", "default"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "NoOpOutputParser"; + } + /** + * This method takes a string as input and returns the same string as + * output. It does not perform any operations on the input string. + * @param text The input string to be parsed. + * @returns The same input string without any operations performed on it. + */ + parse(text) { + return Promise.resolve(text); + } + /** + * This method returns an empty string. It does not provide any formatting + * instructions. + * @returns An empty string, indicating no formatting instructions. + */ + getFormatInstructions() { + return ""; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + + + + +/** + * Chain to run queries against LLMs. + * + * @example + * ```ts + * import { LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); + * const llm = new LLMChain({ llm: new OpenAI(), prompt }); + * ``` + */ +class LLMChain extends base/* BaseChain */.l { + static lc_name() { + return "LLMChain"; + } + get inputKeys() { + return this.prompt.inputVariables; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llmKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "text" + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + this.llm = fields.llm; + this.llmKwargs = fields.llmKwargs; + this.outputKey = fields.outputKey ?? this.outputKey; + this.outputParser = + fields.outputParser ?? new NoOpOutputParser(); + if (this.prompt.outputParser) { + if (fields.outputParser) { + throw new Error("Cannot set both outputParser and prompt.outputParser"); + } + this.outputParser = this.prompt.outputParser; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = super._selectMemoryInputs(values); + for (const key of this.llm.callKeys) { + if (key in values) { + delete valuesForMemory[key]; + } + } + return valuesForMemory; + } + /** @ignore */ + async _getFinalOutput(generations, promptValue, runManager) { + let finalCompletion; + if (this.outputParser) { + finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + } + else { + finalCompletion = generations[0].text; + } + return finalCompletion; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + call(values, config) { + return super.call(values, config); + } + /** @ignore */ + async _call(values, runManager) { + const valuesForPrompt = { ...values }; + const valuesForLLM = { + ...this.llmKwargs, + }; + for (const key of this.llm.callKeys) { + if (key in values) { + valuesForLLM[key] = values[key]; + delete valuesForPrompt[key]; + } + } + const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); + const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); + return { + [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), + }; + } + /** + * Format prompt with values and pass to LLM + * + * @param values - keys to pass to prompt template + * @param callbackManager - CallbackManager to use + * @returns Completion from LLM. + * + * @example + * ```ts + * llm.predict({ adjective: "funny" }) + * ``` + */ + async predict(values, callbackManager) { + const output = await this.call(values, callbackManager); + return output[this.outputKey]; + } + _chainType() { + return "llm"; + } + static async deserialize(data) { + const { llm, prompt } = data; + if (!llm) { + throw new Error("LLMChain must have llm"); + } + if (!prompt) { + throw new Error("LLMChain must have prompt"); + } + return new LLMChain({ + llm: await base_language/* BaseLanguageModel.deserialize */.qV.deserialize(llm), + prompt: await prompts_base/* BasePromptTemplate.deserialize */.dy.deserialize(prompt), + }); + } + /** @deprecated */ + serialize() { + return { + _type: `${this._chainType()}_chain`, + llm: this.llm.serialize(), + prompt: this.prompt.serialize(), + }; + } +} + + +/***/ }) + +}; diff --git a/dist/159.index.js b/dist/159.index.js new file mode 100644 index 0000000..bd6e0f4 --- /dev/null +++ b/dist/159.index.js @@ -0,0 +1,614 @@ +export const id = 159; +export const ids = [159,273]; +export const modules = { + +/***/ 6159: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "APIChain": () => (/* binding */ APIChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 2 modules +var llm_chain = __webpack_require__(7273); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js +var prompts_prompt = __webpack_require__(4095); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/api/prompts.js +/* eslint-disable spaced-comment */ + +const API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation: +{api_docs} +Using this documentation, generate the full API url to call for answering the user question. +You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call. + +Question:{question} +API url:`; +const API_URL_PROMPT_TEMPLATE = /* #__PURE__ */ new prompts_prompt.PromptTemplate({ + inputVariables: ["api_docs", "question"], + template: API_URL_RAW_PROMPT_TEMPLATE, +}); +const API_RESPONSE_RAW_PROMPT_TEMPLATE = `${API_URL_RAW_PROMPT_TEMPLATE} {api_url} + +Here is the response from the API: + +{api_response} + +Summarize this response to answer the original question. + +Summary:`; +const API_RESPONSE_PROMPT_TEMPLATE = /* #__PURE__ */ new prompts_prompt.PromptTemplate({ + inputVariables: ["api_docs", "question", "api_url", "api_response"], + template: API_RESPONSE_RAW_PROMPT_TEMPLATE, +}); + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/api/api_chain.js + + + +/** + * Class that extends BaseChain and represents a chain specifically + * designed for making API requests and processing API responses. + */ +class APIChain extends base/* BaseChain */.l { + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "apiAnswerChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiRequestChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiDocs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "question" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + this.apiRequestChain = fields.apiRequestChain; + this.apiAnswerChain = fields.apiAnswerChain; + this.apiDocs = fields.apiDocs; + this.inputKey = fields.inputKey ?? this.inputKey; + this.outputKey = fields.outputKey ?? this.outputKey; + this.headers = fields.headers ?? this.headers; + } + /** @ignore */ + async _call(values, runManager) { + const question = values[this.inputKey]; + const api_url = await this.apiRequestChain.predict({ question, api_docs: this.apiDocs }, runManager?.getChild("request")); + const res = await fetch(api_url, { headers: this.headers }); + const api_response = await res.text(); + const answer = await this.apiAnswerChain.predict({ question, api_docs: this.apiDocs, api_url, api_response }, runManager?.getChild("response")); + return { [this.outputKey]: answer }; + } + _chainType() { + return "api_chain"; + } + static async deserialize(data) { + const { api_request_chain, api_answer_chain, api_docs } = data; + if (!api_request_chain) { + throw new Error("LLMChain must have api_request_chain"); + } + if (!api_answer_chain) { + throw new Error("LLMChain must have api_answer_chain"); + } + if (!api_docs) { + throw new Error("LLMChain must have api_docs"); + } + return new APIChain({ + apiAnswerChain: await llm_chain.LLMChain.deserialize(api_answer_chain), + apiRequestChain: await llm_chain.LLMChain.deserialize(api_request_chain), + apiDocs: api_docs, + }); + } + serialize() { + return { + _type: this._chainType(), + api_answer_chain: this.apiAnswerChain.serialize(), + api_request_chain: this.apiRequestChain.serialize(), + api_docs: this.apiDocs, + }; + } + /** + * Static method to create a new APIChain from a BaseLanguageModel and API + * documentation. + * @param llm BaseLanguageModel instance. + * @param apiDocs API documentation. + * @param options Optional configuration options for the APIChain. + * @returns New APIChain instance. + */ + static fromLLMAndAPIDocs(llm, apiDocs, options = {}) { + const { apiUrlPrompt = API_URL_PROMPT_TEMPLATE, apiResponsePrompt = API_RESPONSE_PROMPT_TEMPLATE, } = options; + const apiRequestChain = new llm_chain.LLMChain({ prompt: apiUrlPrompt, llm }); + const apiAnswerChain = new llm_chain.LLMChain({ prompt: apiResponsePrompt, llm }); + return new this({ + apiAnswerChain, + apiRequestChain, + apiDocs, + ...options, + }); + } +} + + +/***/ }), + +/***/ 7273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "LLMChain": () => (/* binding */ LLMChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules +var runnable = __webpack_require__(1972); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/output_parser.js + +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends runnable/* Runnable */.eq { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input) => this.parseResult([{ text: input }]), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input) => this.parseResult([{ message: input, text: input.content }]), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Class to parse the output of an LLM call that also allows streaming inputs. + */ +class BaseTransformOutputParser extends (/* unused pure expression or super */ null && (BaseOutputParser)) { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) { + if (typeof chunk === "string") { + yield this.parseResult([{ text: chunk }]); + } + else { + yield this.parseResult([{ message: chunk, text: chunk.content }]); + } + } + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser", + }); + } +} +/** + * OutputParser that parses LLMResult into the top likely string. + */ +class StringOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "StrOutputParser"; + } + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } +} +/** + * OutputParser that parses LLMResult into the top likely string and + * encodes it into bytes. + */ +class BytesOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "textEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: new TextEncoder() + }); + } + static lc_name() { + return "BytesOutputParser"; + } + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/output_parsers/noop.js + +/** + * The NoOpOutputParser class is a type of output parser that does not + * perform any operations on the output. It extends the BaseOutputParser + * class and is part of the LangChain's output parsers module. This class + * is useful in scenarios where the raw output of the Large Language + * Models (LLMs) is required. + */ +class NoOpOutputParser extends BaseOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "output_parsers", "default"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "NoOpOutputParser"; + } + /** + * This method takes a string as input and returns the same string as + * output. It does not perform any operations on the input string. + * @param text The input string to be parsed. + * @returns The same input string without any operations performed on it. + */ + parse(text) { + return Promise.resolve(text); + } + /** + * This method returns an empty string. It does not provide any formatting + * instructions. + * @returns An empty string, indicating no formatting instructions. + */ + getFormatInstructions() { + return ""; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + + + + +/** + * Chain to run queries against LLMs. + * + * @example + * ```ts + * import { LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); + * const llm = new LLMChain({ llm: new OpenAI(), prompt }); + * ``` + */ +class LLMChain extends base/* BaseChain */.l { + static lc_name() { + return "LLMChain"; + } + get inputKeys() { + return this.prompt.inputVariables; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llmKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "text" + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + this.llm = fields.llm; + this.llmKwargs = fields.llmKwargs; + this.outputKey = fields.outputKey ?? this.outputKey; + this.outputParser = + fields.outputParser ?? new NoOpOutputParser(); + if (this.prompt.outputParser) { + if (fields.outputParser) { + throw new Error("Cannot set both outputParser and prompt.outputParser"); + } + this.outputParser = this.prompt.outputParser; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = super._selectMemoryInputs(values); + for (const key of this.llm.callKeys) { + if (key in values) { + delete valuesForMemory[key]; + } + } + return valuesForMemory; + } + /** @ignore */ + async _getFinalOutput(generations, promptValue, runManager) { + let finalCompletion; + if (this.outputParser) { + finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + } + else { + finalCompletion = generations[0].text; + } + return finalCompletion; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + call(values, config) { + return super.call(values, config); + } + /** @ignore */ + async _call(values, runManager) { + const valuesForPrompt = { ...values }; + const valuesForLLM = { + ...this.llmKwargs, + }; + for (const key of this.llm.callKeys) { + if (key in values) { + valuesForLLM[key] = values[key]; + delete valuesForPrompt[key]; + } + } + const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); + const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); + return { + [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), + }; + } + /** + * Format prompt with values and pass to LLM + * + * @param values - keys to pass to prompt template + * @param callbackManager - CallbackManager to use + * @returns Completion from LLM. + * + * @example + * ```ts + * llm.predict({ adjective: "funny" }) + * ``` + */ + async predict(values, callbackManager) { + const output = await this.call(values, callbackManager); + return output[this.outputKey]; + } + _chainType() { + return "llm"; + } + static async deserialize(data) { + const { llm, prompt } = data; + if (!llm) { + throw new Error("LLMChain must have llm"); + } + if (!prompt) { + throw new Error("LLMChain must have prompt"); + } + return new LLMChain({ + llm: await base_language/* BaseLanguageModel.deserialize */.qV.deserialize(llm), + prompt: await prompts_base/* BasePromptTemplate.deserialize */.dy.deserialize(prompt), + }); + } + /** @deprecated */ + serialize() { + return { + _type: `${this._chainType()}_chain`, + llm: this.llm.serialize(), + prompt: this.prompt.serialize(), + }; + } +} + + +/***/ }) + +}; diff --git a/dist/197.index.js b/dist/197.index.js new file mode 100644 index 0000000..086fdc5 --- /dev/null +++ b/dist/197.index.js @@ -0,0 +1,192 @@ +export const id = 197; +export const ids = [197]; +export const modules = { + +/***/ 3197: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "l": () => (/* binding */ BaseChain) +/* harmony export */ }); +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6009); +/* harmony import */ var _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7679); + + + +/** + * Base interface that all chains must implement. + */ +class BaseChain extends _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__/* .BaseLangChain */ .BD { + get lc_namespace() { + return ["langchain", "chains", this._chainType()]; + } + constructor(fields, + /** @deprecated */ + verbose, + /** @deprecated */ + callbacks) { + if (arguments.length === 1 && + typeof fields === "object" && + !("saveContext" in fields)) { + // fields is not a BaseMemory + const { memory, callbackManager, ...rest } = fields; + super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); + this.memory = memory; + } + else { + // fields is a BaseMemory + super({ verbose, callbacks }); + this.memory = fields; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = { ...values }; + if ("signal" in valuesForMemory) { + delete valuesForMemory.signal; + } + if ("timeout" in valuesForMemory) { + delete valuesForMemory.timeout; + } + return valuesForMemory; + } + /** + * Invoke the chain with the provided input and returns the output. + * @param input Input values for the chain run. + * @param config Optional configuration for the Runnable. + * @returns Promise that resolves with the output of the chain run. + */ + async invoke(input, config) { + return this.call(input, config); + } + /** + * Return a json-like object representing this chain. + */ + serialize() { + throw new Error("Method not implemented."); + } + async run( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, config) { + const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); + const isKeylessInput = inputKeys.length <= 1; + if (!isKeylessInput) { + throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; + const returnValues = await this.call(values, config); + const keys = Object.keys(returnValues); + if (keys.length === 1) { + return returnValues[keys[0]]; + } + throw new Error("return values have multiple keys, `run` only supported when one key currently"); + } + async _formatValues(values) { + const fullValues = { ...values }; + if (fullValues.timeout && !fullValues.signal) { + fullValues.signal = AbortSignal.timeout(fullValues.timeout); + delete fullValues.timeout; + } + if (!(this.memory == null)) { + const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); + for (const [key, value] of Object.entries(newValues)) { + fullValues[key] = value; + } + } + return fullValues; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + async call(values, config, + /** @deprecated */ + tags) { + const fullValues = await this._formatValues(values); + const parsedConfig = (0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .parseCallbackConfigArg */ .QH)(config); + const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .CallbackManager.configure */ .Ye.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); + let outputValues; + try { + outputValues = await (values.signal + ? Promise.race([ + this._call(fullValues, runManager), + new Promise((_, reject) => { + values.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]) + : this._call(fullValues, runManager)); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + if (!(this.memory == null)) { + await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + } + await runManager?.handleChainEnd(outputValues); + // add the runManager's currentRunId to the outputValues + Object.defineProperty(outputValues, _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .RUN_KEY */ .WH, { + value: runManager ? { runId: runManager?.runId } : undefined, + configurable: true, + }); + return outputValues; + } + /** + * Call the chain on all inputs in the list + */ + async apply(inputs, config) { + return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + } + /** + * Load a chain from a json-like object describing it. + */ + static async deserialize(data, values = {}) { + switch (data._type) { + case "llm_chain": { + const { LLMChain } = await __webpack_require__.e(/* import() */ 273).then(__webpack_require__.bind(__webpack_require__, 7273)); + return LLMChain.deserialize(data); + } + case "sequential_chain": { + const { SequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SequentialChain.deserialize(data); + } + case "simple_sequential_chain": { + const { SimpleSequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SimpleSequentialChain.deserialize(data); + } + case "stuff_documents_chain": { + const { StuffDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return StuffDocumentsChain.deserialize(data); + } + case "map_reduce_documents_chain": { + const { MapReduceDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return MapReduceDocumentsChain.deserialize(data); + } + case "refine_documents_chain": { + const { RefineDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return RefineDocumentsChain.deserialize(data); + } + case "vector_db_qa": { + const { VectorDBQAChain } = await Promise.all(/* import() */[__webpack_require__.e(608), __webpack_require__.e(214)]).then(__webpack_require__.bind(__webpack_require__, 5214)); + return VectorDBQAChain.deserialize(data, values); + } + case "api_chain": { + const { APIChain } = await __webpack_require__.e(/* import() */ 159).then(__webpack_require__.bind(__webpack_require__, 6159)); + return APIChain.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } +} + + +/***/ }) + +}; diff --git a/dist/210.index.js b/dist/210.index.js new file mode 100644 index 0000000..c65597a --- /dev/null +++ b/dist/210.index.js @@ -0,0 +1,331 @@ +export const id = 210; +export const ids = [210]; +export const modules = { + +/***/ 7210: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "SequentialChain": () => (/* binding */ SequentialChain), + "SimpleSequentialChain": () => (/* binding */ SimpleSequentialChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/set.js +/** + * Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#implementing_basic_set_operations + */ +/** + * returns intersection of two sets + */ +function intersection(setA, setB) { + const _intersection = new Set(); + for (const elem of setB) { + if (setA.has(elem)) { + _intersection.add(elem); + } + } + return _intersection; +} +/** + * returns union of two sets + */ +function union(setA, setB) { + const _union = new Set(setA); + for (const elem of setB) { + _union.add(elem); + } + return _union; +} +/** + * returns difference of two sets + */ +function difference(setA, setB) { + const _difference = new Set(setA); + for (const elem of setB) { + _difference.delete(elem); + } + return _difference; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/sequential_chain.js + + +function formatSet(input) { + return Array.from(input) + .map((i) => `"${i}"`) + .join(", "); +} +/** + * Chain where the outputs of one chain feed directly into next. + */ +class SequentialChain extends base/* BaseChain */.l { + static lc_name() { + return "SequentialChain"; + } + get inputKeys() { + return this.inputVariables; + } + get outputKeys() { + return this.outputVariables; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "chains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnAll", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chains = fields.chains; + this.inputVariables = fields.inputVariables; + this.outputVariables = fields.outputVariables ?? []; + if (this.outputVariables.length > 0 && fields.returnAll) { + throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."); + } + this.returnAll = fields.returnAll ?? false; + this._validateChains(); + } + /** @ignore */ + _validateChains() { + if (this.chains.length === 0) { + throw new Error("Sequential chain must have at least one chain."); + } + const memoryKeys = this.memory?.memoryKeys ?? []; + const inputKeysSet = new Set(this.inputKeys); + const memoryKeysSet = new Set(memoryKeys); + const keysIntersection = intersection(inputKeysSet, memoryKeysSet); + if (keysIntersection.size > 0) { + throw new Error(`The following keys: ${formatSet(keysIntersection)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`); + } + const availableKeys = union(inputKeysSet, memoryKeysSet); + for (const chain of this.chains) { + let missingKeys = difference(new Set(chain.inputKeys), availableKeys); + if (chain.memory) { + missingKeys = difference(missingKeys, new Set(chain.memory.memoryKeys)); + } + if (missingKeys.size > 0) { + throw new Error(`Missing variables for chain "${chain._chainType()}": ${formatSet(missingKeys)}. Only got the following variables: ${formatSet(availableKeys)}.`); + } + const outputKeysSet = new Set(chain.outputKeys); + const overlappingOutputKeys = intersection(availableKeys, outputKeysSet); + if (overlappingOutputKeys.size > 0) { + throw new Error(`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(overlappingOutputKeys)}. This can lead to unexpected behaviour.`); + } + for (const outputKey of outputKeysSet) { + availableKeys.add(outputKey); + } + } + if (this.outputVariables.length === 0) { + if (this.returnAll) { + const outputKeys = difference(availableKeys, inputKeysSet); + this.outputVariables = Array.from(outputKeys); + } + else { + this.outputVariables = this.chains[this.chains.length - 1].outputKeys; + } + } + else { + const missingKeys = difference(new Set(this.outputVariables), new Set(availableKeys)); + if (missingKeys.size > 0) { + throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${formatSet(missingKeys)}.`); + } + } + } + /** @ignore */ + async _call(values, runManager) { + let input = {}; + const allChainValues = values; + let i = 0; + for (const chain of this.chains) { + i += 1; + input = await chain.call(allChainValues, runManager?.getChild(`step_${i}`)); + for (const key of Object.keys(input)) { + allChainValues[key] = input[key]; + } + } + const output = {}; + for (const key of this.outputVariables) { + output[key] = allChainValues[key]; + } + return output; + } + _chainType() { + return "sequential_chain"; + } + static async deserialize(data) { + const chains = []; + const inputVariables = data.input_variables; + const outputVariables = data.output_variables; + const serializedChains = data.chains; + for (const serializedChain of serializedChains) { + const deserializedChain = await base/* BaseChain.deserialize */.l.deserialize(serializedChain); + chains.push(deserializedChain); + } + return new SequentialChain({ chains, inputVariables, outputVariables }); + } + serialize() { + const chains = []; + for (const chain of this.chains) { + chains.push(chain.serialize()); + } + return { + _type: this._chainType(), + input_variables: this.inputVariables, + output_variables: this.outputVariables, + chains, + }; + } +} +/** + * Simple chain where a single string output of one chain is fed directly into the next. + * @augments BaseChain + * @augments SimpleSequentialChainInput + * + * @example + * ```ts + * import { SimpleSequentialChain, LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * // This is an LLMChain to write a synopsis given a title of a play. + * const llm = new OpenAI({ temperature: 0 }); + * const template = `You are a playwright. Given the title of play, it is your job to write a synopsis for that title. + * + * Title: {title} + * Playwright: This is a synopsis for the above play:` + * const promptTemplate = new PromptTemplate({ template, inputVariables: ["title"] }); + * const synopsisChain = new LLMChain({ llm, prompt: promptTemplate }); + * + * + * // This is an LLMChain to write a review of a play given a synopsis. + * const reviewLLM = new OpenAI({ temperature: 0 }) + * const reviewTemplate = `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. + * + * Play Synopsis: + * {synopsis} + * Review from a New York Times play critic of the above play:` + * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] }); + * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate }); + * + * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true}) + * const review = await overallChain.run("Tragedy at sunset on the beach") + * // the variable review contains resulting play review. + * ``` + */ +class SimpleSequentialChain extends base/* BaseChain */.l { + static lc_name() { + return "SimpleSequentialChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "chains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + Object.defineProperty(this, "trimOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chains = fields.chains; + this.trimOutputs = fields.trimOutputs ?? false; + this._validateChains(); + } + /** @ignore */ + _validateChains() { + for (const chain of this.chains) { + if (chain.inputKeys.filter((k) => !chain.memory?.memoryKeys.includes(k) ?? true).length !== 1) { + throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${chain.inputKeys.length} for ${chain._chainType()}.`); + } + if (chain.outputKeys.length !== 1) { + throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${chain.outputKeys.length} for ${chain._chainType()}.`); + } + } + } + /** @ignore */ + async _call(values, runManager) { + let input = values[this.inputKey]; + let i = 0; + for (const chain of this.chains) { + i += 1; + input = (await chain.call({ [chain.inputKeys[0]]: input, signal: values.signal }, runManager?.getChild(`step_${i}`)))[chain.outputKeys[0]]; + if (this.trimOutputs) { + input = input.trim(); + } + await runManager?.handleText(input); + } + return { [this.outputKey]: input }; + } + _chainType() { + return "simple_sequential_chain"; + } + static async deserialize(data) { + const chains = []; + const serializedChains = data.chains; + for (const serializedChain of serializedChains) { + const deserializedChain = await base/* BaseChain.deserialize */.l.deserialize(serializedChain); + chains.push(deserializedChain); + } + return new SimpleSequentialChain({ chains }); + } + serialize() { + const chains = []; + for (const chain of this.chains) { + chains.push(chain.serialize()); + } + return { + _type: this._chainType(), + chains, + }; + } +} + + +/***/ }) + +}; diff --git a/dist/214.index.js b/dist/214.index.js new file mode 100644 index 0000000..acb9008 --- /dev/null +++ b/dist/214.index.js @@ -0,0 +1,969 @@ +export const id = 214; +export const ids = [214,609,806]; +export const modules = { + +/***/ 5214: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "VectorDBQAChain": () => (/* binding */ VectorDBQAChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 2 modules +var llm_chain = __webpack_require__(7273); +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/combine_docs_chain.js +var combine_docs_chain = __webpack_require__(3608); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js +var prompts_prompt = __webpack_require__(4095); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/chat.js +var chat = __webpack_require__(6704); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/conditional.js +/** + * Abstract class that defines the interface for selecting a prompt for a + * given language model. + */ +class BasePromptSelector { + /** + * Asynchronous version of `getPrompt` that also accepts an options object + * for partial variables. + * @param llm The language model for which to get a prompt. + * @param options Optional object for partial variables. + * @returns A Promise that resolves to a prompt template. + */ + async getPromptAsync(llm, options) { + const prompt = this.getPrompt(llm); + return prompt.partial(options?.partialVariables ?? {}); + } +} +/** + * Concrete implementation of `BasePromptSelector` that selects a prompt + * based on a set of conditions. It has a default prompt that it returns + * if none of the conditions are met. + */ +class ConditionalPromptSelector extends BasePromptSelector { + constructor(default_prompt, conditionals = []) { + super(); + Object.defineProperty(this, "defaultPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "conditionals", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.defaultPrompt = default_prompt; + this.conditionals = conditionals; + } + /** + * Method that selects a prompt based on a set of conditions. If none of + * the conditions are met, it returns the default prompt. + * @param llm The language model for which to get a prompt. + * @returns A prompt template. + */ + getPrompt(llm) { + for (const [condition, prompt] of this.conditionals) { + if (condition(llm)) { + return prompt; + } + } + return this.defaultPrompt; + } +} +/** + * Type guard function that checks if a given language model is of type + * `BaseLLM`. + */ +function isLLM(llm) { + return llm._modelType() === "base_llm"; +} +/** + * Type guard function that checks if a given language model is of type + * `BaseChatModel`. + */ +function isChatModel(llm) { + return llm._modelType() === "base_chat_model"; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/stuff_prompts.js +/* eslint-disable spaced-comment */ + + + +const DEFAULT_QA_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ + template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", + inputVariables: ["context", "question"], +}); +const system_template = `Use the following pieces of context to answer the users question. +If you don't know the answer, just say that you don't know, don't try to make up an answer. +---------------- +{context}`; +const messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(system_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_PROMPT = /*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(messages); +const QA_PROMPT_SELECTOR = /*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_QA_PROMPT, [[isChatModel, CHAT_PROMPT]]); + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js +/* eslint-disable spaced-comment */ + + + +const qa_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. +Return any relevant text verbatim. +{context} +Question: {question} +Relevant text, if any:`; +const DEFAULT_COMBINE_QA_PROMPT = +/*#__PURE__*/ +prompts_prompt.PromptTemplate.fromTemplate(qa_template); +const map_reduce_prompts_system_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. +Return any relevant text verbatim. +---------------- +{context}`; +const map_reduce_prompts_messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(map_reduce_prompts_system_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_QA_PROMPT = /*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(map_reduce_prompts_messages); +const map_reduce_prompts_COMBINE_QA_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_COMBINE_QA_PROMPT, [ + [isChatModel, CHAT_QA_PROMPT], +]); +const combine_prompt = `Given the following extracted parts of a long document and a question, create a final answer. +If you don't know the answer, just say that you don't know. Don't try to make up an answer. + +QUESTION: Which state/country's law governs the interpretation of the contract? +========= +Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. + +Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties.\n\n11.9 No Third-Party Beneficiaries. + +Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, +========= +FINAL ANSWER: This Agreement is governed by English law. + +QUESTION: What did the president say about Michael Jackson? +========= +Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. + +Content: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. + +Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay. + +Content: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation. +========= +FINAL ANSWER: The president did not mention Michael Jackson. + +QUESTION: {question} +========= +{summaries} +========= +FINAL ANSWER:`; +const COMBINE_PROMPT = +/*#__PURE__*/ prompts_prompt.PromptTemplate.fromTemplate(combine_prompt); +const system_combine_template = `Given the following extracted parts of a long document and a question, create a final answer. +If you don't know the answer, just say that you don't know. Don't try to make up an answer. +---------------- +{summaries}`; +const combine_messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(system_combine_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_COMBINE_PROMPT = +/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(combine_messages); +const map_reduce_prompts_COMBINE_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(COMBINE_PROMPT, [ + [isChatModel, CHAT_COMBINE_PROMPT], +]); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/LengthBasedExampleSelector.js + +/** + * Calculates the length of a text based on the number of words and lines. + */ +function getLengthBased(text) { + return text.split(/\n| /).length; +} +/** + * A specialized example selector that selects examples based on their + * length, ensuring that the total length of the selected examples does + * not exceed a specified maximum length. + */ +class LengthBasedExampleSelector extends (/* unused pure expression or super */ null && (BaseExampleSelector)) { + constructor(data) { + super(data); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "getTextLength", { + enumerable: true, + configurable: true, + writable: true, + value: getLengthBased + }); + Object.defineProperty(this, "maxLength", { + enumerable: true, + configurable: true, + writable: true, + value: 2048 + }); + Object.defineProperty(this, "exampleTextLengths", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + this.examplePrompt = data.examplePrompt; + this.maxLength = data.maxLength ?? 2048; + this.getTextLength = data.getTextLength ?? getLengthBased; + } + /** + * Adds an example to the list of examples and calculates its length. + * @param example The example to be added. + * @returns Promise that resolves when the example has been added and its length calculated. + */ + async addExample(example) { + this.examples.push(example); + const stringExample = await this.examplePrompt.format(example); + this.exampleTextLengths.push(this.getTextLength(stringExample)); + } + /** + * Calculates the lengths of the examples. + * @param v Array of lengths of the examples. + * @param values Instance of LengthBasedExampleSelector. + * @returns Promise that resolves with an array of lengths of the examples. + */ + async calculateExampleTextLengths(v, values) { + if (v.length > 0) { + return v; + } + const { examples, examplePrompt } = values; + const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); + return stringExamples.map((eg) => this.getTextLength(eg)); + } + /** + * Selects examples until the total length of the selected examples + * reaches the maxLength. + * @param inputVariables The input variables for the examples. + * @returns Promise that resolves with an array of selected examples. + */ + async selectExamples(inputVariables) { + const inputs = Object.values(inputVariables).join(" "); + let remainingLength = this.maxLength - this.getTextLength(inputs); + let i = 0; + const examples = []; + while (remainingLength > 0 && i < this.examples.length) { + const newLength = remainingLength - this.exampleTextLengths[i]; + if (newLength < 0) { + break; + } + else { + examples.push(this.examples[i]); + remainingLength = newLength; + } + i += 1; + } + return examples; + } + /** + * Creates a new instance of LengthBasedExampleSelector and adds a list of + * examples to it. + * @param examples Array of examples to be added. + * @param args Input parameters for the LengthBasedExampleSelector. + * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. + */ + static async fromExamples(examples, args) { + const selector = new LengthBasedExampleSelector(args); + await Promise.all(examples.map((eg) => selector.addExample(eg))); + return selector; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/SemanticSimilarityExampleSelector.js + + +function sortedValues(values) { + return Object.keys(values) + .sort() + .map((key) => values[key]); +} +/** + * Class that selects examples based on semantic similarity. It extends + * the BaseExampleSelector class. + */ +class SemanticSimilarityExampleSelector extends (/* unused pure expression or super */ null && (BaseExampleSelector)) { + constructor(data) { + super(data); + Object.defineProperty(this, "vectorStore", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "k", { + enumerable: true, + configurable: true, + writable: true, + value: 4 + }); + Object.defineProperty(this, "exampleKeys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKeys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.vectorStore = data.vectorStore; + this.k = data.k ?? 4; + this.exampleKeys = data.exampleKeys; + this.inputKeys = data.inputKeys; + } + /** + * Method that adds a new example to the vectorStore. The example is + * converted to a string and added to the vectorStore as a document. + * @param example The example to be added to the vectorStore. + * @returns Promise that resolves when the example has been added to the vectorStore. + */ + async addExample(example) { + const inputKeys = this.inputKeys ?? Object.keys(example); + const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" "); + await this.vectorStore.addDocuments([ + new Document({ + pageContent: stringExample, + metadata: { example }, + }), + ]); + } + /** + * Method that selects which examples to use based on semantic similarity. + * It performs a similarity search in the vectorStore using the input + * variables and returns the examples with the highest similarity. + * @param inputVariables The input variables used for the similarity search. + * @returns Promise that resolves with an array of the selected examples. + */ + async selectExamples(inputVariables) { + const inputKeys = this.inputKeys ?? Object.keys(inputVariables); + const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" "); + const exampleDocs = await this.vectorStore.similaritySearch(query, this.k); + const examples = exampleDocs.map((doc) => doc.metadata); + if (this.exampleKeys) { + // If example keys are provided, filter examples to those keys. + return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})); + } + return examples; + } + /** + * Static method that creates a new instance of + * SemanticSimilarityExampleSelector. It takes a list of examples, an + * instance of Embeddings, a VectorStore class, and an options object as + * parameters. It converts the examples to strings, creates a VectorStore + * from the strings and the embeddings, and returns a new + * SemanticSimilarityExampleSelector with the created VectorStore and the + * options provided. + * @param examples The list of examples to be used. + * @param embeddings The instance of Embeddings to be used. + * @param vectorStoreCls The VectorStore class to be used. + * @param options The options object for the SemanticSimilarityExampleSelector. + * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. + */ + static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { + const inputKeys = options.inputKeys ?? null; + const stringExamples = examples.map((example) => sortedValues(inputKeys + ? inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {}) + : example).join(" ")); + const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, // metadatas + embeddings, options); + return new SemanticSimilarityExampleSelector({ + vectorStore, + k: options.k ?? 4, + exampleKeys: options.exampleKeys, + inputKeys: options.inputKeys, + }); + } +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/few_shot.js +var few_shot = __webpack_require__(609); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/template.js +var template = __webpack_require__(837); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/pipeline.js + + +/** + * Class that handles a sequence of prompts, each of which may require + * different input variables. Includes methods for formatting these + * prompts, extracting required input values, and handling partial + * prompts. + */ +class PipelinePromptTemplate extends (/* unused pure expression or super */ null && (BasePromptTemplate)) { + static lc_name() { + return "PipelinePromptTemplate"; + } + constructor(input) { + super({ ...input, inputVariables: [] }); + Object.defineProperty(this, "pipelinePrompts", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "finalPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.pipelinePrompts = input.pipelinePrompts; + this.finalPrompt = input.finalPrompt; + this.inputVariables = this.computeInputValues(); + } + /** + * Computes the input values required by the pipeline prompts. + * @returns Array of input values required by the pipeline prompts. + */ + computeInputValues() { + const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); + const inputValues = this.pipelinePrompts + .map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))) + .flat(); + return [...new Set(inputValues)]; + } + static extractRequiredInputValues(allValues, requiredValueNames) { + return requiredValueNames.reduce((requiredValues, valueName) => { + // eslint-disable-next-line no-param-reassign + requiredValues[valueName] = allValues[valueName]; + return requiredValues; + }, {}); + } + /** + * Formats the pipeline prompts based on the provided input values. + * @param values Input values to format the pipeline prompts. + * @returns Promise that resolves with the formatted input values. + */ + async formatPipelinePrompts(values) { + const allValues = await this.mergePartialAndUserVariables(values); + for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this + .pipelinePrompts) { + const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); + // eslint-disable-next-line no-instanceof/no-instanceof + if (pipelinePrompt instanceof ChatPromptTemplate) { + allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); + } + else { + allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); + } + } + return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); + } + /** + * Formats the final prompt value based on the provided input values. + * @param values Input values to format the final prompt value. + * @returns Promise that resolves with the formatted final prompt value. + */ + async formatPromptValue(values) { + return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); + } + async format(values) { + return this.finalPrompt.format(await this.formatPipelinePrompts(values)); + } + /** + * Handles partial prompts, which are prompts that have been partially + * filled with input values. + * @param values Partial input values. + * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. + */ + async partial(values) { + const promptDict = { ...this }; + promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); + promptDict.partialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + return new PipelinePromptTemplate(promptDict); + } + serialize() { + throw new Error("Not implemented."); + } + _getPromptType() { + return "pipeline"; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/index.js + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/refine_prompts.js +/* eslint-disable spaced-comment */ + + +const DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question} +We have provided an existing answer: {existing_answer} +We have the opportunity to refine the existing answer +(only if needed) with some more context below. +------------ +{context} +------------ +Given the new context, refine the original answer to better answer the question. +If the context isn't useful, return the original answer.`; +const DEFAULT_REFINE_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ + inputVariables: ["question", "existing_answer", "context"], + template: DEFAULT_REFINE_PROMPT_TMPL, +}); +const refineTemplate = `The original question is as follows: {question} +We have provided an existing answer: {existing_answer} +We have the opportunity to refine the existing answer +(only if needed) with some more context below. +------------ +{context} +------------ +Given the new context, refine the original answer to better answer the question. +If the context isn't useful, return the original answer.`; +const refine_prompts_messages = [ + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), + /*#__PURE__*/ chat/* AIMessagePromptTemplate.fromTemplate */.gc.fromTemplate("{existing_answer}"), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate(refineTemplate), +]; +const CHAT_REFINE_PROMPT = +/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(refine_prompts_messages); +const refine_prompts_REFINE_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_REFINE_PROMPT, [ + [isChatModel, CHAT_REFINE_PROMPT], +]); +const DEFAULT_TEXT_QA_PROMPT_TMPL = `Context information is below. +--------------------- +{context} +--------------------- +Given the context information and no prior knowledge, answer the question: {question}`; +const DEFAULT_TEXT_QA_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ + inputVariables: ["context", "question"], + template: DEFAULT_TEXT_QA_PROMPT_TMPL, +}); +const chat_qa_prompt_template = `Context information is below. +--------------------- +{context} +--------------------- +Given the context information and no prior knowledge, answer any questions`; +const chat_messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(chat_qa_prompt_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_QUESTION_PROMPT = +/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(chat_messages); +const refine_prompts_QUESTION_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_TEXT_QA_PROMPT, [ + [isChatModel, CHAT_QUESTION_PROMPT], +]); + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/load.js + + + + + +const loadQAChain = (llm, params = { type: "stuff" }) => { + const { type } = params; + if (type === "stuff") { + return loadQAStuffChain(llm, params); + } + if (type === "map_reduce") { + return loadQAMapReduceChain(llm, params); + } + if (type === "refine") { + return loadQARefineChain(llm, params); + } + throw new Error(`Invalid _type: ${type}`); +}; +/** + * Loads a StuffQAChain based on the provided parameters. It takes an LLM + * instance and StuffQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a StuffQAChain. + * @returns A StuffQAChain instance. + */ +function loadQAStuffChain(llm, params = {}) { + const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; + const llmChain = new llm_chain.LLMChain({ prompt, llm, verbose }); + const chain = new combine_docs_chain.StuffDocumentsChain({ llmChain, verbose }); + return chain; +} +/** + * Loads a MapReduceQAChain based on the provided parameters. It takes an + * LLM instance and MapReduceQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a MapReduceQAChain. + * @returns A MapReduceQAChain instance. + */ +function loadQAMapReduceChain(llm, params = {}) { + const { combineMapPrompt = COMBINE_QA_PROMPT_SELECTOR.getPrompt(llm), combinePrompt = COMBINE_PROMPT_SELECTOR.getPrompt(llm), verbose, combineLLM, returnIntermediateSteps, } = params; + const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose }); + const combineLLMChain = new LLMChain({ + prompt: combinePrompt, + llm: combineLLM ?? llm, + verbose, + }); + const combineDocumentChain = new StuffDocumentsChain({ + llmChain: combineLLMChain, + documentVariableName: "summaries", + verbose, + }); + const chain = new MapReduceDocumentsChain({ + llmChain, + combineDocumentChain, + returnIntermediateSteps, + verbose, + }); + return chain; +} +/** + * Loads a RefineQAChain based on the provided parameters. It takes an LLM + * instance and RefineQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a RefineQAChain. + * @returns A RefineQAChain instance. + */ +function loadQARefineChain(llm, params = {}) { + const { questionPrompt = QUESTION_PROMPT_SELECTOR.getPrompt(llm), refinePrompt = REFINE_PROMPT_SELECTOR.getPrompt(llm), refineLLM, verbose, } = params; + const llmChain = new LLMChain({ prompt: questionPrompt, llm, verbose }); + const refineLLMChain = new LLMChain({ + prompt: refinePrompt, + llm: refineLLM ?? llm, + verbose, + }); + const chain = new RefineDocumentsChain({ + llmChain, + refineLLMChain, + verbose, + }); + return chain; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/vector_db_qa.js + + +/** + * Class that represents a VectorDBQAChain. It extends the `BaseChain` + * class and implements the `VectorDBQAChainInput` interface. It performs + * a similarity search using a vector store and combines the search + * results using a specified combine documents chain. + */ +class VectorDBQAChain extends base/* BaseChain */.l { + static lc_name() { + return "VectorDBQAChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "k", { + enumerable: true, + configurable: true, + writable: true, + value: 4 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "query" + }); + Object.defineProperty(this, "vectorstore", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnSourceDocuments", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.vectorstore = fields.vectorstore; + this.combineDocumentsChain = fields.combineDocumentsChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.k = fields.k ?? this.k; + this.returnSourceDocuments = + fields.returnSourceDocuments ?? this.returnSourceDocuments; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Question key ${this.inputKey} not found.`); + } + const question = values[this.inputKey]; + const docs = await this.vectorstore.similaritySearch(question, this.k, values.filter, runManager?.getChild("vectorstore")); + const inputs = { question, input_documents: docs }; + const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); + if (this.returnSourceDocuments) { + return { + ...result, + sourceDocuments: docs, + }; + } + return result; + } + _chainType() { + return "vector_db_qa"; + } + static async deserialize(data, values) { + if (!("vectorstore" in values)) { + throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); + } + const { vectorstore } = values; + if (!data.combine_documents_chain) { + throw new Error(`VectorDBQAChain must have combine_documents_chain in serialized data`); + } + return new VectorDBQAChain({ + combineDocumentsChain: await base/* BaseChain.deserialize */.l.deserialize(data.combine_documents_chain), + k: data.k, + vectorstore, + }); + } + serialize() { + return { + _type: this._chainType(), + combine_documents_chain: this.combineDocumentsChain.serialize(), + k: this.k, + }; + } + /** + * Static method that creates a VectorDBQAChain instance from a + * BaseLanguageModel and a vector store. It also accepts optional options + * to customize the chain. + * @param llm The BaseLanguageModel instance. + * @param vectorstore The vector store used for similarity search. + * @param options Optional options to customize the chain. + * @returns A new instance of VectorDBQAChain. + */ + static fromLLM(llm, vectorstore, options) { + const qaChain = loadQAStuffChain(llm); + return new this({ + vectorstore, + combineDocumentsChain: qaChain, + ...options, + }); + } +} + + +/***/ }), + +/***/ 609: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FewShotPromptTemplate": () => (/* binding */ FewShotPromptTemplate) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5411); +/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(837); +/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4095); + + + +/** + * Prompt template that contains few-shot examples. + * @augments BasePromptTemplate + * @augments FewShotPromptTemplateInput + */ +class FewShotPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleSelector", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "suffix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "exampleSeparator", { + enumerable: true, + configurable: true, + writable: true, + value: "\n\n" + }); + Object.defineProperty(this, "prefix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.examples !== undefined && this.exampleSelector !== undefined) { + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + } + if (this.examples === undefined && this.exampleSelector === undefined) { + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "few_shot"; + } + async getExamples(inputVariables) { + if (this.examples !== undefined) { + return this.examples; + } + if (this.exampleSelector !== undefined) { + return this.exampleSelector.selectExamples(inputVariables); + } + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables, + }; + return new FewShotPromptTemplate(promptDict); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); + return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(template, this.templateFormat, allValues); + } + serialize() { + if (this.exampleSelector || !this.examples) { + throw new Error("Serializing an example selector is not currently supported"); + } + if (this.outputParser !== undefined) { + throw new Error("Serializing an output parser is not currently supported"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples, + }; + } + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) { + throw new Error("Missing example prompt"); + } + const examplePrompt = await _prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) { + examples = data.examples; + } + else { + throw new Error("Invalid examples format. Only list or string are supported."); + } + return new FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format, + }); + } +} + + +/***/ }) + +}; diff --git a/dist/231.index.js b/dist/231.index.js new file mode 100644 index 0000000..85d6e22 --- /dev/null +++ b/dist/231.index.js @@ -0,0 +1,518 @@ +export const id = 231; +export const ids = [231,197,210]; +export const modules = { + +/***/ 3197: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "l": () => (/* binding */ BaseChain) +/* harmony export */ }); +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6009); +/* harmony import */ var _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7679); + + + +/** + * Base interface that all chains must implement. + */ +class BaseChain extends _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__/* .BaseLangChain */ .BD { + get lc_namespace() { + return ["langchain", "chains", this._chainType()]; + } + constructor(fields, + /** @deprecated */ + verbose, + /** @deprecated */ + callbacks) { + if (arguments.length === 1 && + typeof fields === "object" && + !("saveContext" in fields)) { + // fields is not a BaseMemory + const { memory, callbackManager, ...rest } = fields; + super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); + this.memory = memory; + } + else { + // fields is a BaseMemory + super({ verbose, callbacks }); + this.memory = fields; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = { ...values }; + if ("signal" in valuesForMemory) { + delete valuesForMemory.signal; + } + if ("timeout" in valuesForMemory) { + delete valuesForMemory.timeout; + } + return valuesForMemory; + } + /** + * Invoke the chain with the provided input and returns the output. + * @param input Input values for the chain run. + * @param config Optional configuration for the Runnable. + * @returns Promise that resolves with the output of the chain run. + */ + async invoke(input, config) { + return this.call(input, config); + } + /** + * Return a json-like object representing this chain. + */ + serialize() { + throw new Error("Method not implemented."); + } + async run( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, config) { + const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); + const isKeylessInput = inputKeys.length <= 1; + if (!isKeylessInput) { + throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; + const returnValues = await this.call(values, config); + const keys = Object.keys(returnValues); + if (keys.length === 1) { + return returnValues[keys[0]]; + } + throw new Error("return values have multiple keys, `run` only supported when one key currently"); + } + async _formatValues(values) { + const fullValues = { ...values }; + if (fullValues.timeout && !fullValues.signal) { + fullValues.signal = AbortSignal.timeout(fullValues.timeout); + delete fullValues.timeout; + } + if (!(this.memory == null)) { + const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); + for (const [key, value] of Object.entries(newValues)) { + fullValues[key] = value; + } + } + return fullValues; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + async call(values, config, + /** @deprecated */ + tags) { + const fullValues = await this._formatValues(values); + const parsedConfig = (0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .parseCallbackConfigArg */ .QH)(config); + const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .CallbackManager.configure */ .Ye.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); + let outputValues; + try { + outputValues = await (values.signal + ? Promise.race([ + this._call(fullValues, runManager), + new Promise((_, reject) => { + values.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]) + : this._call(fullValues, runManager)); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + if (!(this.memory == null)) { + await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + } + await runManager?.handleChainEnd(outputValues); + // add the runManager's currentRunId to the outputValues + Object.defineProperty(outputValues, _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .RUN_KEY */ .WH, { + value: runManager ? { runId: runManager?.runId } : undefined, + configurable: true, + }); + return outputValues; + } + /** + * Call the chain on all inputs in the list + */ + async apply(inputs, config) { + return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + } + /** + * Load a chain from a json-like object describing it. + */ + static async deserialize(data, values = {}) { + switch (data._type) { + case "llm_chain": { + const { LLMChain } = await __webpack_require__.e(/* import() */ 273).then(__webpack_require__.bind(__webpack_require__, 7273)); + return LLMChain.deserialize(data); + } + case "sequential_chain": { + const { SequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SequentialChain.deserialize(data); + } + case "simple_sequential_chain": { + const { SimpleSequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SimpleSequentialChain.deserialize(data); + } + case "stuff_documents_chain": { + const { StuffDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return StuffDocumentsChain.deserialize(data); + } + case "map_reduce_documents_chain": { + const { MapReduceDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return MapReduceDocumentsChain.deserialize(data); + } + case "refine_documents_chain": { + const { RefineDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return RefineDocumentsChain.deserialize(data); + } + case "vector_db_qa": { + const { VectorDBQAChain } = await Promise.all(/* import() */[__webpack_require__.e(608), __webpack_require__.e(214)]).then(__webpack_require__.bind(__webpack_require__, 5214)); + return VectorDBQAChain.deserialize(data, values); + } + case "api_chain": { + const { APIChain } = await __webpack_require__.e(/* import() */ 159).then(__webpack_require__.bind(__webpack_require__, 6159)); + return APIChain.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } +} + + +/***/ }), + +/***/ 7210: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "SequentialChain": () => (/* binding */ SequentialChain), + "SimpleSequentialChain": () => (/* binding */ SimpleSequentialChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/set.js +/** + * Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#implementing_basic_set_operations + */ +/** + * returns intersection of two sets + */ +function intersection(setA, setB) { + const _intersection = new Set(); + for (const elem of setB) { + if (setA.has(elem)) { + _intersection.add(elem); + } + } + return _intersection; +} +/** + * returns union of two sets + */ +function union(setA, setB) { + const _union = new Set(setA); + for (const elem of setB) { + _union.add(elem); + } + return _union; +} +/** + * returns difference of two sets + */ +function difference(setA, setB) { + const _difference = new Set(setA); + for (const elem of setB) { + _difference.delete(elem); + } + return _difference; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/sequential_chain.js + + +function formatSet(input) { + return Array.from(input) + .map((i) => `"${i}"`) + .join(", "); +} +/** + * Chain where the outputs of one chain feed directly into next. + */ +class SequentialChain extends base/* BaseChain */.l { + static lc_name() { + return "SequentialChain"; + } + get inputKeys() { + return this.inputVariables; + } + get outputKeys() { + return this.outputVariables; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "chains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnAll", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chains = fields.chains; + this.inputVariables = fields.inputVariables; + this.outputVariables = fields.outputVariables ?? []; + if (this.outputVariables.length > 0 && fields.returnAll) { + throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."); + } + this.returnAll = fields.returnAll ?? false; + this._validateChains(); + } + /** @ignore */ + _validateChains() { + if (this.chains.length === 0) { + throw new Error("Sequential chain must have at least one chain."); + } + const memoryKeys = this.memory?.memoryKeys ?? []; + const inputKeysSet = new Set(this.inputKeys); + const memoryKeysSet = new Set(memoryKeys); + const keysIntersection = intersection(inputKeysSet, memoryKeysSet); + if (keysIntersection.size > 0) { + throw new Error(`The following keys: ${formatSet(keysIntersection)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`); + } + const availableKeys = union(inputKeysSet, memoryKeysSet); + for (const chain of this.chains) { + let missingKeys = difference(new Set(chain.inputKeys), availableKeys); + if (chain.memory) { + missingKeys = difference(missingKeys, new Set(chain.memory.memoryKeys)); + } + if (missingKeys.size > 0) { + throw new Error(`Missing variables for chain "${chain._chainType()}": ${formatSet(missingKeys)}. Only got the following variables: ${formatSet(availableKeys)}.`); + } + const outputKeysSet = new Set(chain.outputKeys); + const overlappingOutputKeys = intersection(availableKeys, outputKeysSet); + if (overlappingOutputKeys.size > 0) { + throw new Error(`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(overlappingOutputKeys)}. This can lead to unexpected behaviour.`); + } + for (const outputKey of outputKeysSet) { + availableKeys.add(outputKey); + } + } + if (this.outputVariables.length === 0) { + if (this.returnAll) { + const outputKeys = difference(availableKeys, inputKeysSet); + this.outputVariables = Array.from(outputKeys); + } + else { + this.outputVariables = this.chains[this.chains.length - 1].outputKeys; + } + } + else { + const missingKeys = difference(new Set(this.outputVariables), new Set(availableKeys)); + if (missingKeys.size > 0) { + throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${formatSet(missingKeys)}.`); + } + } + } + /** @ignore */ + async _call(values, runManager) { + let input = {}; + const allChainValues = values; + let i = 0; + for (const chain of this.chains) { + i += 1; + input = await chain.call(allChainValues, runManager?.getChild(`step_${i}`)); + for (const key of Object.keys(input)) { + allChainValues[key] = input[key]; + } + } + const output = {}; + for (const key of this.outputVariables) { + output[key] = allChainValues[key]; + } + return output; + } + _chainType() { + return "sequential_chain"; + } + static async deserialize(data) { + const chains = []; + const inputVariables = data.input_variables; + const outputVariables = data.output_variables; + const serializedChains = data.chains; + for (const serializedChain of serializedChains) { + const deserializedChain = await base/* BaseChain.deserialize */.l.deserialize(serializedChain); + chains.push(deserializedChain); + } + return new SequentialChain({ chains, inputVariables, outputVariables }); + } + serialize() { + const chains = []; + for (const chain of this.chains) { + chains.push(chain.serialize()); + } + return { + _type: this._chainType(), + input_variables: this.inputVariables, + output_variables: this.outputVariables, + chains, + }; + } +} +/** + * Simple chain where a single string output of one chain is fed directly into the next. + * @augments BaseChain + * @augments SimpleSequentialChainInput + * + * @example + * ```ts + * import { SimpleSequentialChain, LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * // This is an LLMChain to write a synopsis given a title of a play. + * const llm = new OpenAI({ temperature: 0 }); + * const template = `You are a playwright. Given the title of play, it is your job to write a synopsis for that title. + * + * Title: {title} + * Playwright: This is a synopsis for the above play:` + * const promptTemplate = new PromptTemplate({ template, inputVariables: ["title"] }); + * const synopsisChain = new LLMChain({ llm, prompt: promptTemplate }); + * + * + * // This is an LLMChain to write a review of a play given a synopsis. + * const reviewLLM = new OpenAI({ temperature: 0 }) + * const reviewTemplate = `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. + * + * Play Synopsis: + * {synopsis} + * Review from a New York Times play critic of the above play:` + * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] }); + * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate }); + * + * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true}) + * const review = await overallChain.run("Tragedy at sunset on the beach") + * // the variable review contains resulting play review. + * ``` + */ +class SimpleSequentialChain extends base/* BaseChain */.l { + static lc_name() { + return "SimpleSequentialChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "chains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + Object.defineProperty(this, "trimOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chains = fields.chains; + this.trimOutputs = fields.trimOutputs ?? false; + this._validateChains(); + } + /** @ignore */ + _validateChains() { + for (const chain of this.chains) { + if (chain.inputKeys.filter((k) => !chain.memory?.memoryKeys.includes(k) ?? true).length !== 1) { + throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${chain.inputKeys.length} for ${chain._chainType()}.`); + } + if (chain.outputKeys.length !== 1) { + throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${chain.outputKeys.length} for ${chain._chainType()}.`); + } + } + } + /** @ignore */ + async _call(values, runManager) { + let input = values[this.inputKey]; + let i = 0; + for (const chain of this.chains) { + i += 1; + input = (await chain.call({ [chain.inputKeys[0]]: input, signal: values.signal }, runManager?.getChild(`step_${i}`)))[chain.outputKeys[0]]; + if (this.trimOutputs) { + input = input.trim(); + } + await runManager?.handleText(input); + } + return { [this.outputKey]: input }; + } + _chainType() { + return "simple_sequential_chain"; + } + static async deserialize(data) { + const chains = []; + const serializedChains = data.chains; + for (const serializedChain of serializedChains) { + const deserializedChain = await base/* BaseChain.deserialize */.l.deserialize(serializedChain); + chains.push(deserializedChain); + } + return new SimpleSequentialChain({ chains }); + } + serialize() { + const chains = []; + for (const chain of this.chains) { + chains.push(chain.serialize()); + } + return { + _type: this._chainType(), + chains, + }; + } +} + + +/***/ }) + +}; diff --git a/dist/27.index.js b/dist/27.index.js new file mode 100644 index 0000000..67b422a --- /dev/null +++ b/dist/27.index.js @@ -0,0 +1,1034 @@ +export const id = 27; +export const ids = [27]; +export const modules = { + +/***/ 27: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "ChatOpenAI": () => (/* binding */ ChatOpenAI), + "PromptLayerChatOpenAI": () => (/* binding */ PromptLayerChatOpenAI) +}); + +// EXTERNAL MODULE: ./node_modules/openai/index.mjs + 53 modules +var openai = __webpack_require__(37); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/count_tokens.js +var count_tokens = __webpack_require__(8393); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js +var schema = __webpack_require__(8102); +// EXTERNAL MODULE: ./node_modules/zod-to-json-schema/index.js +var zod_to_json_schema = __webpack_require__(8707); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/tools/convert_to_openai.js + +/** + * Formats a `StructuredTool` instance into a format that is compatible + * with OpenAI's ChatCompletionFunctions. It uses the `zodToJsonSchema` + * function to convert the schema of the `StructuredTool` into a JSON + * schema, which is then used as the parameters for the OpenAI function. + */ +function formatToOpenAIFunction(tool) { + return { + name: tool.name, + description: tool.description, + parameters: (0,zod_to_json_schema.zodToJsonSchema)(tool.schema), + }; +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/azure.js +var azure = __webpack_require__(113); +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/env.js +var env = __webpack_require__(5785); +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/prompt-layer.js +var prompt_layer = __webpack_require__(2306); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/manager.js + 13 modules +var manager = __webpack_require__(6009); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chat_models/base.js + + + +/** + * Creates a transform stream for encoding chat message chunks. + * @deprecated Use {@link BytesOutputParser} instead + * @returns A TransformStream instance that encodes chat message chunks. + */ +function createChatMessageChunkEncoderStream() { + const textEncoder = new TextEncoder(); + return new TransformStream({ + transform(chunk, controller) { + controller.enqueue(textEncoder.encode(chunk.content)); + }, + }); +} +/** + * Base class for chat models. It extends the BaseLanguageModel class and + * provides methods for generating chat based on input messages. + */ +class BaseChatModel extends base_language/* BaseLanguageModel */.qV { + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "chat_models", this._llmType()] + }); + } + _separateRunnableConfigFromCallOptions(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + if (callOptions?.timeout && !callOptions.signal) { + callOptions.signal = AbortSignal.timeout(callOptions.timeout); + } + return [runnableConfig, callOptions]; + } + /** + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = BaseChatModel._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + const chatGeneration = result.generations[0][0]; + // TODO: Remove cast after figuring out inheritance + return chatGeneration.message; + } + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); + } + async *_streamIterator(input, options) { + // Subclass check required to avoid double callbacks with default implementation + if (this._streamResponseChunks === + BaseChatModel.prototype._streamResponseChunks) { + yield this.invoke(input, options); + } + else { + const prompt = BaseChatModel._convertInputToPromptValue(input); + const messages = prompt.toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); + const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [messages], undefined, undefined, extra); + let generationChunk; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + yield chunk.message; + if (!generationChunk) { + generationChunk = chunk; + } + else { + generationChunk = generationChunk.concat(chunk); + } + } + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + // TODO: Remove cast after figuring out inheritance + generations: [[generationChunk]], + }))); + } + } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions) { + const baseMessages = messages.map((messageList) => messageList.map(schema/* coerceMessageLikeToMessage */.E1)); + // create callback manager and start run + const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, undefined, undefined, extra); + // generate results + const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); + // handle results + const generations = []; + const llmOutputs = []; + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput, + }); + } + else { + // status === "rejected" + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); + } + })); + // create combined output + const output = { + generations, + llmOutput: llmOutputs.length + ? this._combineLLMOutput?.(...llmOutputs) + : undefined, + }; + Object.defineProperty(output, schema/* RUN_KEY */.WH, { + value: runManagers + ? { runIds: runManagers?.map((manager) => manager.runId) } + : undefined, + configurable: true, + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + // parse call options + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } + else { + parsedOptions = options; + } + const baseMessages = messages.map((messageList) => messageList.map(schema/* coerceMessageLikeToMessage */.E1)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(baseMessages, callOptions, runnableConfig); + } + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const missingPromptIndices = []; + const generations = await Promise.all(baseMessages.map(async (baseMessage, index) => { + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache.lookup(prompt, llmStringKey); + if (!result) { + missingPromptIndices.push(index); + } + return result; + })); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; + } + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; + } + _modelType() { + return "base_chat_model"; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this.invocationParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); + } + /** + * Makes a single call to the chat model. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async call(messages, options, callbacks) { + const result = await this.generate([messages.map(schema/* coerceMessageLikeToMessage */.E1)], options, callbacks); + const generations = result.generations; + return generations[0][0].message; + } + /** + * Makes a single call to the chat model with a prompt value. + * @param promptValue The value of the prompt. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async callPrompt(promptValue, options, callbacks) { + const promptMessages = promptValue.toChatMessages(); + return this.call(promptMessages, options, callbacks); + } + /** + * Predicts the next message based on the input messages. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async predictMessages(messages, options, callbacks) { + return this.call(messages, options, callbacks); + } + /** + * Predicts the next message based on a text input. + * @param text The text input. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a string. + */ + async predict(text, options, callbacks) { + const message = new schema/* HumanMessage */.xk(text); + const result = await this.call([message], options, callbacks); + return result.content; + } +} +/** + * An abstract class that extends BaseChatModel and provides a simple + * implementation of _generate. + */ +class SimpleChatModel extends (/* unused pure expression or super */ null && (BaseChatModel)) { + async _generate(messages, options, runManager) { + const text = await this._call(messages, options, runManager); + const message = new AIMessage(text); + return { + generations: [ + { + text: message.content, + message, + }, + ], + }; + } +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/openai.js +var util_openai = __webpack_require__(8311); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chat_models/openai.js + + + + + + + + + +function extractGenericMessageCustomRole(message) { + if (message.role !== "system" && + message.role !== "assistant" && + message.role !== "user" && + message.role !== "function") { + console.warn(`Unknown message role: ${message.role}`); + } + return message.role; +} +function messageToOpenAIRole(message) { + const type = message._getType(); + switch (type) { + case "system": + return "system"; + case "ai": + return "assistant"; + case "human": + return "user"; + case "function": + return "function"; + case "generic": { + if (!schema/* ChatMessage.isInstance */.J.isInstance(message)) + throw new Error("Invalid generic chat message"); + return extractGenericMessageCustomRole(message); + } + default: + throw new Error(`Unknown message type: ${type}`); + } +} +function openAIResponseToChatMessage(message) { + switch (message.role) { + case "user": + return new schema/* HumanMessage */.xk(message.content || ""); + case "assistant": + return new schema/* AIMessage */.gY(message.content || "", { + function_call: message.function_call, + }); + case "system": + return new schema/* SystemMessage */.jN(message.content || ""); + default: + return new schema/* ChatMessage */.J(message.content || "", message.role ?? "unknown"); + } +} +function _convertDeltaToMessageChunk( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +delta, defaultRole) { + const role = delta.role ?? defaultRole; + const content = delta.content ?? ""; + let additional_kwargs; + if (delta.function_call) { + additional_kwargs = { + function_call: delta.function_call, + }; + } + else { + additional_kwargs = {}; + } + if (role === "user") { + return new schema/* HumanMessageChunk */.ro({ content }); + } + else if (role === "assistant") { + return new schema/* AIMessageChunk */.GC({ content, additional_kwargs }); + } + else if (role === "system") { + return new schema/* SystemMessageChunk */.xq({ content }); + } + else if (role === "function") { + return new schema/* FunctionMessageChunk */.Cr({ + content, + additional_kwargs, + name: delta.name, + }); + } + else { + return new schema/* ChatMessageChunk */.HD({ content, role }); + } +} +/** + * Wrapper around OpenAI large language models that use the Chat endpoint. + * + * To use you should have the `openai` package installed, with the + * `OPENAI_API_KEY` environment variable set. + * + * To use with Azure you should have the `openai` package installed, with the + * `AZURE_OPENAI_API_KEY`, + * `AZURE_OPENAI_API_INSTANCE_NAME`, + * `AZURE_OPENAI_API_DEPLOYMENT_NAME` + * and `AZURE_OPENAI_API_VERSION` environment variable set. + * `AZURE_OPENAI_BASE_PATH` is optional and will override `AZURE_OPENAI_API_INSTANCE_NAME` if you need to use a custom endpoint. + * + * @remarks + * Any parameters that are valid to be passed to {@link + * https://platform.openai.com/docs/api-reference/chat/create | + * `openai.createChatCompletion`} can be passed through {@link modelKwargs}, even + * if not explicitly available on this class. + */ +class ChatOpenAI extends BaseChatModel { + static lc_name() { + return "ChatOpenAI"; + } + get callKeys() { + return [ + ...super.callKeys, + "options", + "function_call", + "functions", + "tools", + "promptIndex", + ]; + } + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION", + }; + } + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + azureOpenAIApiVersion: "azure_openai_api_version", + azureOpenAIApiKey: "azure_openai_api_key", + azureOpenAIApiInstanceName: "azure_openai_api_instance_name", + azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", + }; + } + constructor(fields, + /** @deprecated */ + configuration) { + super(fields ?? {}); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "temperature", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "topP", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "frequencyPenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "presencePenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "n", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "logitBias", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelName", { + enumerable: true, + configurable: true, + writable: true, + value: "gpt-3.5-turbo" + }); + Object.defineProperty(this, "modelKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stop", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "user", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "streaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "openAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiVersion", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiInstanceName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiDeploymentName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIBasePath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "organization", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.openAIApiKey = + fields?.openAIApiKey ?? (0,env/* getEnvironmentVariable */.lS)("OPENAI_API_KEY"); + this.azureOpenAIApiKey = + fields?.azureOpenAIApiKey ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_KEY"); + if (!this.azureOpenAIApiKey && !this.openAIApiKey) { + throw new Error("OpenAI or Azure OpenAI API key not found"); + } + this.azureOpenAIApiInstanceName = + fields?.azureOpenAIApiInstanceName ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = + fields?.azureOpenAIApiDeploymentName ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_DEPLOYMENT_NAME"); + this.azureOpenAIApiVersion = + fields?.azureOpenAIApiVersion ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = + fields?.azureOpenAIBasePath ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_BASE_PATH"); + this.organization = + fields?.configuration?.organization ?? + (0,env/* getEnvironmentVariable */.lS)("OPENAI_ORGANIZATION"); + this.modelName = fields?.modelName ?? this.modelName; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.maxTokens = fields?.maxTokens; + this.n = fields?.n ?? this.n; + this.logitBias = fields?.logitBias; + this.stop = fields?.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.azureOpenAIApiKey) { + if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { + throw new Error("Azure OpenAI API instance name not found"); + } + if (!this.azureOpenAIApiDeploymentName) { + throw new Error("Azure OpenAI API deployment name not found"); + } + if (!this.azureOpenAIApiVersion) { + throw new Error("Azure OpenAI API version not found"); + } + this.openAIApiKey = this.openAIApiKey ?? ""; + } + this.clientConfig = { + apiKey: this.openAIApiKey, + organization: this.organization, + baseURL: configuration?.basePath ?? fields?.configuration?.basePath, + dangerouslyAllowBrowser: true, + defaultHeaders: configuration?.baseOptions?.headers ?? + fields?.configuration?.baseOptions?.headers, + defaultQuery: configuration?.baseOptions?.params ?? + fields?.configuration?.baseOptions?.params, + ...configuration, + ...fields?.configuration, + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.modelName, + temperature: this.temperature, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens, + n: this.n, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stop, + user: this.user, + stream: this.streaming, + functions: options?.functions ?? + (options?.tools + ? options?.tools.map(formatToOpenAIFunction) + : undefined), + function_call: options?.function_call, + ...this.modelKwargs, + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + async *_streamResponseChunks(messages, options, runManager) { + const messagesMapped = messages.map((message) => ({ + role: messageToOpenAIRole(message), + content: message.content, + name: message.name, + function_call: message.additional_kwargs + .function_call, + })); + const params = { + ...this.invocationParams(options), + messages: messagesMapped, + stream: true, + }; + let defaultRole; + const streamIterable = await this.completionWithRetry(params, options); + for await (const data of streamIterable) { + const choice = data?.choices[0]; + if (!choice) { + continue; + } + const { delta } = choice; + const chunk = _convertDeltaToMessageChunk(delta, defaultRole); + defaultRole = delta.role ?? defaultRole; + const newTokenIndices = { + prompt: options.promptIndex ?? 0, + completion: choice.index ?? 0, + }; + const generationChunk = new schema/* ChatGenerationChunk */.Ls({ + message: chunk, + text: chunk.content, + generationInfo: newTokenIndices, + }); + yield generationChunk; + // eslint-disable-next-line no-void + void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, undefined, undefined, undefined, { chunk: generationChunk }); + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); + } + /** @ignore */ + async _generate(messages, options, runManager) { + const tokenUsage = {}; + const params = this.invocationParams(options); + const messagesMapped = messages.map((message) => ({ + role: messageToOpenAIRole(message), + content: message.content, + name: message.name, + function_call: message.additional_kwargs + .function_call, + })); + if (params.stream) { + const stream = await this._streamResponseChunks(messages, options, runManager); + const finalChunks = {}; + for await (const chunk of stream) { + const index = chunk.generationInfo?.completion ?? 0; + if (finalChunks[index] === undefined) { + finalChunks[index] = chunk; + } + else { + finalChunks[index] = finalChunks[index].concat(chunk); + } + } + const generations = Object.entries(finalChunks) + .sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)) + .map(([_, value]) => value); + return { generations }; + } + else { + const data = await this.completionWithRetry({ + ...params, + stream: false, + messages: messagesMapped, + }, { + signal: options?.signal, + ...options?.options, + }); + const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data?.usage ?? {}; + if (completionTokens) { + tokenUsage.completionTokens = + (tokenUsage.completionTokens ?? 0) + completionTokens; + } + if (promptTokens) { + tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; + } + if (totalTokens) { + tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; + } + const generations = []; + for (const part of data?.choices ?? []) { + const text = part.message?.content ?? ""; + const generation = { + text, + message: openAIResponseToChatMessage(part.message ?? { role: "assistant" }), + }; + if (part.finish_reason) { + generation.generationInfo = { finish_reason: part.finish_reason }; + } + generations.push(generation); + } + return { + generations, + llmOutput: { tokenUsage }, + }; + } + } + async getNumTokensFromMessages(messages) { + let totalCount = 0; + let tokensPerMessage = 0; + let tokensPerName = 0; + // From: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb + if ((0,count_tokens/* getModelNameForTiktoken */._i)(this.modelName) === "gpt-3.5-turbo") { + tokensPerMessage = 4; + tokensPerName = -1; + } + else if ((0,count_tokens/* getModelNameForTiktoken */._i)(this.modelName).startsWith("gpt-4")) { + tokensPerMessage = 3; + tokensPerName = 1; + } + const countPerMessage = await Promise.all(messages.map(async (message) => { + const textCount = await this.getNumTokens(message.content); + const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); + const nameCount = message.name !== undefined + ? tokensPerName + (await this.getNumTokens(message.name)) + : 0; + const count = textCount + tokensPerMessage + roleCount + nameCount; + totalCount += count; + return count; + })); + totalCount += 3; // every reply is primed with <|start|>assistant<|message|> + return { totalCount, countPerMessage }; + } + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.chat.completions.create(request, requestOptions); + return res; + } + catch (e) { + const error = (0,util_openai/* wrapOpenAIClientError */.K)(e); + throw error; + } + }); + } + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + baseURL: this.clientConfig.baseURL, + }; + const endpoint = (0,azure/* getEndpoint */.O)(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0, + }; + if (!params.baseURL) { + delete params.baseURL; + } + this.client = new openai/* OpenAI */.Pp(params); + } + const requestOptions = { + ...this.clientConfig, + ...options, + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers, + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query, + }; + } + return requestOptions; + } + _llmType() { + return "openai"; + } + /** @ignore */ + _combineLLMOutput(...llmOutputs) { + return llmOutputs.reduce((acc, llmOutput) => { + if (llmOutput && llmOutput.tokenUsage) { + acc.tokenUsage.completionTokens += + llmOutput.tokenUsage.completionTokens ?? 0; + acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; + acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; + } + return acc; + }, { + tokenUsage: { + completionTokens: 0, + promptTokens: 0, + totalTokens: 0, + }, + }); + } +} +class PromptLayerChatOpenAI extends ChatOpenAI { + constructor(fields) { + super(fields); + Object.defineProperty(this, "promptLayerApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "plTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnPromptLayerId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.promptLayerApiKey = + fields?.promptLayerApiKey ?? + (typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.PROMPTLAYER_API_KEY + : undefined); + this.plTags = fields?.plTags ?? []; + this.returnPromptLayerId = fields?.returnPromptLayerId ?? false; + } + async _generate(messages, options, runManager) { + const requestStartTime = Date.now(); + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } + else if (options?.timeout && !options.signal) { + parsedOptions = { + ...options, + signal: AbortSignal.timeout(options.timeout), + }; + } + else { + parsedOptions = options ?? {}; + } + const generatedResponses = await super._generate(messages, parsedOptions, runManager); + const requestEndTime = Date.now(); + const _convertMessageToDict = (message) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let messageDict; + if (message._getType() === "human") { + messageDict = { role: "user", content: message.content }; + } + else if (message._getType() === "ai") { + messageDict = { role: "assistant", content: message.content }; + } + else if (message._getType() === "function") { + messageDict = { role: "assistant", content: message.content }; + } + else if (message._getType() === "system") { + messageDict = { role: "system", content: message.content }; + } + else if (message._getType() === "generic") { + messageDict = { + role: message.role, + content: message.content, + }; + } + else { + throw new Error(`Got unknown type ${message}`); + } + return messageDict; + }; + const _createMessageDicts = (messages, callOptions) => { + const params = { + ...this.invocationParams(), + model: this.modelName, + }; + if (callOptions?.stop) { + if (Object.keys(params).includes("stop")) { + throw new Error("`stop` found in both the input and default params."); + } + } + const messageDicts = messages.map((message) => _convertMessageToDict(message)); + return messageDicts; + }; + for (let i = 0; i < generatedResponses.generations.length; i += 1) { + const generation = generatedResponses.generations[i]; + const messageDicts = _createMessageDicts(messages, parsedOptions); + let promptLayerRequestId; + const parsedResp = [ + { + content: generation.text, + role: messageToOpenAIRole(generation.message), + }, + ]; + const promptLayerRespBody = await (0,prompt_layer/* promptLayerTrackRequest */.r)(this.caller, "langchain.PromptLayerChatOpenAI", { ...this._identifyingParams(), messages: messageDicts, stream: false }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); + if (this.returnPromptLayerId === true) { + if (promptLayerRespBody.success === true) { + promptLayerRequestId = promptLayerRespBody.request_id; + } + if (!generation.generationInfo || + typeof generation.generationInfo !== "object") { + generation.generationInfo = {}; + } + generation.generationInfo.promptLayerRequestId = promptLayerRequestId; + } + } + return generatedResponses; + } +} + + +/***/ }) + +}; diff --git a/dist/273.index.js b/dist/273.index.js new file mode 100644 index 0000000..5e6246c --- /dev/null +++ b/dist/273.index.js @@ -0,0 +1,448 @@ +export const id = 273; +export const ids = [273]; +export const modules = { + +/***/ 7273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "LLMChain": () => (/* binding */ LLMChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules +var runnable = __webpack_require__(1972); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/output_parser.js + +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends runnable/* Runnable */.eq { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input) => this.parseResult([{ text: input }]), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input) => this.parseResult([{ message: input, text: input.content }]), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Class to parse the output of an LLM call that also allows streaming inputs. + */ +class BaseTransformOutputParser extends (/* unused pure expression or super */ null && (BaseOutputParser)) { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) { + if (typeof chunk === "string") { + yield this.parseResult([{ text: chunk }]); + } + else { + yield this.parseResult([{ message: chunk, text: chunk.content }]); + } + } + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser", + }); + } +} +/** + * OutputParser that parses LLMResult into the top likely string. + */ +class StringOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "StrOutputParser"; + } + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } +} +/** + * OutputParser that parses LLMResult into the top likely string and + * encodes it into bytes. + */ +class BytesOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "textEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: new TextEncoder() + }); + } + static lc_name() { + return "BytesOutputParser"; + } + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/output_parsers/noop.js + +/** + * The NoOpOutputParser class is a type of output parser that does not + * perform any operations on the output. It extends the BaseOutputParser + * class and is part of the LangChain's output parsers module. This class + * is useful in scenarios where the raw output of the Large Language + * Models (LLMs) is required. + */ +class NoOpOutputParser extends BaseOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "output_parsers", "default"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "NoOpOutputParser"; + } + /** + * This method takes a string as input and returns the same string as + * output. It does not perform any operations on the input string. + * @param text The input string to be parsed. + * @returns The same input string without any operations performed on it. + */ + parse(text) { + return Promise.resolve(text); + } + /** + * This method returns an empty string. It does not provide any formatting + * instructions. + * @returns An empty string, indicating no formatting instructions. + */ + getFormatInstructions() { + return ""; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + + + + +/** + * Chain to run queries against LLMs. + * + * @example + * ```ts + * import { LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); + * const llm = new LLMChain({ llm: new OpenAI(), prompt }); + * ``` + */ +class LLMChain extends base/* BaseChain */.l { + static lc_name() { + return "LLMChain"; + } + get inputKeys() { + return this.prompt.inputVariables; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llmKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "text" + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + this.llm = fields.llm; + this.llmKwargs = fields.llmKwargs; + this.outputKey = fields.outputKey ?? this.outputKey; + this.outputParser = + fields.outputParser ?? new NoOpOutputParser(); + if (this.prompt.outputParser) { + if (fields.outputParser) { + throw new Error("Cannot set both outputParser and prompt.outputParser"); + } + this.outputParser = this.prompt.outputParser; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = super._selectMemoryInputs(values); + for (const key of this.llm.callKeys) { + if (key in values) { + delete valuesForMemory[key]; + } + } + return valuesForMemory; + } + /** @ignore */ + async _getFinalOutput(generations, promptValue, runManager) { + let finalCompletion; + if (this.outputParser) { + finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + } + else { + finalCompletion = generations[0].text; + } + return finalCompletion; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + call(values, config) { + return super.call(values, config); + } + /** @ignore */ + async _call(values, runManager) { + const valuesForPrompt = { ...values }; + const valuesForLLM = { + ...this.llmKwargs, + }; + for (const key of this.llm.callKeys) { + if (key in values) { + valuesForLLM[key] = values[key]; + delete valuesForPrompt[key]; + } + } + const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); + const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); + return { + [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), + }; + } + /** + * Format prompt with values and pass to LLM + * + * @param values - keys to pass to prompt template + * @param callbackManager - CallbackManager to use + * @returns Completion from LLM. + * + * @example + * ```ts + * llm.predict({ adjective: "funny" }) + * ``` + */ + async predict(values, callbackManager) { + const output = await this.call(values, callbackManager); + return output[this.outputKey]; + } + _chainType() { + return "llm"; + } + static async deserialize(data) { + const { llm, prompt } = data; + if (!llm) { + throw new Error("LLMChain must have llm"); + } + if (!prompt) { + throw new Error("LLMChain must have prompt"); + } + return new LLMChain({ + llm: await base_language/* BaseLanguageModel.deserialize */.qV.deserialize(llm), + prompt: await prompts_base/* BasePromptTemplate.deserialize */.dy.deserialize(prompt), + }); + } + /** @deprecated */ + serialize() { + return { + _type: `${this._chainType()}_chain`, + llm: this.llm.serialize(), + prompt: this.prompt.serialize(), + }; + } +} + + +/***/ }) + +}; diff --git a/dist/312.index.js b/dist/312.index.js new file mode 100644 index 0000000..d85481c --- /dev/null +++ b/dist/312.index.js @@ -0,0 +1,1156 @@ +export const id = 312; +export const ids = [312,609,197,806,214]; +export const modules = { + +/***/ 3197: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "l": () => (/* binding */ BaseChain) +/* harmony export */ }); +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6009); +/* harmony import */ var _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7679); + + + +/** + * Base interface that all chains must implement. + */ +class BaseChain extends _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__/* .BaseLangChain */ .BD { + get lc_namespace() { + return ["langchain", "chains", this._chainType()]; + } + constructor(fields, + /** @deprecated */ + verbose, + /** @deprecated */ + callbacks) { + if (arguments.length === 1 && + typeof fields === "object" && + !("saveContext" in fields)) { + // fields is not a BaseMemory + const { memory, callbackManager, ...rest } = fields; + super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); + this.memory = memory; + } + else { + // fields is a BaseMemory + super({ verbose, callbacks }); + this.memory = fields; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = { ...values }; + if ("signal" in valuesForMemory) { + delete valuesForMemory.signal; + } + if ("timeout" in valuesForMemory) { + delete valuesForMemory.timeout; + } + return valuesForMemory; + } + /** + * Invoke the chain with the provided input and returns the output. + * @param input Input values for the chain run. + * @param config Optional configuration for the Runnable. + * @returns Promise that resolves with the output of the chain run. + */ + async invoke(input, config) { + return this.call(input, config); + } + /** + * Return a json-like object representing this chain. + */ + serialize() { + throw new Error("Method not implemented."); + } + async run( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, config) { + const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); + const isKeylessInput = inputKeys.length <= 1; + if (!isKeylessInput) { + throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; + const returnValues = await this.call(values, config); + const keys = Object.keys(returnValues); + if (keys.length === 1) { + return returnValues[keys[0]]; + } + throw new Error("return values have multiple keys, `run` only supported when one key currently"); + } + async _formatValues(values) { + const fullValues = { ...values }; + if (fullValues.timeout && !fullValues.signal) { + fullValues.signal = AbortSignal.timeout(fullValues.timeout); + delete fullValues.timeout; + } + if (!(this.memory == null)) { + const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); + for (const [key, value] of Object.entries(newValues)) { + fullValues[key] = value; + } + } + return fullValues; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + async call(values, config, + /** @deprecated */ + tags) { + const fullValues = await this._formatValues(values); + const parsedConfig = (0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .parseCallbackConfigArg */ .QH)(config); + const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .CallbackManager.configure */ .Ye.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); + let outputValues; + try { + outputValues = await (values.signal + ? Promise.race([ + this._call(fullValues, runManager), + new Promise((_, reject) => { + values.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]) + : this._call(fullValues, runManager)); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + if (!(this.memory == null)) { + await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + } + await runManager?.handleChainEnd(outputValues); + // add the runManager's currentRunId to the outputValues + Object.defineProperty(outputValues, _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .RUN_KEY */ .WH, { + value: runManager ? { runId: runManager?.runId } : undefined, + configurable: true, + }); + return outputValues; + } + /** + * Call the chain on all inputs in the list + */ + async apply(inputs, config) { + return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + } + /** + * Load a chain from a json-like object describing it. + */ + static async deserialize(data, values = {}) { + switch (data._type) { + case "llm_chain": { + const { LLMChain } = await __webpack_require__.e(/* import() */ 273).then(__webpack_require__.bind(__webpack_require__, 7273)); + return LLMChain.deserialize(data); + } + case "sequential_chain": { + const { SequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SequentialChain.deserialize(data); + } + case "simple_sequential_chain": { + const { SimpleSequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SimpleSequentialChain.deserialize(data); + } + case "stuff_documents_chain": { + const { StuffDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return StuffDocumentsChain.deserialize(data); + } + case "map_reduce_documents_chain": { + const { MapReduceDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return MapReduceDocumentsChain.deserialize(data); + } + case "refine_documents_chain": { + const { RefineDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return RefineDocumentsChain.deserialize(data); + } + case "vector_db_qa": { + const { VectorDBQAChain } = await Promise.all(/* import() */[__webpack_require__.e(608), __webpack_require__.e(214)]).then(__webpack_require__.bind(__webpack_require__, 5214)); + return VectorDBQAChain.deserialize(data, values); + } + case "api_chain": { + const { APIChain } = await __webpack_require__.e(/* import() */ 159).then(__webpack_require__.bind(__webpack_require__, 6159)); + return APIChain.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } +} + + +/***/ }), + +/***/ 5214: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "VectorDBQAChain": () => (/* binding */ VectorDBQAChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 2 modules +var llm_chain = __webpack_require__(7273); +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/combine_docs_chain.js +var combine_docs_chain = __webpack_require__(3608); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js +var prompts_prompt = __webpack_require__(4095); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/chat.js +var chat = __webpack_require__(6704); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/conditional.js +/** + * Abstract class that defines the interface for selecting a prompt for a + * given language model. + */ +class BasePromptSelector { + /** + * Asynchronous version of `getPrompt` that also accepts an options object + * for partial variables. + * @param llm The language model for which to get a prompt. + * @param options Optional object for partial variables. + * @returns A Promise that resolves to a prompt template. + */ + async getPromptAsync(llm, options) { + const prompt = this.getPrompt(llm); + return prompt.partial(options?.partialVariables ?? {}); + } +} +/** + * Concrete implementation of `BasePromptSelector` that selects a prompt + * based on a set of conditions. It has a default prompt that it returns + * if none of the conditions are met. + */ +class ConditionalPromptSelector extends BasePromptSelector { + constructor(default_prompt, conditionals = []) { + super(); + Object.defineProperty(this, "defaultPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "conditionals", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.defaultPrompt = default_prompt; + this.conditionals = conditionals; + } + /** + * Method that selects a prompt based on a set of conditions. If none of + * the conditions are met, it returns the default prompt. + * @param llm The language model for which to get a prompt. + * @returns A prompt template. + */ + getPrompt(llm) { + for (const [condition, prompt] of this.conditionals) { + if (condition(llm)) { + return prompt; + } + } + return this.defaultPrompt; + } +} +/** + * Type guard function that checks if a given language model is of type + * `BaseLLM`. + */ +function isLLM(llm) { + return llm._modelType() === "base_llm"; +} +/** + * Type guard function that checks if a given language model is of type + * `BaseChatModel`. + */ +function isChatModel(llm) { + return llm._modelType() === "base_chat_model"; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/stuff_prompts.js +/* eslint-disable spaced-comment */ + + + +const DEFAULT_QA_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ + template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", + inputVariables: ["context", "question"], +}); +const system_template = `Use the following pieces of context to answer the users question. +If you don't know the answer, just say that you don't know, don't try to make up an answer. +---------------- +{context}`; +const messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(system_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_PROMPT = /*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(messages); +const QA_PROMPT_SELECTOR = /*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_QA_PROMPT, [[isChatModel, CHAT_PROMPT]]); + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js +/* eslint-disable spaced-comment */ + + + +const qa_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. +Return any relevant text verbatim. +{context} +Question: {question} +Relevant text, if any:`; +const DEFAULT_COMBINE_QA_PROMPT = +/*#__PURE__*/ +prompts_prompt.PromptTemplate.fromTemplate(qa_template); +const map_reduce_prompts_system_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. +Return any relevant text verbatim. +---------------- +{context}`; +const map_reduce_prompts_messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(map_reduce_prompts_system_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_QA_PROMPT = /*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(map_reduce_prompts_messages); +const map_reduce_prompts_COMBINE_QA_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_COMBINE_QA_PROMPT, [ + [isChatModel, CHAT_QA_PROMPT], +]); +const combine_prompt = `Given the following extracted parts of a long document and a question, create a final answer. +If you don't know the answer, just say that you don't know. Don't try to make up an answer. + +QUESTION: Which state/country's law governs the interpretation of the contract? +========= +Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. + +Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties.\n\n11.9 No Third-Party Beneficiaries. + +Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, +========= +FINAL ANSWER: This Agreement is governed by English law. + +QUESTION: What did the president say about Michael Jackson? +========= +Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. + +Content: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. + +Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay. + +Content: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation. +========= +FINAL ANSWER: The president did not mention Michael Jackson. + +QUESTION: {question} +========= +{summaries} +========= +FINAL ANSWER:`; +const COMBINE_PROMPT = +/*#__PURE__*/ prompts_prompt.PromptTemplate.fromTemplate(combine_prompt); +const system_combine_template = `Given the following extracted parts of a long document and a question, create a final answer. +If you don't know the answer, just say that you don't know. Don't try to make up an answer. +---------------- +{summaries}`; +const combine_messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(system_combine_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_COMBINE_PROMPT = +/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(combine_messages); +const map_reduce_prompts_COMBINE_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(COMBINE_PROMPT, [ + [isChatModel, CHAT_COMBINE_PROMPT], +]); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/LengthBasedExampleSelector.js + +/** + * Calculates the length of a text based on the number of words and lines. + */ +function getLengthBased(text) { + return text.split(/\n| /).length; +} +/** + * A specialized example selector that selects examples based on their + * length, ensuring that the total length of the selected examples does + * not exceed a specified maximum length. + */ +class LengthBasedExampleSelector extends (/* unused pure expression or super */ null && (BaseExampleSelector)) { + constructor(data) { + super(data); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "getTextLength", { + enumerable: true, + configurable: true, + writable: true, + value: getLengthBased + }); + Object.defineProperty(this, "maxLength", { + enumerable: true, + configurable: true, + writable: true, + value: 2048 + }); + Object.defineProperty(this, "exampleTextLengths", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + this.examplePrompt = data.examplePrompt; + this.maxLength = data.maxLength ?? 2048; + this.getTextLength = data.getTextLength ?? getLengthBased; + } + /** + * Adds an example to the list of examples and calculates its length. + * @param example The example to be added. + * @returns Promise that resolves when the example has been added and its length calculated. + */ + async addExample(example) { + this.examples.push(example); + const stringExample = await this.examplePrompt.format(example); + this.exampleTextLengths.push(this.getTextLength(stringExample)); + } + /** + * Calculates the lengths of the examples. + * @param v Array of lengths of the examples. + * @param values Instance of LengthBasedExampleSelector. + * @returns Promise that resolves with an array of lengths of the examples. + */ + async calculateExampleTextLengths(v, values) { + if (v.length > 0) { + return v; + } + const { examples, examplePrompt } = values; + const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); + return stringExamples.map((eg) => this.getTextLength(eg)); + } + /** + * Selects examples until the total length of the selected examples + * reaches the maxLength. + * @param inputVariables The input variables for the examples. + * @returns Promise that resolves with an array of selected examples. + */ + async selectExamples(inputVariables) { + const inputs = Object.values(inputVariables).join(" "); + let remainingLength = this.maxLength - this.getTextLength(inputs); + let i = 0; + const examples = []; + while (remainingLength > 0 && i < this.examples.length) { + const newLength = remainingLength - this.exampleTextLengths[i]; + if (newLength < 0) { + break; + } + else { + examples.push(this.examples[i]); + remainingLength = newLength; + } + i += 1; + } + return examples; + } + /** + * Creates a new instance of LengthBasedExampleSelector and adds a list of + * examples to it. + * @param examples Array of examples to be added. + * @param args Input parameters for the LengthBasedExampleSelector. + * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. + */ + static async fromExamples(examples, args) { + const selector = new LengthBasedExampleSelector(args); + await Promise.all(examples.map((eg) => selector.addExample(eg))); + return selector; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/SemanticSimilarityExampleSelector.js + + +function sortedValues(values) { + return Object.keys(values) + .sort() + .map((key) => values[key]); +} +/** + * Class that selects examples based on semantic similarity. It extends + * the BaseExampleSelector class. + */ +class SemanticSimilarityExampleSelector extends (/* unused pure expression or super */ null && (BaseExampleSelector)) { + constructor(data) { + super(data); + Object.defineProperty(this, "vectorStore", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "k", { + enumerable: true, + configurable: true, + writable: true, + value: 4 + }); + Object.defineProperty(this, "exampleKeys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKeys", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.vectorStore = data.vectorStore; + this.k = data.k ?? 4; + this.exampleKeys = data.exampleKeys; + this.inputKeys = data.inputKeys; + } + /** + * Method that adds a new example to the vectorStore. The example is + * converted to a string and added to the vectorStore as a document. + * @param example The example to be added to the vectorStore. + * @returns Promise that resolves when the example has been added to the vectorStore. + */ + async addExample(example) { + const inputKeys = this.inputKeys ?? Object.keys(example); + const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" "); + await this.vectorStore.addDocuments([ + new Document({ + pageContent: stringExample, + metadata: { example }, + }), + ]); + } + /** + * Method that selects which examples to use based on semantic similarity. + * It performs a similarity search in the vectorStore using the input + * variables and returns the examples with the highest similarity. + * @param inputVariables The input variables used for the similarity search. + * @returns Promise that resolves with an array of the selected examples. + */ + async selectExamples(inputVariables) { + const inputKeys = this.inputKeys ?? Object.keys(inputVariables); + const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" "); + const exampleDocs = await this.vectorStore.similaritySearch(query, this.k); + const examples = exampleDocs.map((doc) => doc.metadata); + if (this.exampleKeys) { + // If example keys are provided, filter examples to those keys. + return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})); + } + return examples; + } + /** + * Static method that creates a new instance of + * SemanticSimilarityExampleSelector. It takes a list of examples, an + * instance of Embeddings, a VectorStore class, and an options object as + * parameters. It converts the examples to strings, creates a VectorStore + * from the strings and the embeddings, and returns a new + * SemanticSimilarityExampleSelector with the created VectorStore and the + * options provided. + * @param examples The list of examples to be used. + * @param embeddings The instance of Embeddings to be used. + * @param vectorStoreCls The VectorStore class to be used. + * @param options The options object for the SemanticSimilarityExampleSelector. + * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. + */ + static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { + const inputKeys = options.inputKeys ?? null; + const stringExamples = examples.map((example) => sortedValues(inputKeys + ? inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {}) + : example).join(" ")); + const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, // metadatas + embeddings, options); + return new SemanticSimilarityExampleSelector({ + vectorStore, + k: options.k ?? 4, + exampleKeys: options.exampleKeys, + inputKeys: options.inputKeys, + }); + } +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/few_shot.js +var few_shot = __webpack_require__(609); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/template.js +var template = __webpack_require__(837); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/pipeline.js + + +/** + * Class that handles a sequence of prompts, each of which may require + * different input variables. Includes methods for formatting these + * prompts, extracting required input values, and handling partial + * prompts. + */ +class PipelinePromptTemplate extends (/* unused pure expression or super */ null && (BasePromptTemplate)) { + static lc_name() { + return "PipelinePromptTemplate"; + } + constructor(input) { + super({ ...input, inputVariables: [] }); + Object.defineProperty(this, "pipelinePrompts", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "finalPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.pipelinePrompts = input.pipelinePrompts; + this.finalPrompt = input.finalPrompt; + this.inputVariables = this.computeInputValues(); + } + /** + * Computes the input values required by the pipeline prompts. + * @returns Array of input values required by the pipeline prompts. + */ + computeInputValues() { + const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); + const inputValues = this.pipelinePrompts + .map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))) + .flat(); + return [...new Set(inputValues)]; + } + static extractRequiredInputValues(allValues, requiredValueNames) { + return requiredValueNames.reduce((requiredValues, valueName) => { + // eslint-disable-next-line no-param-reassign + requiredValues[valueName] = allValues[valueName]; + return requiredValues; + }, {}); + } + /** + * Formats the pipeline prompts based on the provided input values. + * @param values Input values to format the pipeline prompts. + * @returns Promise that resolves with the formatted input values. + */ + async formatPipelinePrompts(values) { + const allValues = await this.mergePartialAndUserVariables(values); + for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this + .pipelinePrompts) { + const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); + // eslint-disable-next-line no-instanceof/no-instanceof + if (pipelinePrompt instanceof ChatPromptTemplate) { + allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); + } + else { + allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); + } + } + return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); + } + /** + * Formats the final prompt value based on the provided input values. + * @param values Input values to format the final prompt value. + * @returns Promise that resolves with the formatted final prompt value. + */ + async formatPromptValue(values) { + return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); + } + async format(values) { + return this.finalPrompt.format(await this.formatPipelinePrompts(values)); + } + /** + * Handles partial prompts, which are prompts that have been partially + * filled with input values. + * @param values Partial input values. + * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. + */ + async partial(values) { + const promptDict = { ...this }; + promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); + promptDict.partialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + return new PipelinePromptTemplate(promptDict); + } + serialize() { + throw new Error("Not implemented."); + } + _getPromptType() { + return "pipeline"; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/index.js + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/refine_prompts.js +/* eslint-disable spaced-comment */ + + +const DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question} +We have provided an existing answer: {existing_answer} +We have the opportunity to refine the existing answer +(only if needed) with some more context below. +------------ +{context} +------------ +Given the new context, refine the original answer to better answer the question. +If the context isn't useful, return the original answer.`; +const DEFAULT_REFINE_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ + inputVariables: ["question", "existing_answer", "context"], + template: DEFAULT_REFINE_PROMPT_TMPL, +}); +const refineTemplate = `The original question is as follows: {question} +We have provided an existing answer: {existing_answer} +We have the opportunity to refine the existing answer +(only if needed) with some more context below. +------------ +{context} +------------ +Given the new context, refine the original answer to better answer the question. +If the context isn't useful, return the original answer.`; +const refine_prompts_messages = [ + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), + /*#__PURE__*/ chat/* AIMessagePromptTemplate.fromTemplate */.gc.fromTemplate("{existing_answer}"), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate(refineTemplate), +]; +const CHAT_REFINE_PROMPT = +/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(refine_prompts_messages); +const refine_prompts_REFINE_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_REFINE_PROMPT, [ + [isChatModel, CHAT_REFINE_PROMPT], +]); +const DEFAULT_TEXT_QA_PROMPT_TMPL = `Context information is below. +--------------------- +{context} +--------------------- +Given the context information and no prior knowledge, answer the question: {question}`; +const DEFAULT_TEXT_QA_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ + inputVariables: ["context", "question"], + template: DEFAULT_TEXT_QA_PROMPT_TMPL, +}); +const chat_qa_prompt_template = `Context information is below. +--------------------- +{context} +--------------------- +Given the context information and no prior knowledge, answer any questions`; +const chat_messages = [ + /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(chat_qa_prompt_template), + /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), +]; +const CHAT_QUESTION_PROMPT = +/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(chat_messages); +const refine_prompts_QUESTION_PROMPT_SELECTOR = +/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_TEXT_QA_PROMPT, [ + [isChatModel, CHAT_QUESTION_PROMPT], +]); + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/load.js + + + + + +const loadQAChain = (llm, params = { type: "stuff" }) => { + const { type } = params; + if (type === "stuff") { + return loadQAStuffChain(llm, params); + } + if (type === "map_reduce") { + return loadQAMapReduceChain(llm, params); + } + if (type === "refine") { + return loadQARefineChain(llm, params); + } + throw new Error(`Invalid _type: ${type}`); +}; +/** + * Loads a StuffQAChain based on the provided parameters. It takes an LLM + * instance and StuffQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a StuffQAChain. + * @returns A StuffQAChain instance. + */ +function loadQAStuffChain(llm, params = {}) { + const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; + const llmChain = new llm_chain.LLMChain({ prompt, llm, verbose }); + const chain = new combine_docs_chain.StuffDocumentsChain({ llmChain, verbose }); + return chain; +} +/** + * Loads a MapReduceQAChain based on the provided parameters. It takes an + * LLM instance and MapReduceQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a MapReduceQAChain. + * @returns A MapReduceQAChain instance. + */ +function loadQAMapReduceChain(llm, params = {}) { + const { combineMapPrompt = COMBINE_QA_PROMPT_SELECTOR.getPrompt(llm), combinePrompt = COMBINE_PROMPT_SELECTOR.getPrompt(llm), verbose, combineLLM, returnIntermediateSteps, } = params; + const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose }); + const combineLLMChain = new LLMChain({ + prompt: combinePrompt, + llm: combineLLM ?? llm, + verbose, + }); + const combineDocumentChain = new StuffDocumentsChain({ + llmChain: combineLLMChain, + documentVariableName: "summaries", + verbose, + }); + const chain = new MapReduceDocumentsChain({ + llmChain, + combineDocumentChain, + returnIntermediateSteps, + verbose, + }); + return chain; +} +/** + * Loads a RefineQAChain based on the provided parameters. It takes an LLM + * instance and RefineQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a RefineQAChain. + * @returns A RefineQAChain instance. + */ +function loadQARefineChain(llm, params = {}) { + const { questionPrompt = QUESTION_PROMPT_SELECTOR.getPrompt(llm), refinePrompt = REFINE_PROMPT_SELECTOR.getPrompt(llm), refineLLM, verbose, } = params; + const llmChain = new LLMChain({ prompt: questionPrompt, llm, verbose }); + const refineLLMChain = new LLMChain({ + prompt: refinePrompt, + llm: refineLLM ?? llm, + verbose, + }); + const chain = new RefineDocumentsChain({ + llmChain, + refineLLMChain, + verbose, + }); + return chain; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/vector_db_qa.js + + +/** + * Class that represents a VectorDBQAChain. It extends the `BaseChain` + * class and implements the `VectorDBQAChainInput` interface. It performs + * a similarity search using a vector store and combines the search + * results using a specified combine documents chain. + */ +class VectorDBQAChain extends base/* BaseChain */.l { + static lc_name() { + return "VectorDBQAChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "k", { + enumerable: true, + configurable: true, + writable: true, + value: 4 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "query" + }); + Object.defineProperty(this, "vectorstore", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnSourceDocuments", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.vectorstore = fields.vectorstore; + this.combineDocumentsChain = fields.combineDocumentsChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.k = fields.k ?? this.k; + this.returnSourceDocuments = + fields.returnSourceDocuments ?? this.returnSourceDocuments; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Question key ${this.inputKey} not found.`); + } + const question = values[this.inputKey]; + const docs = await this.vectorstore.similaritySearch(question, this.k, values.filter, runManager?.getChild("vectorstore")); + const inputs = { question, input_documents: docs }; + const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); + if (this.returnSourceDocuments) { + return { + ...result, + sourceDocuments: docs, + }; + } + return result; + } + _chainType() { + return "vector_db_qa"; + } + static async deserialize(data, values) { + if (!("vectorstore" in values)) { + throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); + } + const { vectorstore } = values; + if (!data.combine_documents_chain) { + throw new Error(`VectorDBQAChain must have combine_documents_chain in serialized data`); + } + return new VectorDBQAChain({ + combineDocumentsChain: await base/* BaseChain.deserialize */.l.deserialize(data.combine_documents_chain), + k: data.k, + vectorstore, + }); + } + serialize() { + return { + _type: this._chainType(), + combine_documents_chain: this.combineDocumentsChain.serialize(), + k: this.k, + }; + } + /** + * Static method that creates a VectorDBQAChain instance from a + * BaseLanguageModel and a vector store. It also accepts optional options + * to customize the chain. + * @param llm The BaseLanguageModel instance. + * @param vectorstore The vector store used for similarity search. + * @param options Optional options to customize the chain. + * @returns A new instance of VectorDBQAChain. + */ + static fromLLM(llm, vectorstore, options) { + const qaChain = loadQAStuffChain(llm); + return new this({ + vectorstore, + combineDocumentsChain: qaChain, + ...options, + }); + } +} + + +/***/ }), + +/***/ 609: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FewShotPromptTemplate": () => (/* binding */ FewShotPromptTemplate) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5411); +/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(837); +/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4095); + + + +/** + * Prompt template that contains few-shot examples. + * @augments BasePromptTemplate + * @augments FewShotPromptTemplateInput + */ +class FewShotPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleSelector", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "suffix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "exampleSeparator", { + enumerable: true, + configurable: true, + writable: true, + value: "\n\n" + }); + Object.defineProperty(this, "prefix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.examples !== undefined && this.exampleSelector !== undefined) { + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + } + if (this.examples === undefined && this.exampleSelector === undefined) { + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "few_shot"; + } + async getExamples(inputVariables) { + if (this.examples !== undefined) { + return this.examples; + } + if (this.exampleSelector !== undefined) { + return this.exampleSelector.selectExamples(inputVariables); + } + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables, + }; + return new FewShotPromptTemplate(promptDict); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); + return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(template, this.templateFormat, allValues); + } + serialize() { + if (this.exampleSelector || !this.examples) { + throw new Error("Serializing an example selector is not currently supported"); + } + if (this.outputParser !== undefined) { + throw new Error("Serializing an output parser is not currently supported"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples, + }; + } + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) { + throw new Error("Missing example prompt"); + } + const examplePrompt = await _prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) { + examples = data.examples; + } + else { + throw new Error("Invalid examples format. Only list or string are supported."); + } + return new FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format, + }); + } +} + + +/***/ }) + +}; diff --git a/dist/366.index.js b/dist/366.index.js new file mode 100644 index 0000000..97cdc08 --- /dev/null +++ b/dist/366.index.js @@ -0,0 +1,2917 @@ +export const id = 366; +export const ids = [366]; +export const modules = { + +/***/ 113: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "O": () => (/* binding */ getEndpoint) +/* harmony export */ }); +/** + * This function generates an endpoint URL for (Azure) OpenAI + * based on the configuration parameters provided. + * + * @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint. + * + * @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI. + * @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI. + * @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI. + * @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI. + * @property {string} config.baseURL - Some other custom base path URL. + * + * The function operates as follows: + * - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`). + * - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters. + * - If none of the above conditions are met, return any custom `baseURL`. + * - The function returns the generated URL as a string, or undefined if no custom paths are specified. + * + * @throws Will throw an error if the necessary parameters for generating the URL are missing. + * + * @returns {string | undefined} The generated (Azure) OpenAI endpoint URL. + */ +function getEndpoint(config) { + const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, } = config; + if (azureOpenAIApiKey && + azureOpenAIBasePath && + azureOpenAIApiDeploymentName) { + return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; + } + if (azureOpenAIApiKey) { + if (!azureOpenAIApiInstanceName) { + throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); + } + if (!azureOpenAIApiDeploymentName) { + throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); + } + return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; + } + return baseURL; +} + + +/***/ }), + +/***/ 8311: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "K": () => (/* binding */ wrapOpenAIClientError) +/* harmony export */ }); +/* harmony import */ var openai__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function wrapOpenAIClientError(e) { + let error; + if (e.constructor.name === openai__WEBPACK_IMPORTED_MODULE_0__/* .APIConnectionTimeoutError.name */ .zo.name) { + error = new Error(e.message); + error.name = "TimeoutError"; + } + else if (e.constructor.name === openai__WEBPACK_IMPORTED_MODULE_0__/* .APIUserAbortError.name */ .Qr.name) { + error = new Error(e.message); + error.name = "AbortError"; + } + else { + error = e; + } + return error; +} + + +/***/ }), + +/***/ 2306: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "r": () => (/* binding */ promptLayerTrackRequest) +/* harmony export */ }); +const promptLayerTrackRequest = async (callerFunc, functionName, kwargs, plTags, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +requestResponse, startTime, endTime, apiKey) => { + // https://github.com/MagnivOrg/promptlayer-js-helper + const promptLayerResp = await callerFunc.call(fetch, "https://api.promptlayer.com/track-request", { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + function_name: functionName, + provider: "langchain", + kwargs, + tags: plTags, + request_response: requestResponse, + request_start_time: Math.floor(startTime / 1000), + request_end_time: Math.floor(endTime / 1000), + api_key: apiKey, + }), + }); + return promptLayerResp.json(); +}; + + +/***/ }), + +/***/ 37: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "zo": () => (/* binding */ openai_APIConnectionTimeoutError), + "Qr": () => (/* binding */ openai_APIUserAbortError), + "Pp": () => (/* binding */ OpenAI) +}); + +// UNUSED EXPORTS: APIConnectionError, APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, default, fileFromPath, toFile + +// NAMESPACE OBJECT: ./node_modules/openai/error.mjs +var error_namespaceObject = {}; +__webpack_require__.r(error_namespaceObject); +__webpack_require__.d(error_namespaceObject, { + "APIConnectionError": () => (APIConnectionError), + "APIConnectionTimeoutError": () => (APIConnectionTimeoutError), + "APIError": () => (APIError), + "APIUserAbortError": () => (APIUserAbortError), + "AuthenticationError": () => (AuthenticationError), + "BadRequestError": () => (BadRequestError), + "ConflictError": () => (ConflictError), + "InternalServerError": () => (InternalServerError), + "NotFoundError": () => (NotFoundError), + "PermissionDeniedError": () => (PermissionDeniedError), + "RateLimitError": () => (RateLimitError), + "UnprocessableEntityError": () => (UnprocessableEntityError) +}); + +;// CONCATENATED MODULE: ./node_modules/openai/version.mjs +const VERSION = '4.4.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs +class Stream { + constructor(response, controller) { + this.response = response; + this.controller = controller; + this.decoder = new SSEDecoder(); + } + async *iterMessages() { + if (!this.response.body) { + this.controller.abort(); + throw new Error(`Attempted to iterate over a response with no body`); + } + const lineDecoder = new LineDecoder(); + const iter = readableStreamAsyncIterable(this.response.body); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + const sse = this.decoder.decode(line); + if (sse) yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = this.decoder.decode(line); + if (sse) yield sse; + } + } + async *[Symbol.asyncIterator]() { + let done = false; + try { + for await (const sse of this.iterMessages()) { + if (done) continue; + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + if (sse.event === null) { + try { + yield JSON.parse(sse.data); + } catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + } + } + done = true; + } catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') return; + throw e; + } finally { + // If the user `break`s, abort the ongoing request. + if (!done) this.controller.abort(); + } + } +} +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } else if (fieldname === 'data') { + this.data.push(value); + } + return null; + } +} +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class LineDecoder { + constructor() { + this.buffer = []; + this.trailingCR = false; + } + decode(chunk) { + let text = this.decodeText(chunk); + if (this.trailingCR) { + text = '\r' + text; + this.trailingCR = false; + } + if (text.endsWith('\r')) { + this.trailingCR = true; + text = text.slice(0, -1); + } + if (!text) { + return []; + } + const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ''); + let lines = text.split(LineDecoder.NEWLINE_REGEXP); + if (lines.length === 1 && !trailingNewline) { + this.buffer.push(lines[0]); + return []; + } + if (this.buffer.length > 0) { + lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; + this.buffer = []; + } + if (!trailingNewline) { + this.buffer = [lines.pop() || '']; + } + return lines; + } + decodeText(bytes) { + var _a; + if (bytes == null) return ''; + if (typeof bytes === 'string') return bytes; + // Node: + if (typeof Buffer !== 'undefined') { + if (bytes instanceof Buffer) { + return bytes.toString(); + } + if (bytes instanceof Uint8Array) { + return Buffer.from(bytes).toString(); + } + throw new Error( + `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`, + ); + } + // Browser + if (typeof TextDecoder !== 'undefined') { + if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { + (_a = this.textDecoder) !== null && _a !== void 0 ? _a : (this.textDecoder = new TextDecoder('utf8')); + return this.textDecoder.decode(bytes); + } + throw new Error( + `Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`, + ); + } + throw new Error( + `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`, + ); + } + flush() { + if (!this.buffer.length && !this.trailingCR) { + return []; + } + const lines = [this.buffer.join('')]; + this.buffer = []; + this.trailingCR = false; + return lines; + } +} +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\x85', '\u2028', '\u2029']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +function readableStreamAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result === null || result === void 0 ? void 0 : result.done) reader.releaseLock(); // release lock when stream becomes closed + return result; + } catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +//# sourceMappingURL=streaming.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/error.mjs +// File generated from our OpenAPI spec by Stainless. + +class APIError extends Error { + constructor(status, error, message, headers) { + super(APIError.makeMessage(error, message)); + this.status = status; + this.headers = headers; + const data = error; + this.error = data; + this.code = data === null || data === void 0 ? void 0 : data['code']; + this.param = data === null || data === void 0 ? void 0 : data['param']; + this.type = data === null || data === void 0 ? void 0 : data['type']; + } + static makeMessage(error, message) { + return ( + ( + error === null || error === void 0 ? void 0 : error.message + ) ? + typeof error.message === 'string' ? error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message || 'Unknown error occurred' + ); + } + static generate(status, errorResponse, message, headers) { + if (!status) { + return new APIConnectionError({ cause: castToError(errorResponse) }); + } + const error = errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + this.status = undefined; + } +} +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + this.status = undefined; + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) this.cause = cause; + } +} +class APIConnectionTimeoutError extends APIConnectionError { + constructor() { + super({ message: 'Request timed out.' }); + } +} +class BadRequestError extends APIError { + constructor() { + super(...arguments); + this.status = 400; + } +} +class AuthenticationError extends APIError { + constructor() { + super(...arguments); + this.status = 401; + } +} +class PermissionDeniedError extends APIError { + constructor() { + super(...arguments); + this.status = 403; + } +} +class NotFoundError extends APIError { + constructor() { + super(...arguments); + this.status = 404; + } +} +class ConflictError extends APIError { + constructor() { + super(...arguments); + this.status = 409; + } +} +class UnprocessableEntityError extends APIError { + constructor() { + super(...arguments); + this.status = 422; + } +} +class RateLimitError extends APIError { + constructor() { + super(...arguments); + this.status = 429; + } +} +class InternalServerError extends APIError {} +//# sourceMappingURL=error.mjs.map + +// EXTERNAL MODULE: ./node_modules/agentkeepalive/index.js +var agentkeepalive = __webpack_require__(4623); +// EXTERNAL MODULE: ./node_modules/abort-controller/dist/abort-controller.js +var abort_controller = __webpack_require__(1659); +;// CONCATENATED MODULE: ./node_modules/openai/_shims/agent.node.mjs +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ + + +const defaultHttpAgent = new agentkeepalive({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent = new agentkeepalive.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +// Polyfill global object if needed. +if (typeof AbortController === 'undefined') { + AbortController = abort_controller.AbortController; +} +const getDefaultAgent = (url) => { + if (defaultHttpsAgent && url.startsWith('https')) return defaultHttpsAgent; + return defaultHttpAgent; +}; +//# sourceMappingURL=agent.node.mjs.map + +// EXTERNAL MODULE: ./node_modules/node-fetch/lib/index.js +var lib = __webpack_require__(467); +;// CONCATENATED MODULE: ./node_modules/openai/_shims/fetch.node.mjs +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ + + + +const _fetch = lib; +const _Request = lib.Request; +const _Response = lib.Response; +const _Headers = lib.Headers; + + + +const isPolyfilled = true; + +// EXTERNAL MODULE: external "util" +var external_util_ = __webpack_require__(3837); +;// CONCATENATED MODULE: ./node_modules/web-streams-polyfill/dist/ponyfill.mjs +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d(e){return s(e)}function f(e,t,r){return i.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,o)}function h(e,t){b(e,t)}function _(e,t){b(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,o)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class S{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),j(e)}(e):B(e,t._storedError)}function P(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function B(e,t){O(e),A(e,t)}function A(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function D(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function x(e){if(!r(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t)}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S}get closed(){return K(this)?this._closedPromise:d(ee("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(ee("cancel"))}read(){if(!K(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(k("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function K(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z(e,t){const r=e._readRequests;e._readRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d(k("iterate")):f(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ce(e){e._queue=new S,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,qe(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!fe(this))throw Be("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,qe(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return ke(this)}close(){if(!de(this))throw Ae("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Pe(e,t),t}}Ee(e),Xt(t)}(this)}enqueue(e){if(!de(this))throw Ae("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t)}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift())}}(e),0===X(r))me(e,i,n,a);else{e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1)}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e)}(this,e)}error(e){if(!de(this))throw Ae("error");Pe(this,e)}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}U(t,e),be(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S,this._pendingPullIntos.push(e)}}}function de(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(t)&&X(t)>0)return!0;if(Le(t)&&ze(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e)),null)),(t=>(Pe(e,t),null)))}function he(e){Re(e),e._pendingPullIntos=new S}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw Pe(e,t),t}me(e,n,0,o)}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Se(e,o,t),l-=o}return s}function Se(e,t,r){r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Xt(e._controlledReadableByteStream)):be(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t))}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e))}(e,r):function(e,t,r){if(Se(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o)}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e)}(e,t,r),be(e)}function Ce(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Pe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Ee(e),Jt(r,t))}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Oe(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new S,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Pe(t,e),null)))}(e,o,n,a,i,r,l)}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t)}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S}get closed(){return Fe(this)?this._closedPromise:d(De("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(De("cancel"))}read(e){if(!Fe(this))return d(De("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(k("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Pe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw De("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function Fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function De(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return I(e,t),t=>Y(e(t))}function Ne(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function xe(e,t,r){return I(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new S,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,$e(r,1),a)}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d(_t("abort"))}close(){return Ge(this)?Xe(this)?d(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d(new TypeError("Cannot close an already-closing stream")):Ke(this):d(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||et(e,t),a}function Ke(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t)}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&tt(e)}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new S,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)))}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&St(t,e._storedError)}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else{const t=e._storedError;Tt(this,t),wt(this,t)}var r}get closed(){return at(this)?this._closedPromise:d(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d(mt("abort"))}close(){if(!at(this))return d(mt("close"));const e=this._ownerWritableStream;return void 0===e?d(yt("close")):rt(e)?d(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?St(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return at(this)?void 0===this._ownerWritableStream?d(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(yt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(rt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ue(e,t,r)}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e))}dt(e)}(o,t,n),i}(this,e):d(mt("write"))}}function at(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e)}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this)}}function st(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();ut(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&vt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Ze(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t)}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t)}(r,t),null)))}(e,r)}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t)}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t)}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function wt(e,t){gt(e),St(e,t)}function St(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Tt(e,t){Rt(e),Ct(e,t)}function qt(e){Rt(e),Et(e)}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Pt="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Pt)?Pt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,w=!1,S=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e}));let E=Promise.resolve(void 0);return u(((P,W)=>{let k;function O(){if(w)return;const e=u(((e,t)=>{!function r(o){o?e():f(function(){if(w)return c(!0);return f(l.ready,(()=>f(i.read(),(e=>!!e.done||(E=l.write(e.value),m(E),!1)))))}(),r,t)}(!1)}));m(e)}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return w||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return S||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(k=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?k():a.addEventListener("abort",k)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==E)return e=E,p(E,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}w||(w=!0,q?o():h(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return S=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",k),e?W(t):P(void 0),null}w||(b(i.closed,B,A),b(l.closed,(function(){return S||(R="closed"),null}),j)),q?O():y((()=>{q=!0,g(),O()}))}))}function Ot(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function w(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else{let e;try{e=le(l)}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e)}return s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function S(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():w(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():w(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:S,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t)}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return p}const w=new ReadableStream({start(e){a=e},pull:m,cancel:y}),S=new ReadableStream({start(e){i=e},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[w,S]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw Dt("desiredSize");return Lt(this)}close(){if(!Bt(this))throw Dt("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t))}(this)}enqueue(e){if(!Bt(this))throw Dt("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw zt(e,t),t}try{ue(e,t,r)}catch(t){throw zt(e,t),t}}At(e)}(this,e)}error(e){if(!Bt(this))throw Dt("error");zt(this,e)}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r)}else U(t,e),At(this)}[C](){}}function Bt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return!1;if(!e._started)return!1;if(Ut(t)&&X(t)>0)return!0;if(Lt(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,At(e)),null)),(t=>(zt(e,t),null)))}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t))}function Lt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,At(t),null)),(e=>(zt(t,e),null)))}(e,n,a,i,l,r,o)}function Dt(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return I(e,r),r=>w(e,t,[r])}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function xt(e,t){F(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Oe(this,o,$e(r,0))}else{const e=Me(r);It(this,o,$e(r,1),e)}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d(Kt("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Ot(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){F(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Vt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new S,e.forEach((e=>{e._closeSteps(void 0)}))}return p(e._readableStreamController[T](r),t)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new S,e.forEach((e=>{e._closeSteps()}))}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A(r,t),K(r)?Z(r,t):Ie(r,t))}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Zt(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream.prototype,e.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Zt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!rr(this))throw tr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rr(this))throw tr("size");return er}}function tr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function rr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const or=()=>1;n(or,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Zt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ar(this))throw nr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ar(this))throw nr("size");return or}}function nr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function ir(e,t,r){return I(e,r),r=>w(e,t,[r])}function lr(e,t,r){return I(e,r),r=>g(e,t,[r])}function sr(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ye(t,"Second parameter"),n=Ye(r,"Third parameter"),a=function(e,t){F(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ir(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:lr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:sr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=$e(n,0),l=Me(n),s=$e(o,1),f=Me(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{if("erroring"===(Ge(e._writable)?e._writable._state:e._writableState))throw Ge(e._writable)?e._writable._storedError:e._writableStoredError;return pr(r,t)}))}return pr(r,t)}(e,t)}function s(t){return function(e,t){return cr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return hr(t),p(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;gr(e)&&wr(e)}),(t=>{throw cr(e,t),e._readableStoredError}))}(e)}function d(){return function(e){return fr(e,!1),e._backpressureChangePromise}(e)}function f(t){return dr(e,t),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return p(t(),(()=>(e._writableStarted=!0,Cr(e),null)),(t=>{throw e._writableStarted=!0,Rr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),p(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Cr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Rr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),p(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Rr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{Sr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{Sr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fr(e,!0),e._transformStreamController=void 0}(this,u((e=>{b=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return _r(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!ur(this))throw yr("readable");return this._readable}get writable(){if(!ur(this))throw yr("writable");return this._writable}}function ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function cr(e,t){Sr(e,t),dr(e,t)}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t)}(e,t),e._backpressure&&fr(e,!1)}function fr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStream.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e)}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t)}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&wr(t);const r=new TypeError("TransformStream terminated");dr(t,r)}(this)}}function br(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw Sr(e,t),t}}(r,t)}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!gr(e))return!1;if(e._readablePulling)return!0;if(vr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&fr(r,!0)}function pr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw cr(e._controlledTransformStream,t),t}))}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function yr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function gr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Sr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function vr(e){return e._readableController.desiredSize}function Rr(e,t){"writable"!==e._writableState?qr(e):Tr(e,t)}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e)}function qr(e){e._writableState="errored"}function Cr(e){"erroring"===e._writableState&&qr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}); + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js +const isFunction = (value) => (typeof value === "function"); + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/blobHelpers.js +/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ + +const CHUNK_SIZE = 65536; +async function* clonePart(part) { + const end = part.byteOffset + part.byteLength; + let position = part.byteOffset; + while (position !== end) { + const size = Math.min(end - position, CHUNK_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } +} +async function* consumeNodeBlob(blob) { + let position = 0; + while (position !== blob.size) { + const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } +} +async function* consumeBlobParts(parts, clone = false) { + for (const part of parts) { + if (ArrayBuffer.isView(part)) { + if (clone) { + yield* clonePart(part); + } + else { + yield part; + } + } + else if (isFunction(part.stream)) { + yield* part.stream(); + } + else { + yield* consumeNodeBlob(part); + } + } +} +function* sliceBlob(blobParts, blobSize, start = 0, end) { + end !== null && end !== void 0 ? end : (end = blobSize); + let relativeStart = start < 0 + ? Math.max(blobSize + start, 0) + : Math.min(start, blobSize); + let relativeEnd = end < 0 + ? Math.max(blobSize + end, 0) + : Math.min(end, blobSize); + const span = Math.max(relativeEnd - relativeStart, 0); + let added = 0; + for (const part of blobParts) { + if (added >= span) { + break; + } + const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && partSize <= relativeStart) { + relativeStart -= partSize; + relativeEnd -= partSize; + } + else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd)); + added += chunk.byteLength; + } + else { + chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd)); + added += chunk.size; + } + relativeEnd -= partSize; + relativeStart = 0; + yield chunk; + } + } +} + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/Blob.js +/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ +var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _Blob_parts, _Blob_type, _Blob_size; + + + +class Blob { + constructor(blobParts = [], options = {}) { + _Blob_parts.set(this, []); + _Blob_type.set(this, ""); + _Blob_size.set(this, 0); + options !== null && options !== void 0 ? options : (options = {}); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': " + + "The provided value cannot be converted to a sequence."); + } + if (!isFunction(blobParts[Symbol.iterator])) { + throw new TypeError("Failed to construct 'Blob': " + + "The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && !isFunction(options)) { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + const encoder = new TextEncoder(); + for (const raw of blobParts) { + let part; + if (ArrayBuffer.isView(raw)) { + part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); + } + else if (raw instanceof ArrayBuffer) { + part = new Uint8Array(raw.slice(0)); + } + else if (raw instanceof Blob) { + part = raw; + } + else { + part = encoder.encode(String(raw)); + } + __classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f"); + __classPrivateFieldGet(this, _Blob_parts, "f").push(part); + } + const type = options.type === undefined ? "" : String(options.type); + __classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f"); + } + static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) { + return Boolean(value + && typeof value === "object" + && isFunction(value.constructor) + && (isFunction(value.stream) + || isFunction(value.arrayBuffer)) + && /^(Blob|File)$/.test(value[Symbol.toStringTag])); + } + get type() { + return __classPrivateFieldGet(this, _Blob_type, "f"); + } + get size() { + return __classPrivateFieldGet(this, _Blob_size, "f"); + } + slice(start, end, contentType) { + return new Blob(sliceBlob(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), { + type: contentType + }); + } + async text() { + const decoder = new TextDecoder(); + let result = ""; + for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { + result += decoder.decode(chunk, { stream: true }); + } + result += decoder.decode(); + return result; + } + async arrayBuffer() { + const view = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { + view.set(chunk, offset); + offset += chunk.length; + } + return view.buffer; + } + stream() { + const iterator = consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"), true); + return new ReadableStream({ + async pull(controller) { + const { value, done } = await iterator.next(); + if (done) { + return queueMicrotask(() => controller.close()); + } + controller.enqueue(value); + }, + async cancel() { + await iterator.return(); + } + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } +} +Object.defineProperties(Blob.prototype, { + type: { enumerable: true }, + size: { enumerable: true }, + slice: { enumerable: true }, + stream: { enumerable: true }, + text: { enumerable: true }, + arrayBuffer: { enumerable: true } +}); + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/File.js +var File_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var File_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _File_name, _File_lastModified; + +class File extends Blob { + constructor(fileBits, name, options = {}) { + super(fileBits, options); + _File_name.set(this, void 0); + _File_lastModified.set(this, 0); + if (arguments.length < 2) { + throw new TypeError("Failed to construct 'File': 2 arguments required, " + + `but only ${arguments.length} present.`); + } + File_classPrivateFieldSet(this, _File_name, String(name), "f"); + const lastModified = options.lastModified === undefined + ? Date.now() + : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + File_classPrivateFieldSet(this, _File_lastModified, lastModified, "f"); + } + } + static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) { + return value instanceof Blob + && value[Symbol.toStringTag] === "File" + && typeof value.name === "string"; + } + get name() { + return File_classPrivateFieldGet(this, _File_name, "f"); + } + get lastModified() { + return File_classPrivateFieldGet(this, _File_lastModified, "f"); + } + get webkitRelativePath() { + return ""; + } + get [Symbol.toStringTag]() { + return "File"; + } +} + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isFile.js + +const isFile = (value) => value instanceof File; + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isBlob.js + +const isBlob = (value) => value instanceof Blob; + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js + +const deprecateConstructorEntries = (0,external_util_.deprecate)(() => { }, "Constructor \"entries\" argument is not spec-compliant " + + "and will be removed in next major release."); + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/FormData.js +var FormData_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _FormData_instances, _FormData_entries, _FormData_setEntry; + + + + + + +class FormData { + constructor(entries) { + _FormData_instances.add(this); + _FormData_entries.set(this, new Map()); + if (entries) { + deprecateConstructorEntries(); + entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName)); + } + } + static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) { + return Boolean(value + && isFunction(value.constructor) + && value[Symbol.toStringTag] === "FormData" + && isFunction(value.append) + && isFunction(value.set) + && isFunction(value.get) + && isFunction(value.getAll) + && isFunction(value.has) + && isFunction(value.delete) + && isFunction(value.entries) + && isFunction(value.values) + && isFunction(value.keys) + && isFunction(value[Symbol.iterator]) + && isFunction(value.forEach)); + } + append(name, value, fileName) { + FormData_classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { + name, + fileName, + append: true, + rawValue: value, + argsLength: arguments.length + }); + } + set(name, value, fileName) { + FormData_classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { + name, + fileName, + append: false, + rawValue: value, + argsLength: arguments.length + }); + } + get(name) { + const field = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); + if (!field) { + return null; + } + return field[0]; + } + getAll(name) { + const field = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); + if (!field) { + return []; + } + return field.slice(); + } + has(name) { + return FormData_classPrivateFieldGet(this, _FormData_entries, "f").has(String(name)); + } + delete(name) { + FormData_classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name)); + } + *keys() { + for (const key of FormData_classPrivateFieldGet(this, _FormData_entries, "f").keys()) { + yield key; + } + } + *entries() { + for (const name of this.keys()) { + const values = this.getAll(name); + for (const value of values) { + yield [name, value]; + } + } + } + *values() { + for (const [, value] of this) { + yield value; + } + } + [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) { + const methodName = append ? "append" : "set"; + if (argsLength < 2) { + throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` + + `2 arguments required, but only ${argsLength} present.`); + } + name = String(name); + let value; + if (isFile(rawValue)) { + value = fileName === undefined + ? rawValue + : new File([rawValue], fileName, { + type: rawValue.type, + lastModified: rawValue.lastModified + }); + } + else if (isBlob(rawValue)) { + value = new File([rawValue], fileName === undefined ? "blob" : fileName, { + type: rawValue.type + }); + } + else if (fileName) { + throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` + + "parameter 2 is not of type 'Blob'."); + } + else { + value = String(rawValue); + } + const values = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(name); + if (!values) { + return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); + } + if (!append) { + return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); + } + values.push(value); + }, Symbol.iterator)]() { + return this.entries(); + } + forEach(callback, thisArg) { + for (const [name, value] of this) { + callback.call(thisArg, value, name, this); + } + } + get [Symbol.toStringTag]() { + return "FormData"; + } + [external_util_.inspect.custom]() { + return this[Symbol.toStringTag]; + } +} + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/index.js + + + + +;// CONCATENATED MODULE: ./node_modules/openai/_shims/formdata.node.mjs +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ + + + + + +const formdata_node_isPolyfilled = true; + +// EXTERNAL MODULE: external "node:stream" +var external_node_stream_ = __webpack_require__(4492); +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/createBoundary.js +const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; +function createBoundary() { + let size = 16; + let res = ""; + while (size--) { + res += alphabet[(Math.random() * alphabet.length) << 0]; + } + return res; +} +/* harmony default export */ const util_createBoundary = (createBoundary); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isPlainObject.js +const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); +function isPlainObject(value) { + if (getType(value) !== "object") { + return false; + } + const pp = Object.getPrototypeOf(value); + if (pp === null || pp === undefined) { + return true; + } + const Ctor = pp.constructor && pp.constructor.toString(); + return Ctor === Object.toString(); +} +/* harmony default export */ const util_isPlainObject = (isPlainObject); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/normalizeValue.js +const normalizeValue = (value) => String(value) + .replace(/\r|\n/g, (match, i, str) => { + if ((match === "\r" && str[i + 1] !== "\n") + || (match === "\n" && str[i - 1] !== "\r")) { + return "\r\n"; + } + return match; +}); +/* harmony default export */ const util_normalizeValue = (normalizeValue); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/escapeName.js +const escapeName = (name) => String(name) + .replace(/\r/g, "%0D") + .replace(/\n/g, "%0A") + .replace(/"/g, "%22"); +/* harmony default export */ const util_escapeName = (escapeName); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFunction.js +const isFunction_isFunction = (value) => (typeof value === "function"); +/* harmony default export */ const util_isFunction = (isFunction_isFunction); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFileLike.js + +const isFileLike = (value) => Boolean(value + && typeof value === "object" + && util_isFunction(value.constructor) + && value[Symbol.toStringTag] === "File" + && util_isFunction(value.stream) + && value.name != null + && value.size != null + && value.lastModified != null); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFormData.js + +const isFormData = (value) => Boolean(value + && util_isFunction(value.constructor) + && value[Symbol.toStringTag] === "FormData" + && util_isFunction(value.append) + && util_isFunction(value.getAll) + && util_isFunction(value.entries) + && util_isFunction(value[Symbol.iterator])); +const isFormDataLike = (/* unused pure expression or super */ null && (isFormData)); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/FormDataEncoder.js +var FormDataEncoder_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var FormDataEncoder_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader; + + + + + + +const defaultOptions = { + enableAdditionalHeaders: false +}; +class FormDataEncoder { + constructor(form, boundaryOrOptions, options) { + _FormDataEncoder_instances.add(this); + _FormDataEncoder_CRLF.set(this, "\r\n"); + _FormDataEncoder_CRLF_BYTES.set(this, void 0); + _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0); + _FormDataEncoder_DASHES.set(this, "-".repeat(2)); + _FormDataEncoder_encoder.set(this, new TextEncoder()); + _FormDataEncoder_footer.set(this, void 0); + _FormDataEncoder_form.set(this, void 0); + _FormDataEncoder_options.set(this, void 0); + if (!isFormData(form)) { + throw new TypeError("Expected first argument to be a FormData instance."); + } + let boundary; + if (util_isPlainObject(boundaryOrOptions)) { + options = boundaryOrOptions; + } + else { + boundary = boundaryOrOptions; + } + if (!boundary) { + boundary = util_createBoundary(); + } + if (typeof boundary !== "string") { + throw new TypeError("Expected boundary argument to be a string."); + } + if (options && !util_isPlainObject(options)) { + throw new TypeError("Expected options argument to be an object."); + } + FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_form, form, "f"); + FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f"); + FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")), "f"); + FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f"); + this.boundary = `form-data-boundary-${boundary}`; + this.contentType = `multipart/form-data; boundary=${this.boundary}`; + FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_footer, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f"); + this.contentLength = String(this.getContentLength()); + this.headers = Object.freeze({ + "Content-Type": this.contentType, + "Content-Length": this.contentLength + }); + Object.defineProperties(this, { + boundary: { writable: false, configurable: false }, + contentType: { writable: false, configurable: false }, + contentLength: { writable: false, configurable: false }, + headers: { writable: false, configurable: false } + }); + } + getContentLength() { + let length = 0; + for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f")) { + const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); + length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength; + length += isFileLike(value) ? value.size : value.byteLength; + length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f"); + } + return length + FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f").byteLength; + } + *values() { + for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f").entries()) { + const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); + yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value); + yield value; + yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f"); + } + yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f"); + } + async *encode() { + for (const part of this.values()) { + if (isFileLike(part)) { + yield* part.stream(); + } + else { + yield part; + } + } + } + [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) { + let header = ""; + header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; + header += `Content-Disposition: form-data; name="${util_escapeName(name)}"`; + if (isFileLike(value)) { + header += `; filename="${util_escapeName(value.name)}"${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; + header += `Content-Type: ${value.type || "application/octet-stream"}`; + } + if (FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) { + header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike(value) ? value.size : value.byteLength}`; + } + return FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${header}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`); + }, Symbol.iterator)]() { + return this.values(); + } + [Symbol.asyncIterator]() { + return this.encode(); + } +} +const Encoder = (/* unused pure expression or super */ null && (FormDataEncoder)); + +;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/index.js + + + + + + +;// CONCATENATED MODULE: ./node_modules/openai/_shims/getMultipartRequestOptions.node.mjs +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ + + + +async function getMultipartRequestOptions_node_getMultipartRequestOptions(form, opts) { + const encoder = new FormDataEncoder(form); + const readable = external_node_stream_.Readable.from(encoder); + const body = new MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + return { ...opts, body: body, headers }; +} +//# sourceMappingURL=getMultipartRequestOptions.node.mjs.map + +// EXTERNAL MODULE: external "fs" +var external_fs_ = __webpack_require__(7147); +// EXTERNAL MODULE: external "path" +var external_path_ = __webpack_require__(1017); +// EXTERNAL MODULE: ./node_modules/node-domexception/index.js +var node_domexception = __webpack_require__(7760); +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isPlainObject.js +const isPlainObject_getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); +function isPlainObject_isPlainObject(value) { + if (isPlainObject_getType(value) !== "object") { + return false; + } + const pp = Object.getPrototypeOf(value); + if (pp === null || pp === undefined) { + return true; + } + const Ctor = pp.constructor && pp.constructor.toString(); + return Ctor === Object.toString(); +} +/* harmony default export */ const esm_isPlainObject = (isPlainObject_isPlainObject); + +;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/fileFromPath.js +var fileFromPath_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var fileFromPath_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _FileFromPath_path, _FileFromPath_start; + + + + + + +const MESSAGE = "The requested file could not be read, " + + "typically due to permission problems that have occurred after a reference " + + "to a file was acquired."; +class FileFromPath { + constructor(input) { + _FileFromPath_path.set(this, void 0); + _FileFromPath_start.set(this, void 0); + fileFromPath_classPrivateFieldSet(this, _FileFromPath_path, input.path, "f"); + fileFromPath_classPrivateFieldSet(this, _FileFromPath_start, input.start || 0, "f"); + this.name = (0,external_path_.basename)(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f")); + this.size = input.size; + this.lastModified = input.lastModified; + } + slice(start, end) { + return new FileFromPath({ + path: fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"), + lastModified: this.lastModified, + size: end - start, + start + }); + } + async *stream() { + const { mtimeMs } = await external_fs_.promises.stat(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f")); + if (mtimeMs > this.lastModified) { + throw new node_domexception(MESSAGE, "NotReadableError"); + } + if (this.size) { + yield* (0,external_fs_.createReadStream)(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"), { + start: fileFromPath_classPrivateFieldGet(this, _FileFromPath_start, "f"), + end: fileFromPath_classPrivateFieldGet(this, _FileFromPath_start, "f") + this.size - 1 + }); + } + } + get [(_FileFromPath_path = new WeakMap(), _FileFromPath_start = new WeakMap(), Symbol.toStringTag)]() { + return "File"; + } +} +function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) { + let filename; + if (esm_isPlainObject(filenameOrOptions)) { + [options, filename] = [filenameOrOptions, undefined]; + } + else { + filename = filenameOrOptions; + } + const file = new FileFromPath({ path, size, lastModified: mtimeMs }); + if (!filename) { + filename = file.name; + } + return new File([file], filename, { + ...options, lastModified: file.lastModified + }); +} +function fileFromPathSync(path, filenameOrOptions, options = {}) { + const stats = statSync(path); + return createFileFromPath(path, stats, filenameOrOptions, options); +} +async function fileFromPath(path, filenameOrOptions, options) { + const stats = await external_fs_.promises.stat(path); + return createFileFromPath(path, stats, filenameOrOptions, options); +} + +;// CONCATENATED MODULE: ./node_modules/openai/_shims/fileFromPath.node.mjs +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ + +let warned = false; +async function fileFromPath_node_fileFromPath(path, ...args) { + if (!warned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + warned = true; + } + return await fileFromPath(path, ...args); +} +//# sourceMappingURL=fileFromPath.node.mjs.map + +// EXTERNAL MODULE: external "node:fs" +var external_node_fs_ = __webpack_require__(7561); +;// CONCATENATED MODULE: ./node_modules/openai/_shims/node-readable.node.mjs + +function isFsReadStream(value) { + return value instanceof external_node_fs_.ReadStream; +} +//# sourceMappingURL=node-readable.node.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/uploads.mjs + + + + + +const isResponseLike = (value) => + value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +const uploads_isFileLike = (value) => + value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); +/** + * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check + * adds the arrayBuffer() method type because it is available and used at runtime + */ +const isBlobLike = (value) => + value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +const isUploadable = (value) => { + return uploads_isFileLike(value) || isResponseLike(value) || isFsReadStream(value); +}; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function toFile(value, name, options = {}) { + var _a, _b, _c; + // If it's a promise, resolve it. + value = await value; + if (isResponseLike(value)) { + const blob = await value.blob(); + name || + (name = + (_a = new URL(value.url).pathname.split(/[\\/]/).pop()) !== null && _a !== void 0 ? + _a + : 'unknown_file'); + return new File([blob], name, options); + } + const bits = await getBytes(value); + name || (name = (_b = getName(value)) !== null && _b !== void 0 ? _b : 'unknown_file'); + if (!options.type) { + const type = (_c = bits[0]) === null || _c === void 0 ? void 0 : _c.type; + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return new File(bits, name, options); +} +async function getBytes(value) { + var _a; + let parts = []; + if ( + typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer + ) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(await value.arrayBuffer()); + } else if ( + isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(chunk); // TODO, consider validating? + } + } else { + throw new Error( + `Unexpected data type: ${typeof value}; constructor: ${ + (_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? + void 0 + : _a.name + }; props: ${propsForError(value)}`, + ); + } + return parts; +} +function propsForError(value) { + const props = Object.getOwnPropertyNames(value); + return `[${props.map((p) => `"${p}"`).join(', ')}]`; +} +function getName(value) { + var _a; + return ( + getStringFromMaybeBuffer(value.name) || + getStringFromMaybeBuffer(value.filename) || + // For fs.ReadStream + ((_a = getStringFromMaybeBuffer(value.path)) === null || _a === void 0 ? void 0 : _a.split(/[\\/]/).pop()) + ); +} +const getStringFromMaybeBuffer = (x) => { + if (typeof x === 'string') return x; + if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x); + return undefined; +}; +const isAsyncIterableIterator = (value) => + value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +class MultipartBody { + constructor(body) { + this.body = body; + } + get [Symbol.toStringTag]() { + return 'MultipartBody'; + } +} +const isMultipartBody = (body) => + body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +const maybeMultipartFormRequestOptions = async (opts) => { + if (!hasUploadableValue(opts.body)) return opts; + const form = await createForm(opts.body); + return getMultipartRequestOptions(form, opts); +}; +const multipartFormRequestOptions = async (opts) => { + const form = await createForm(opts.body); + return getMultipartRequestOptions_node_getMultipartRequestOptions(form, opts); +}; +const createForm = async (body) => { + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +const hasUploadableValue = (value) => { + if (isUploadable(value)) return true; + if (Array.isArray(value)) return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) return true; + } + } + return false; +}; +const addFormValue = async (form, key, value) => { + if (value === undefined) return; + if (value == null) { + throw new TypeError( + `Received null for "${key}"; to pass null in FormData, you must use the string 'null'`, + ); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } else if (isUploadable(value)) { + const file = await toFile(value); + form.append(key, file); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } else if (typeof value === 'object') { + await Promise.all( + Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)), + ); + } else { + throw new TypeError( + `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`, + ); + } +}; +//# sourceMappingURL=uploads.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/core.mjs +var core_classPrivateFieldSet = + (undefined && undefined.__classPrivateFieldSet) || + function (receiver, state, value, kind, f) { + if (kind === 'm') throw new TypeError('Private method is not writable'); + if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a setter'); + 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'); + return ( + kind === 'a' ? f.call(receiver, value) + : f ? (f.value = value) + : state.set(receiver, value), + value + ); + }; +var core_classPrivateFieldGet = + (undefined && undefined.__classPrivateFieldGet) || + function (receiver, state, kind, f) { + if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter'); + 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'); + return ( + kind === 'm' ? f + : kind === 'a' ? f.call(receiver) + : f ? f.value + : state.get(receiver) + ); + }; +var _AbstractPage_client; + + + + + + + +const MAX_RETRIES = 2; +async function defaultParseResponse(props) { + const { response } = props; + if (props.options.stream) { + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + return new Stream(response, props.controller); + } + const contentType = response.headers.get('content-type'); + if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { + const json = await response.json(); + debug('response', response.status, response.url, response.headers, json); + return json; + } + // TODO handle blob, arraybuffer, other content types, etc. + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + return text; +} +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class APIPromise extends Promise { + constructor(responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + } + _thenUnwrap(transform) { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +class APIClient { + constructor({ + baseURL, + maxRetries, + timeout = 600000, // 10 minutes + httpAgent, + fetch: overridenFetch, + }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger( + 'maxRetries', + maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES, + ); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : _fetch; + } + authHeaders(opts) { + return {}; + } + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + defaultHeaders(opts) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + /** + * Override this to add your own headers validation: + */ + validateHeaders(headers, customHeaders) {} + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + calculateContentLength(body) { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } + } + return null; + } + buildRequest(options) { + var _a, _b, _c, _d, _e, _f; + const { method, path, query, headers: headers = {} } = options; + const body = + isMultipartBody(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + const url = this.buildURL(path, query); + if ('timeout' in options) validatePositiveInteger('timeout', options.timeout); + const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout; + const httpAgent = + ( + (_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null && + _c !== void 0 + ) ? + _c + : getDefaultAgent(url); + const minAgentTimeout = timeout + 1000; + if ( + typeof (( + (_d = httpAgent === null || httpAgent === void 0 ? void 0 : httpAgent.options) === null || + _d === void 0 + ) ? + void 0 + : _d.timeout) === 'number' && + minAgentTimeout > ((_e = httpAgent.options.timeout) !== null && _e !== void 0 ? _e : 0) + ) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + httpAgent.options.timeout = minAgentTimeout; + } + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; + } + const reqHeaders = { + ...(contentLength && { 'Content-Length': contentLength }), + ...this.defaultHeaders(options), + ...headers, + }; + // let builtin fetch set the Content-Type for multipart bodies + if (isMultipartBody(options.body) && !isPolyfilled) { + delete reqHeaders['Content-Type']; + } + // Strip any headers being explicitly omitted with null + Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]); + const req = { + method, + ...(body && { body: body }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: (_f = options.signal) !== null && _f !== void 0 ? _f : null, + }; + this.validateHeaders(reqHeaders, headers); + return { req, url, timeout }; + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) {} + parseHeaders(headers) { + return ( + !headers ? {} + : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) + : { ...headers } + ); + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + request(options, remainingRetries = null) { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + async makeRequest(optionsInput, retriesRemaining) { + var _a, _b, _c; + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries; + } + const { req, url, timeout } = this.buildRequest(options); + await this.prepareRequest(req, { url, options }); + debug('request', url, options, req.headers); + if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + if (response instanceof Error) { + if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) { + throw new APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const responseHeaders = createResponseHeaders(response.headers); + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + const errText = await response.text().catch(() => 'Unknown'); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + debug('response', response.status, url, responseHeaders, errMessage); + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; + } + return { response, options, controller }; + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + buildURL(path, query) { + const url = + isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (query) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new Error( + `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`, + ); + }) + .join('&'); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, ...options } = init || {}; + if (signal) signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + return this.getRequestClient() + .fetch(url, { signal: controller.signal, ...options }) + .finally(() => { + clearTimeout(timeout); + }); + } + getRequestClient() { + return { fetch: this.fetch }; + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') return true; + if (shouldRetryHeader === 'false') return false; + // Retry on lock timeouts. + if (response.status === 409) return true; + // Retry on rate limits. + if (response.status === 429) return true; + // Retry internal errors. + if (response.status >= 500) return true; + return false; + } + async retryRequest(options, retriesRemaining, responseHeaders) { + var _a; + retriesRemaining -= 1; + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + // + // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: ". + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details. + const retryAfter = parseInt( + (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) || + '', + ); + const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries; + const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000; + await sleep(timeout); + return this.makeRequest(options, retriesRemaining); + } + calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 2; + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says. + if (Number.isInteger(retryAfter) && retryAfter <= 60) { + return retryAfter; + } + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay); + // Apply some jitter, plus-or-minus half a second. + const jitter = Math.random() - 0.5; + return sleepSeconds + jitter; + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } +} +class APIResource { + constructor(client) { + this.client = client; + this.get = client.get.bind(client); + this.post = client.post.bind(client); + this.patch = client.patch.bind(client); + this.put = client.put.bind(client); + this.delete = client.delete.bind(client); + this.getAPIList = client.getAPIList.bind(client); + } +} +class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + core_classPrivateFieldSet(this, _AbstractPage_client, client, 'f'); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) return false; + return this.nextPageInfo() != null; + } + async getNextPage() { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new Error( + 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.', + ); + } + const nextOptions = { ...this.options }; + if ('params' in nextInfo) { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); + } + return await core_classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList( + this.constructor, + nextOptions, + ); + } + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class PagePromise extends APIPromise { + constructor(client, request, Page) { + super( + request, + async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options), + ); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +const createResponseHeaders = (headers) => { + return new Proxy( + Object.fromEntries( + // @ts-ignore + headers.entries(), + ), + { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }, + ); +}; +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys = { + method: true, + path: true, + query: true, + body: true, + headers: true, + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, +}; +const isRequestOptions = (obj) => { + return ( + typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)) + ); +}; +const getPlatformProperties = () => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': Deno.version, + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') return 'x32'; + if (arch === 'x86_64' || arch === 'x64') return 'x64'; + if (arch === 'arm') return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') return 'arm64'; + if (arch) return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) return 'iOS'; + if (platform === 'android') return 'Android'; + if (platform === 'darwin') return 'MacOS'; + if (platform === 'win32') return 'Windows'; + if (platform === 'freebsd') return 'FreeBSD'; + if (platform === 'openbsd') return 'OpenBSD'; + if (platform === 'linux') return 'Linux'; + if (platform) return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return _platformHeaders !== null && _platformHeaders !== void 0 ? + _platformHeaders + : (_platformHeaders = getPlatformProperties()); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return undefined; + } +}; +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new Error(`${name} must be an integer`); + } + if (n < 0) { + throw new Error(`${name} must be a positive integer`); + } + return n; +}; +const castToError = (err) => { + if (err instanceof Error) return err; + return new Error(err); +}; +const ensurePresent = (value) => { + if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`); + return value; +}; +/** + * Read an environment variable. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + var _a, _b, _c, _d; + if (typeof process !== 'undefined') { + return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ? + _b + : undefined; + } + if (typeof Deno !== 'undefined') { + return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ? + void 0 + : _d.call(_c, env); + } + return undefined; +}; +const coerceInteger = (value) => { + if (typeof value === 'number') return Math.round(value); + if (typeof value === 'string') return parseInt(value, 10); + throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const coerceFloat = (value) => { + if (typeof value === 'number') return value; + if (typeof value === 'string') return parseFloat(value); + throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') return value; + if (typeof value === 'string') return value === 'true'; + return Boolean(value); +}; +const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; + } + return coerceInteger(value); +}; +const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return coerceFloat(value); +}; +const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return coerceBoolean(value); +}; +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) return true; + for (const _k in obj) return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function debug(action, ...args) { + if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } +} +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined' + ); +}; +const isHeadersProtocol = (headers) => { + return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function'; +}; +const getHeader = (headers, key) => { + const lowerKey = key.toLowerCase(); + if (isHeadersProtocol(headers)) return headers.get(key) || headers.get(lowerKey); + const value = headers[key] || headers[lowerKey]; + if (Array.isArray(value)) { + if (value.length <= 1) return value[0]; + console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`); + return value[0]; + } + return value; +}; +/** + * Encodes a string to Base64 format. + */ +const toBase64 = (str) => { + if (!str) return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + if (typeof btoa !== 'undefined') { + return btoa(str); + } + throw new Error('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; +//# sourceMappingURL=core.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/pagination.mjs +// File generated from our OpenAPI spec by Stainless. + +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class Page extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.object = body.object; + this.data = body.data; + } + getPaginatedItems() { + return this.data; + } + // @deprecated Please use `nextPageInfo()` instead + /** + * This page represents a response that isn't actually paginated at the API level + * so there will never be any next page params. + */ + nextPageParams() { + return null; + } + nextPageInfo() { + return null; + } +} +class CursorPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data; + } + getPaginatedItems() { + return this.data; + } + // @deprecated Please use `nextPageInfo()` instead + nextPageParams() { + const info = this.nextPageInfo(); + if (!info) return null; + if ('params' in info) return info.params; + const params = Object.fromEntries(info.url.searchParams); + if (!Object.keys(params).length) return null; + return params; + } + nextPageInfo() { + var _a, _b; + if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.length)) { + return null; + } + const next = (_b = this.data[this.data.length - 1]) === null || _b === void 0 ? void 0 : _b.id; + if (!next) return null; + return { params: { after: next } }; + } +} +//# sourceMappingURL=pagination.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resource.mjs +// File generated from our OpenAPI spec by Stainless. +class resource_APIResource { + constructor(client) { + this.client = client; + this.get = client.get.bind(client); + this.post = client.post.bind(client); + this.patch = client.patch.bind(client); + this.put = client.put.bind(client); + this.delete = client.delete.bind(client); + this.getAPIList = client.getAPIList.bind(client); + } +} +//# sourceMappingURL=resource.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs +// File generated from our OpenAPI spec by Stainless. + + +class Transcriptions extends resource_APIResource { + /** + * Transcribes audio into the input language. + */ + create(body, options) { + return this.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options })); + } +} +(function (Transcriptions) {})(Transcriptions || (Transcriptions = {})); +//# sourceMappingURL=transcriptions.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs +// File generated from our OpenAPI spec by Stainless. + + +class Translations extends resource_APIResource { + /** + * Translates audio into English. + */ + create(body, options) { + return this.post('/audio/translations', multipartFormRequestOptions({ body, ...options })); + } +} +(function (Translations) {})(Translations || (Translations = {})); +//# sourceMappingURL=translations.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/index.mjs +// File generated from our OpenAPI spec by Stainless. + + + +//# sourceMappingURL=index.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs +// File generated from our OpenAPI spec by Stainless. + + + + +class Audio extends resource_APIResource { + constructor() { + super(...arguments); + this.transcriptions = new Transcriptions(this.client); + this.translations = new Translations(this.client); + } +} +(function (Audio) { + Audio.Transcriptions = Transcriptions; + Audio.Translations = Translations; +})(Audio || (Audio = {})); +//# sourceMappingURL=audio.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions.mjs +// File generated from our OpenAPI spec by Stainless. + +class Completions extends resource_APIResource { + create(body, options) { + var _a; + return this.post('/chat/completions', { + body, + ...options, + stream: (_a = body.stream) !== null && _a !== void 0 ? _a : false, + }); + } +} +(function (Completions) {})(Completions || (Completions = {})); +//# sourceMappingURL=completions.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs +// File generated from our OpenAPI spec by Stainless. + + +//# sourceMappingURL=index.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs +// File generated from our OpenAPI spec by Stainless. + + + +class Chat extends resource_APIResource { + constructor() { + super(...arguments); + this.completions = new Completions(this.client); + } +} +(function (Chat) { + Chat.Completions = Completions; +})(Chat || (Chat = {})); +//# sourceMappingURL=chat.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs +// File generated from our OpenAPI spec by Stainless. + +class completions_Completions extends resource_APIResource { + create(body, options) { + var _a; + return this.post('/completions', { + body, + ...options, + stream: (_a = body.stream) !== null && _a !== void 0 ? _a : false, + }); + } +} +(function (Completions) {})(completions_Completions || (completions_Completions = {})); +//# sourceMappingURL=completions.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs +// File generated from our OpenAPI spec by Stainless. + +class Embeddings extends resource_APIResource { + /** + * Creates an embedding vector representing the input text. + */ + create(body, options) { + return this.post('/embeddings', { body, ...options }); + } +} +(function (Embeddings) {})(Embeddings || (Embeddings = {})); +//# sourceMappingURL=embeddings.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/edits.mjs +// File generated from our OpenAPI spec by Stainless. + +class Edits extends resource_APIResource { + /** + * Creates a new edit for the provided input, instruction, and parameters. + * + * @deprecated The Edits API is deprecated; please use Chat Completions instead. + * + * https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api + */ + create(body, options) { + return this.post('/edits', { body, ...options }); + } +} +(function (Edits) {})(Edits || (Edits = {})); +//# sourceMappingURL=edits.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs +// File generated from our OpenAPI spec by Stainless. + + + +class Files extends resource_APIResource { + /** + * Upload a file that contains document(s) to be used across various + * endpoints/features. Currently, the size of all the files uploaded by one + * organization can be up to 1 GB. Please contact us if you need to increase the + * storage limit. + */ + create(body, options) { + return this.post('/files', multipartFormRequestOptions({ body, ...options })); + } + /** + * Returns information about a specific file. + */ + retrieve(fileId, options) { + return this.get(`/files/${fileId}`, options); + } + /** + * Returns a list of files that belong to the user's organization. + */ + list(options) { + return this.getAPIList('/files', FileObjectsPage, options); + } + /** + * Delete a file. + */ + del(fileId, options) { + return this.delete(`/files/${fileId}`, options); + } + /** + * Returns the contents of the specified file + */ + retrieveContent(fileId, options) { + return this.get(`/files/${fileId}/content`, { + ...options, + headers: { + Accept: 'application/json', + ...(options === null || options === void 0 ? void 0 : options.headers), + }, + }); + } +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class FileObjectsPage extends Page {} +(function (Files) {})(Files || (Files = {})); +//# sourceMappingURL=files.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tunes.mjs +// File generated from our OpenAPI spec by Stainless. + + +class FineTunes extends resource_APIResource { + /** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/legacy-fine-tuning) + */ + create(body, options) { + return this.post('/fine-tunes', { body, ...options }); + } + /** + * Gets info about the fine-tune job. + * + * [Learn more about fine-tuning](/docs/guides/legacy-fine-tuning) + */ + retrieve(fineTuneId, options) { + return this.get(`/fine-tunes/${fineTuneId}`, options); + } + /** + * List your organization's fine-tuning jobs + */ + list(options) { + return this.getAPIList('/fine-tunes', FineTunesPage, options); + } + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuneId, options) { + return this.post(`/fine-tunes/${fineTuneId}/cancel`, options); + } + listEvents(fineTuneId, query, options) { + var _a; + return this.get(`/fine-tunes/${fineTuneId}/events`, { + query, + timeout: 86400000, + ...options, + stream: + (_a = query === null || query === void 0 ? void 0 : query.stream) !== null && _a !== void 0 ? + _a + : false, + }); + } +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class FineTunesPage extends Page {} +(function (FineTunes) {})(FineTunes || (FineTunes = {})); +//# sourceMappingURL=fine-tunes.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs.mjs +// File generated from our OpenAPI spec by Stainless. + + + +class Jobs extends resource_APIResource { + /** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ + create(body, options) { + return this.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ + retrieve(fineTuningJobId, options) { + return this.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); + } + list(query = {}, options) { + if (isRequestOptions(query)) { + return this.list({}, query); + } + return this.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuningJobId, options) { + return this.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); + } + listEvents(fineTuningJobId, query = {}, options) { + if (isRequestOptions(query)) { + return this.listEvents(fineTuningJobId, {}, query); + } + return this.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { + query, + ...options, + }); + } +} +class FineTuningJobsPage extends CursorPage {} +class FineTuningJobEventsPage extends CursorPage {} +(function (Jobs) {})(Jobs || (Jobs = {})); +//# sourceMappingURL=jobs.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/index.mjs +// File generated from our OpenAPI spec by Stainless. + + +//# sourceMappingURL=index.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs +// File generated from our OpenAPI spec by Stainless. + + + +class FineTuning extends resource_APIResource { + constructor() { + super(...arguments); + this.jobs = new Jobs(this.client); + } +} +(function (FineTuning) { + FineTuning.Jobs = Jobs; + FineTuning.FineTuningJobsPage = FineTuningJobsPage; + FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage; +})(FineTuning || (FineTuning = {})); +//# sourceMappingURL=fine-tuning.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs +// File generated from our OpenAPI spec by Stainless. + + +class Images extends resource_APIResource { + /** + * Creates a variation of a given image. + */ + createVariation(body, options) { + return this.post('/images/variations', multipartFormRequestOptions({ body, ...options })); + } + /** + * Creates an edited or extended image given an original image and a prompt. + */ + edit(body, options) { + return this.post('/images/edits', multipartFormRequestOptions({ body, ...options })); + } + /** + * Creates an image given a prompt. + */ + generate(body, options) { + return this.post('/images/generations', { body, ...options }); + } +} +(function (Images) {})(Images || (Images = {})); +//# sourceMappingURL=images.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs +// File generated from our OpenAPI spec by Stainless. + + +class Models extends resource_APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this.get(`/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this.getAPIList('/models', ModelsPage, options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization. + */ + del(model, options) { + return this.delete(`/models/${model}`, options); + } +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class ModelsPage extends Page {} +(function (Models) {})(Models || (Models = {})); +//# sourceMappingURL=models.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs +// File generated from our OpenAPI spec by Stainless. + +class Moderations extends resource_APIResource { + /** + * Classifies if text violates OpenAI's Content Policy + */ + create(body, options) { + return this.post('/moderations', { body, ...options }); + } +} +(function (Moderations) {})(Moderations || (Moderations = {})); +//# sourceMappingURL=moderations.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs +// File generated from our OpenAPI spec by Stainless. + + + + + + + + + + + +//# sourceMappingURL=index.mjs.map + +;// CONCATENATED MODULE: ./node_modules/openai/index.mjs +// File generated from our OpenAPI spec by Stainless. +var _a; + + + + + +/** API Client for interfacing with the OpenAI API. */ +class OpenAI extends APIClient { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string} [opts.apiKey=process.env['OPENAI_API_KEY']] - The API Key to send to the API. + * @param {string} [opts.baseURL] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * @param {string | null} [opts.organization] + */ + constructor(_b) { + var _c, _d; + var { + apiKey = readEnv('OPENAI_API_KEY'), + organization = (_c = readEnv('OPENAI_ORG_ID')) !== null && _c !== void 0 ? _c : null, + ...opts + } = _b === void 0 ? {} : _b; + if (apiKey === undefined) { + throw new Error( + "The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'my apiKey' }).", + ); + } + const options = { + apiKey, + organization, + baseURL: `https://api.openai.com/v1`, + ...opts, + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new Error( + "It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n", + ); + } + super({ + baseURL: options.baseURL, + timeout: (_d = options.timeout) !== null && _d !== void 0 ? _d : 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this.completions = new completions_Completions(this); + this.chat = new Chat(this); + this.edits = new Edits(this); + this.embeddings = new Embeddings(this); + this.files = new Files(this); + this.images = new Images(this); + this.audio = new Audio(this); + this.moderations = new Moderations(this); + this.models = new Models(this); + this.fineTuning = new FineTuning(this); + this.fineTunes = new FineTunes(this); + this._options = options; + this.apiKey = apiKey; + this.organization = organization; + } + defaultQuery() { + return this._options.defaultQuery; + } + defaultHeaders(opts) { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + authHeaders(opts) { + return { Authorization: `Bearer ${this.apiKey}` }; + } +} +_a = OpenAI; +OpenAI.OpenAI = _a; +OpenAI.APIError = APIError; +OpenAI.APIConnectionError = APIConnectionError; +OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError; +OpenAI.APIUserAbortError = APIUserAbortError; +OpenAI.NotFoundError = NotFoundError; +OpenAI.ConflictError = ConflictError; +OpenAI.RateLimitError = RateLimitError; +OpenAI.BadRequestError = BadRequestError; +OpenAI.AuthenticationError = AuthenticationError; +OpenAI.InternalServerError = InternalServerError; +OpenAI.PermissionDeniedError = PermissionDeniedError; +OpenAI.UnprocessableEntityError = UnprocessableEntityError; +const { + APIError: openai_APIError, + APIConnectionError: openai_APIConnectionError, + APIConnectionTimeoutError: openai_APIConnectionTimeoutError, + APIUserAbortError: openai_APIUserAbortError, + NotFoundError: openai_NotFoundError, + ConflictError: openai_ConflictError, + RateLimitError: openai_RateLimitError, + BadRequestError: openai_BadRequestError, + AuthenticationError: openai_AuthenticationError, + InternalServerError: openai_InternalServerError, + PermissionDeniedError: openai_PermissionDeniedError, + UnprocessableEntityError: openai_UnprocessableEntityError, +} = error_namespaceObject; +var openai_toFile = toFile; +var openai_fileFromPath = fileFromPath_node_fileFromPath; +(function (OpenAI) { + // Helper functions + OpenAI.toFile = toFile; + OpenAI.fileFromPath = fileFromPath_node_fileFromPath; + OpenAI.Page = Page; + OpenAI.CursorPage = CursorPage; + OpenAI.Completions = completions_Completions; + OpenAI.Chat = Chat; + OpenAI.Edits = Edits; + OpenAI.Embeddings = Embeddings; + OpenAI.Files = Files; + OpenAI.FileObjectsPage = FileObjectsPage; + OpenAI.Images = Images; + OpenAI.Audio = Audio; + OpenAI.Moderations = Moderations; + OpenAI.Models = Models; + OpenAI.ModelsPage = ModelsPage; + OpenAI.FineTuning = FineTuning; + OpenAI.FineTunes = FineTunes; + OpenAI.FineTunesPage = FineTunesPage; +})(OpenAI || (OpenAI = {})); +/* harmony default export */ const openai = ((/* unused pure expression or super */ null && (OpenAI))); +//# sourceMappingURL=index.mjs.map + + +/***/ }) + +}; diff --git a/dist/586.index.js b/dist/586.index.js new file mode 100644 index 0000000..16e5c66 --- /dev/null +++ b/dist/586.index.js @@ -0,0 +1,801 @@ +export const id = 586; +export const ids = [586,130,197,273,159]; +export const modules = { + +/***/ 6159: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "APIChain": () => (/* binding */ APIChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 2 modules +var llm_chain = __webpack_require__(7273); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js +var prompts_prompt = __webpack_require__(4095); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/api/prompts.js +/* eslint-disable spaced-comment */ + +const API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation: +{api_docs} +Using this documentation, generate the full API url to call for answering the user question. +You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call. + +Question:{question} +API url:`; +const API_URL_PROMPT_TEMPLATE = /* #__PURE__ */ new prompts_prompt.PromptTemplate({ + inputVariables: ["api_docs", "question"], + template: API_URL_RAW_PROMPT_TEMPLATE, +}); +const API_RESPONSE_RAW_PROMPT_TEMPLATE = `${API_URL_RAW_PROMPT_TEMPLATE} {api_url} + +Here is the response from the API: + +{api_response} + +Summarize this response to answer the original question. + +Summary:`; +const API_RESPONSE_PROMPT_TEMPLATE = /* #__PURE__ */ new prompts_prompt.PromptTemplate({ + inputVariables: ["api_docs", "question", "api_url", "api_response"], + template: API_RESPONSE_RAW_PROMPT_TEMPLATE, +}); + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/api/api_chain.js + + + +/** + * Class that extends BaseChain and represents a chain specifically + * designed for making API requests and processing API responses. + */ +class APIChain extends base/* BaseChain */.l { + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "apiAnswerChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiRequestChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiDocs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "question" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + this.apiRequestChain = fields.apiRequestChain; + this.apiAnswerChain = fields.apiAnswerChain; + this.apiDocs = fields.apiDocs; + this.inputKey = fields.inputKey ?? this.inputKey; + this.outputKey = fields.outputKey ?? this.outputKey; + this.headers = fields.headers ?? this.headers; + } + /** @ignore */ + async _call(values, runManager) { + const question = values[this.inputKey]; + const api_url = await this.apiRequestChain.predict({ question, api_docs: this.apiDocs }, runManager?.getChild("request")); + const res = await fetch(api_url, { headers: this.headers }); + const api_response = await res.text(); + const answer = await this.apiAnswerChain.predict({ question, api_docs: this.apiDocs, api_url, api_response }, runManager?.getChild("response")); + return { [this.outputKey]: answer }; + } + _chainType() { + return "api_chain"; + } + static async deserialize(data) { + const { api_request_chain, api_answer_chain, api_docs } = data; + if (!api_request_chain) { + throw new Error("LLMChain must have api_request_chain"); + } + if (!api_answer_chain) { + throw new Error("LLMChain must have api_answer_chain"); + } + if (!api_docs) { + throw new Error("LLMChain must have api_docs"); + } + return new APIChain({ + apiAnswerChain: await llm_chain.LLMChain.deserialize(api_answer_chain), + apiRequestChain: await llm_chain.LLMChain.deserialize(api_request_chain), + apiDocs: api_docs, + }); + } + serialize() { + return { + _type: this._chainType(), + api_answer_chain: this.apiAnswerChain.serialize(), + api_request_chain: this.apiRequestChain.serialize(), + api_docs: this.apiDocs, + }; + } + /** + * Static method to create a new APIChain from a BaseLanguageModel and API + * documentation. + * @param llm BaseLanguageModel instance. + * @param apiDocs API documentation. + * @param options Optional configuration options for the APIChain. + * @returns New APIChain instance. + */ + static fromLLMAndAPIDocs(llm, apiDocs, options = {}) { + const { apiUrlPrompt = API_URL_PROMPT_TEMPLATE, apiResponsePrompt = API_RESPONSE_PROMPT_TEMPLATE, } = options; + const apiRequestChain = new llm_chain.LLMChain({ prompt: apiUrlPrompt, llm }); + const apiAnswerChain = new llm_chain.LLMChain({ prompt: apiResponsePrompt, llm }); + return new this({ + apiAnswerChain, + apiRequestChain, + apiDocs, + ...options, + }); + } +} + + +/***/ }), + +/***/ 3197: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "l": () => (/* binding */ BaseChain) +/* harmony export */ }); +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6009); +/* harmony import */ var _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7679); + + + +/** + * Base interface that all chains must implement. + */ +class BaseChain extends _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__/* .BaseLangChain */ .BD { + get lc_namespace() { + return ["langchain", "chains", this._chainType()]; + } + constructor(fields, + /** @deprecated */ + verbose, + /** @deprecated */ + callbacks) { + if (arguments.length === 1 && + typeof fields === "object" && + !("saveContext" in fields)) { + // fields is not a BaseMemory + const { memory, callbackManager, ...rest } = fields; + super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); + this.memory = memory; + } + else { + // fields is a BaseMemory + super({ verbose, callbacks }); + this.memory = fields; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = { ...values }; + if ("signal" in valuesForMemory) { + delete valuesForMemory.signal; + } + if ("timeout" in valuesForMemory) { + delete valuesForMemory.timeout; + } + return valuesForMemory; + } + /** + * Invoke the chain with the provided input and returns the output. + * @param input Input values for the chain run. + * @param config Optional configuration for the Runnable. + * @returns Promise that resolves with the output of the chain run. + */ + async invoke(input, config) { + return this.call(input, config); + } + /** + * Return a json-like object representing this chain. + */ + serialize() { + throw new Error("Method not implemented."); + } + async run( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, config) { + const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); + const isKeylessInput = inputKeys.length <= 1; + if (!isKeylessInput) { + throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; + const returnValues = await this.call(values, config); + const keys = Object.keys(returnValues); + if (keys.length === 1) { + return returnValues[keys[0]]; + } + throw new Error("return values have multiple keys, `run` only supported when one key currently"); + } + async _formatValues(values) { + const fullValues = { ...values }; + if (fullValues.timeout && !fullValues.signal) { + fullValues.signal = AbortSignal.timeout(fullValues.timeout); + delete fullValues.timeout; + } + if (!(this.memory == null)) { + const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); + for (const [key, value] of Object.entries(newValues)) { + fullValues[key] = value; + } + } + return fullValues; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + async call(values, config, + /** @deprecated */ + tags) { + const fullValues = await this._formatValues(values); + const parsedConfig = (0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .parseCallbackConfigArg */ .QH)(config); + const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .CallbackManager.configure */ .Ye.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); + let outputValues; + try { + outputValues = await (values.signal + ? Promise.race([ + this._call(fullValues, runManager), + new Promise((_, reject) => { + values.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]) + : this._call(fullValues, runManager)); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + if (!(this.memory == null)) { + await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + } + await runManager?.handleChainEnd(outputValues); + // add the runManager's currentRunId to the outputValues + Object.defineProperty(outputValues, _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .RUN_KEY */ .WH, { + value: runManager ? { runId: runManager?.runId } : undefined, + configurable: true, + }); + return outputValues; + } + /** + * Call the chain on all inputs in the list + */ + async apply(inputs, config) { + return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + } + /** + * Load a chain from a json-like object describing it. + */ + static async deserialize(data, values = {}) { + switch (data._type) { + case "llm_chain": { + const { LLMChain } = await __webpack_require__.e(/* import() */ 273).then(__webpack_require__.bind(__webpack_require__, 7273)); + return LLMChain.deserialize(data); + } + case "sequential_chain": { + const { SequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SequentialChain.deserialize(data); + } + case "simple_sequential_chain": { + const { SimpleSequentialChain } = await __webpack_require__.e(/* import() */ 210).then(__webpack_require__.bind(__webpack_require__, 7210)); + return SimpleSequentialChain.deserialize(data); + } + case "stuff_documents_chain": { + const { StuffDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return StuffDocumentsChain.deserialize(data); + } + case "map_reduce_documents_chain": { + const { MapReduceDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return MapReduceDocumentsChain.deserialize(data); + } + case "refine_documents_chain": { + const { RefineDocumentsChain } = await __webpack_require__.e(/* import() */ 608).then(__webpack_require__.bind(__webpack_require__, 3608)); + return RefineDocumentsChain.deserialize(data); + } + case "vector_db_qa": { + const { VectorDBQAChain } = await Promise.all(/* import() */[__webpack_require__.e(608), __webpack_require__.e(214)]).then(__webpack_require__.bind(__webpack_require__, 5214)); + return VectorDBQAChain.deserialize(data, values); + } + case "api_chain": { + const { APIChain } = await __webpack_require__.e(/* import() */ 159).then(__webpack_require__.bind(__webpack_require__, 6159)); + return APIChain.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } +} + + +/***/ }), + +/***/ 7273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "LLMChain": () => (/* binding */ LLMChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules +var runnable = __webpack_require__(1972); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/output_parser.js + +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends runnable/* Runnable */.eq { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input) => this.parseResult([{ text: input }]), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input) => this.parseResult([{ message: input, text: input.content }]), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Class to parse the output of an LLM call that also allows streaming inputs. + */ +class BaseTransformOutputParser extends (/* unused pure expression or super */ null && (BaseOutputParser)) { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) { + if (typeof chunk === "string") { + yield this.parseResult([{ text: chunk }]); + } + else { + yield this.parseResult([{ message: chunk, text: chunk.content }]); + } + } + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser", + }); + } +} +/** + * OutputParser that parses LLMResult into the top likely string. + */ +class StringOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "StrOutputParser"; + } + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } +} +/** + * OutputParser that parses LLMResult into the top likely string and + * encodes it into bytes. + */ +class BytesOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "textEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: new TextEncoder() + }); + } + static lc_name() { + return "BytesOutputParser"; + } + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/output_parsers/noop.js + +/** + * The NoOpOutputParser class is a type of output parser that does not + * perform any operations on the output. It extends the BaseOutputParser + * class and is part of the LangChain's output parsers module. This class + * is useful in scenarios where the raw output of the Large Language + * Models (LLMs) is required. + */ +class NoOpOutputParser extends BaseOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "output_parsers", "default"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "NoOpOutputParser"; + } + /** + * This method takes a string as input and returns the same string as + * output. It does not perform any operations on the input string. + * @param text The input string to be parsed. + * @returns The same input string without any operations performed on it. + */ + parse(text) { + return Promise.resolve(text); + } + /** + * This method returns an empty string. It does not provide any formatting + * instructions. + * @returns An empty string, indicating no formatting instructions. + */ + getFormatInstructions() { + return ""; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + + + + +/** + * Chain to run queries against LLMs. + * + * @example + * ```ts + * import { LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); + * const llm = new LLMChain({ llm: new OpenAI(), prompt }); + * ``` + */ +class LLMChain extends base/* BaseChain */.l { + static lc_name() { + return "LLMChain"; + } + get inputKeys() { + return this.prompt.inputVariables; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llmKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "text" + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + this.llm = fields.llm; + this.llmKwargs = fields.llmKwargs; + this.outputKey = fields.outputKey ?? this.outputKey; + this.outputParser = + fields.outputParser ?? new NoOpOutputParser(); + if (this.prompt.outputParser) { + if (fields.outputParser) { + throw new Error("Cannot set both outputParser and prompt.outputParser"); + } + this.outputParser = this.prompt.outputParser; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = super._selectMemoryInputs(values); + for (const key of this.llm.callKeys) { + if (key in values) { + delete valuesForMemory[key]; + } + } + return valuesForMemory; + } + /** @ignore */ + async _getFinalOutput(generations, promptValue, runManager) { + let finalCompletion; + if (this.outputParser) { + finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + } + else { + finalCompletion = generations[0].text; + } + return finalCompletion; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + call(values, config) { + return super.call(values, config); + } + /** @ignore */ + async _call(values, runManager) { + const valuesForPrompt = { ...values }; + const valuesForLLM = { + ...this.llmKwargs, + }; + for (const key of this.llm.callKeys) { + if (key in values) { + valuesForLLM[key] = values[key]; + delete valuesForPrompt[key]; + } + } + const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); + const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); + return { + [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), + }; + } + /** + * Format prompt with values and pass to LLM + * + * @param values - keys to pass to prompt template + * @param callbackManager - CallbackManager to use + * @returns Completion from LLM. + * + * @example + * ```ts + * llm.predict({ adjective: "funny" }) + * ``` + */ + async predict(values, callbackManager) { + const output = await this.call(values, callbackManager); + return output[this.outputKey]; + } + _chainType() { + return "llm"; + } + static async deserialize(data) { + const { llm, prompt } = data; + if (!llm) { + throw new Error("LLMChain must have llm"); + } + if (!prompt) { + throw new Error("LLMChain must have prompt"); + } + return new LLMChain({ + llm: await base_language/* BaseLanguageModel.deserialize */.qV.deserialize(llm), + prompt: await prompts_base/* BasePromptTemplate.deserialize */.dy.deserialize(prompt), + }); + } + /** @deprecated */ + serialize() { + return { + _type: `${this._chainType()}_chain`, + llm: this.llm.serialize(), + prompt: this.prompt.serialize(), + }; + } +} + + +/***/ }) + +}; diff --git a/dist/608.index.js b/dist/608.index.js new file mode 100644 index 0000000..ca0bdbe --- /dev/null +++ b/dist/608.index.js @@ -0,0 +1,859 @@ +export const id = 608; +export const ids = [608,273]; +export const modules = { + +/***/ 3608: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "MapReduceDocumentsChain": () => (/* binding */ MapReduceDocumentsChain), +/* harmony export */ "RefineDocumentsChain": () => (/* binding */ RefineDocumentsChain), +/* harmony export */ "StuffDocumentsChain": () => (/* binding */ StuffDocumentsChain) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3197); +/* harmony import */ var _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7273); +/* harmony import */ var _prompts_prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4095); + + + +/** + * Chain that combines documents by stuffing into context. + * @augments BaseChain + * @augments StuffDocumentsChainInput + */ +class StuffDocumentsChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { + static lc_name() { + return "StuffDocumentsChain"; + } + get inputKeys() { + return [this.inputKey, ...this.llmChain.inputKeys].filter((key) => key !== this.documentVariableName); + } + get outputKeys() { + return this.llmChain.outputKeys; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_documents" + }); + Object.defineProperty(this, "documentVariableName", { + enumerable: true, + configurable: true, + writable: true, + value: "context" + }); + this.llmChain = fields.llmChain; + this.documentVariableName = + fields.documentVariableName ?? this.documentVariableName; + this.inputKey = fields.inputKey ?? this.inputKey; + } + /** @ignore */ + _prepInputs(values) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: docs, ...rest } = values; + const texts = docs.map(({ pageContent }) => pageContent); + const text = texts.join("\n\n"); + return { + ...rest, + [this.documentVariableName]: text, + }; + } + /** @ignore */ + async _call(values, runManager) { + const result = await this.llmChain.call(this._prepInputs(values), runManager?.getChild("combine_documents")); + return result; + } + _chainType() { + return "stuff_documents_chain"; + } + static async deserialize(data) { + if (!data.llm_chain) { + throw new Error("Missing llm_chain"); + } + return new StuffDocumentsChain({ + llmChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(data.llm_chain), + }); + } + serialize() { + return { + _type: this._chainType(), + llm_chain: this.llmChain.serialize(), + }; + } +} +/** + * Combine documents by mapping a chain over them, then combining results. + * @augments BaseChain + * @augments StuffDocumentsChainInput + */ +class MapReduceDocumentsChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { + static lc_name() { + return "MapReduceDocumentsChain"; + } + get inputKeys() { + return [this.inputKey, ...this.combineDocumentChain.inputKeys]; + } + get outputKeys() { + return this.combineDocumentChain.outputKeys; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_documents" + }); + Object.defineProperty(this, "documentVariableName", { + enumerable: true, + configurable: true, + writable: true, + value: "context" + }); + Object.defineProperty(this, "returnIntermediateSteps", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: 3000 + }); + Object.defineProperty(this, "maxIterations", { + enumerable: true, + configurable: true, + writable: true, + value: 10 + }); + Object.defineProperty(this, "ensureMapStep", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "combineDocumentChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmChain = fields.llmChain; + this.combineDocumentChain = fields.combineDocumentChain; + this.documentVariableName = + fields.documentVariableName ?? this.documentVariableName; + this.ensureMapStep = fields.ensureMapStep ?? this.ensureMapStep; + this.inputKey = fields.inputKey ?? this.inputKey; + this.maxTokens = fields.maxTokens ?? this.maxTokens; + this.maxIterations = fields.maxIterations ?? this.maxIterations; + this.returnIntermediateSteps = fields.returnIntermediateSteps ?? false; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: docs, ...rest } = values; + let currentDocs = docs; + let intermediateSteps = []; + // For each iteration, we'll use the `llmChain` to get a new result + for (let i = 0; i < this.maxIterations; i += 1) { + const inputs = currentDocs.map((d) => ({ + [this.documentVariableName]: d.pageContent, + ...rest, + })); + const canSkipMapStep = i !== 0 || !this.ensureMapStep; + if (canSkipMapStep) { + // Calculate the total tokens required in the input + const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({ + [this.combineDocumentChain.inputKey]: currentDocs, + ...rest, + })); + const length = await this.combineDocumentChain.llmChain.llm.getNumTokens(formatted); + const withinTokenLimit = length < this.maxTokens; + // If we can skip the map step, and we're within the token limit, we don't + // need to run the map step, so just break out of the loop. + if (withinTokenLimit) { + break; + } + } + const results = await this.llmChain.apply(inputs, + // If we have a runManager, then we need to create a child for each input + // so that we can track the progress of each input. + runManager + ? Array.from({ length: inputs.length }, (_, i) => runManager.getChild(`map_${i + 1}`)) + : undefined); + const { outputKey } = this.llmChain; + // If the flag is set, then concat that to the intermediate steps + if (this.returnIntermediateSteps) { + intermediateSteps = intermediateSteps.concat(results.map((r) => r[outputKey])); + } + currentDocs = results.map((r) => ({ + pageContent: r[outputKey], + metadata: {}, + })); + } + // Now, with the final result of all the inputs from the `llmChain`, we can + // run the `combineDocumentChain` over them. + const newInputs = { + [this.combineDocumentChain.inputKey]: currentDocs, + ...rest, + }; + const result = await this.combineDocumentChain.call(newInputs, runManager?.getChild("combine_documents")); + // Return the intermediate steps results if the flag is set + if (this.returnIntermediateSteps) { + return { ...result, intermediateSteps }; + } + return result; + } + _chainType() { + return "map_reduce_documents_chain"; + } + static async deserialize(data) { + if (!data.llm_chain) { + throw new Error("Missing llm_chain"); + } + if (!data.combine_document_chain) { + throw new Error("Missing combine_document_chain"); + } + return new MapReduceDocumentsChain({ + llmChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(data.llm_chain), + combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain), + }); + } + serialize() { + return { + _type: this._chainType(), + llm_chain: this.llmChain.serialize(), + combine_document_chain: this.combineDocumentChain.serialize(), + }; + } +} +/** + * Combine documents by doing a first pass and then refining on more documents. + * @augments BaseChain + * @augments RefineDocumentsChainInput + */ +class RefineDocumentsChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { + static lc_name() { + return "RefineDocumentsChain"; + } + get defaultDocumentPrompt() { + return new _prompts_prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate({ + inputVariables: ["page_content"], + template: "{page_content}", + }); + } + get inputKeys() { + return [ + ...new Set([ + this.inputKey, + ...this.llmChain.inputKeys, + ...this.refineLLMChain.inputKeys, + ]), + ].filter((key) => key !== this.documentVariableName && key !== this.initialResponseName); + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_documents" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output_text" + }); + Object.defineProperty(this, "documentVariableName", { + enumerable: true, + configurable: true, + writable: true, + value: "context" + }); + Object.defineProperty(this, "initialResponseName", { + enumerable: true, + configurable: true, + writable: true, + value: "existing_answer" + }); + Object.defineProperty(this, "refineLLMChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "documentPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: this.defaultDocumentPrompt + }); + this.llmChain = fields.llmChain; + this.refineLLMChain = fields.refineLLMChain; + this.documentVariableName = + fields.documentVariableName ?? this.documentVariableName; + this.inputKey = fields.inputKey ?? this.inputKey; + this.outputKey = fields.outputKey ?? this.outputKey; + this.documentPrompt = fields.documentPrompt ?? this.documentPrompt; + this.initialResponseName = + fields.initialResponseName ?? this.initialResponseName; + } + /** @ignore */ + async _constructInitialInputs(doc, rest) { + const baseInfo = { + page_content: doc.pageContent, + ...doc.metadata, + }; + const documentInfo = {}; + this.documentPrompt.inputVariables.forEach((value) => { + documentInfo[value] = baseInfo[value]; + }); + const baseInputs = { + [this.documentVariableName]: await this.documentPrompt.format({ + ...documentInfo, + }), + }; + const inputs = { ...baseInputs, ...rest }; + return inputs; + } + /** @ignore */ + async _constructRefineInputs(doc, res) { + const baseInfo = { + page_content: doc.pageContent, + ...doc.metadata, + }; + const documentInfo = {}; + this.documentPrompt.inputVariables.forEach((value) => { + documentInfo[value] = baseInfo[value]; + }); + const baseInputs = { + [this.documentVariableName]: await this.documentPrompt.format({ + ...documentInfo, + }), + }; + const inputs = { [this.initialResponseName]: res, ...baseInputs }; + return inputs; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: docs, ...rest } = values; + const currentDocs = docs; + const initialInputs = await this._constructInitialInputs(currentDocs[0], rest); + let res = await this.llmChain.predict({ ...initialInputs }, runManager?.getChild("answer")); + const refineSteps = [res]; + for (let i = 1; i < currentDocs.length; i += 1) { + const refineInputs = await this._constructRefineInputs(currentDocs[i], res); + const inputs = { ...refineInputs, ...rest }; + res = await this.refineLLMChain.predict({ ...inputs }, runManager?.getChild("refine")); + refineSteps.push(res); + } + return { [this.outputKey]: res }; + } + _chainType() { + return "refine_documents_chain"; + } + static async deserialize(data) { + const SerializedLLMChain = data.llm_chain; + if (!SerializedLLMChain) { + throw new Error("Missing llm_chain"); + } + const SerializedRefineDocumentChain = data.refine_llm_chain; + if (!SerializedRefineDocumentChain) { + throw new Error("Missing refine_llm_chain"); + } + return new RefineDocumentsChain({ + llmChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(SerializedLLMChain), + refineLLMChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(SerializedRefineDocumentChain), + }); + } + serialize() { + return { + _type: this._chainType(), + llm_chain: this.llmChain.serialize(), + refine_llm_chain: this.refineLLMChain.serialize(), + }; + } +} + + +/***/ }), + +/***/ 7273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "LLMChain": () => (/* binding */ LLMChain) +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js +var base = __webpack_require__(3197); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var prompts_base = __webpack_require__(5411); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules +var runnable = __webpack_require__(1972); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/output_parser.js + +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends runnable/* Runnable */.eq { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input) => this.parseResult([{ text: input }]), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input) => this.parseResult([{ message: input, text: input.content }]), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Class to parse the output of an LLM call that also allows streaming inputs. + */ +class BaseTransformOutputParser extends (/* unused pure expression or super */ null && (BaseOutputParser)) { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) { + if (typeof chunk === "string") { + yield this.parseResult([{ text: chunk }]); + } + else { + yield this.parseResult([{ message: chunk, text: chunk.content }]); + } + } + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser", + }); + } +} +/** + * OutputParser that parses LLMResult into the top likely string. + */ +class StringOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "StrOutputParser"; + } + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } +} +/** + * OutputParser that parses LLMResult into the top likely string and + * encodes it into bytes. + */ +class BytesOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "output_parser"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "textEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: new TextEncoder() + }); + } + static lc_name() { + return "BytesOutputParser"; + } + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/output_parsers/noop.js + +/** + * The NoOpOutputParser class is a type of output parser that does not + * perform any operations on the output. It extends the BaseOutputParser + * class and is part of the LangChain's output parsers module. This class + * is useful in scenarios where the raw output of the Large Language + * Models (LLMs) is required. + */ +class NoOpOutputParser extends BaseOutputParser { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "output_parsers", "default"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "NoOpOutputParser"; + } + /** + * This method takes a string as input and returns the same string as + * output. It does not perform any operations on the input string. + * @param text The input string to be parsed. + * @returns The same input string without any operations performed on it. + */ + parse(text) { + return Promise.resolve(text); + } + /** + * This method returns an empty string. It does not provide any formatting + * instructions. + * @returns An empty string, indicating no formatting instructions. + */ + getFormatInstructions() { + return ""; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + + + + +/** + * Chain to run queries against LLMs. + * + * @example + * ```ts + * import { LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); + * const llm = new LLMChain({ llm: new OpenAI(), prompt }); + * ``` + */ +class LLMChain extends base/* BaseChain */.l { + static lc_name() { + return "LLMChain"; + } + get inputKeys() { + return this.prompt.inputVariables; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llmKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "text" + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + this.llm = fields.llm; + this.llmKwargs = fields.llmKwargs; + this.outputKey = fields.outputKey ?? this.outputKey; + this.outputParser = + fields.outputParser ?? new NoOpOutputParser(); + if (this.prompt.outputParser) { + if (fields.outputParser) { + throw new Error("Cannot set both outputParser and prompt.outputParser"); + } + this.outputParser = this.prompt.outputParser; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = super._selectMemoryInputs(values); + for (const key of this.llm.callKeys) { + if (key in values) { + delete valuesForMemory[key]; + } + } + return valuesForMemory; + } + /** @ignore */ + async _getFinalOutput(generations, promptValue, runManager) { + let finalCompletion; + if (this.outputParser) { + finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + } + else { + finalCompletion = generations[0].text; + } + return finalCompletion; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + call(values, config) { + return super.call(values, config); + } + /** @ignore */ + async _call(values, runManager) { + const valuesForPrompt = { ...values }; + const valuesForLLM = { + ...this.llmKwargs, + }; + for (const key of this.llm.callKeys) { + if (key in values) { + valuesForLLM[key] = values[key]; + delete valuesForPrompt[key]; + } + } + const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); + const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); + return { + [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), + }; + } + /** + * Format prompt with values and pass to LLM + * + * @param values - keys to pass to prompt template + * @param callbackManager - CallbackManager to use + * @returns Completion from LLM. + * + * @example + * ```ts + * llm.predict({ adjective: "funny" }) + * ``` + */ + async predict(values, callbackManager) { + const output = await this.call(values, callbackManager); + return output[this.outputKey]; + } + _chainType() { + return "llm"; + } + static async deserialize(data) { + const { llm, prompt } = data; + if (!llm) { + throw new Error("LLMChain must have llm"); + } + if (!prompt) { + throw new Error("LLMChain must have prompt"); + } + return new LLMChain({ + llm: await base_language/* BaseLanguageModel.deserialize */.qV.deserialize(llm), + prompt: await prompts_base/* BasePromptTemplate.deserialize */.dy.deserialize(prompt), + }); + } + /** @deprecated */ + serialize() { + return { + _type: `${this._chainType()}_chain`, + llm: this.llm.serialize(), + prompt: this.prompt.serialize(), + }; + } +} + + +/***/ }) + +}; diff --git a/dist/609.index.js b/dist/609.index.js new file mode 100644 index 0000000..7678e9f --- /dev/null +++ b/dist/609.index.js @@ -0,0 +1,178 @@ +export const id = 609; +export const ids = [609,806]; +export const modules = { + +/***/ 609: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FewShotPromptTemplate": () => (/* binding */ FewShotPromptTemplate) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5411); +/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(837); +/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4095); + + + +/** + * Prompt template that contains few-shot examples. + * @augments BasePromptTemplate + * @augments FewShotPromptTemplateInput + */ +class FewShotPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleSelector", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "suffix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "exampleSeparator", { + enumerable: true, + configurable: true, + writable: true, + value: "\n\n" + }); + Object.defineProperty(this, "prefix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.examples !== undefined && this.exampleSelector !== undefined) { + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + } + if (this.examples === undefined && this.exampleSelector === undefined) { + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "few_shot"; + } + async getExamples(inputVariables) { + if (this.examples !== undefined) { + return this.examples; + } + if (this.exampleSelector !== undefined) { + return this.exampleSelector.selectExamples(inputVariables); + } + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables, + }; + return new FewShotPromptTemplate(promptDict); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); + return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(template, this.templateFormat, allValues); + } + serialize() { + if (this.exampleSelector || !this.examples) { + throw new Error("Serializing an example selector is not currently supported"); + } + if (this.outputParser !== undefined) { + throw new Error("Serializing an output parser is not currently supported"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples, + }; + } + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) { + throw new Error("Missing example prompt"); + } + const examplePrompt = await _prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) { + examples = data.examples; + } + else { + throw new Error("Invalid examples format. Only list or string are supported."); + } + return new FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format, + }); + } +} + + +/***/ }) + +}; diff --git a/dist/624.index.js b/dist/624.index.js new file mode 100644 index 0000000..24e4f56 --- /dev/null +++ b/dist/624.index.js @@ -0,0 +1,1411 @@ +export const id = 624; +export const ids = [624]; +export const modules = { + +/***/ 4624: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +// ESM COMPAT FLAG +__webpack_require__.r(__webpack_exports__); + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "OpenAI": () => (/* binding */ OpenAI), + "OpenAIChat": () => (/* reexport */ OpenAIChat), + "PromptLayerOpenAI": () => (/* binding */ PromptLayerOpenAI), + "PromptLayerOpenAIChat": () => (/* reexport */ PromptLayerOpenAIChat) +}); + +// EXTERNAL MODULE: ./node_modules/openai/index.mjs + 53 modules +var openai = __webpack_require__(37); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/count_tokens.js +var count_tokens = __webpack_require__(8393); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js +var schema = __webpack_require__(8102); +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/azure.js +var azure = __webpack_require__(113); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/chunk.js +const chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => { + const chunkIndex = Math.floor(index / chunkSize); + const chunk = chunks[chunkIndex] || []; + // eslint-disable-next-line no-param-reassign + chunks[chunkIndex] = chunk.concat([elem]); + return chunks; +}, []); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/env.js +var env = __webpack_require__(5785); +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/prompt-layer.js +var prompt_layer = __webpack_require__(2306); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules +var base_language = __webpack_require__(7679); +// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/manager.js + 13 modules +var manager = __webpack_require__(6009); +// EXTERNAL MODULE: ./node_modules/langchain/dist/memory/base.js +var base = __webpack_require__(790); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/llms/base.js + + + + +/** + * LLM Wrapper. Provides an {@link call} (an {@link generate}) function that takes in a prompt (or prompts) and returns a string. + */ +class BaseLLM extends base_language/* BaseLanguageModel */.qV { + constructor({ concurrency, ...rest }) { + super(concurrency ? { maxConcurrency: concurrency, ...rest } : rest); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "llms", this._llmType()] + }); + } + /** + * This method takes an input and options, and returns a string. It + * converts the input to a prompt value and generates a result based on + * the prompt. + * @param input Input for the LLM. + * @param options Options for the LLM call. + * @returns A string result based on the prompt. + */ + async invoke(input, options) { + const promptValue = BaseLLM._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + return result.generations[0][0].text; + } + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_input, _options, _runManager) { + throw new Error("Not implemented."); + } + _separateRunnableConfigFromCallOptions(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + if (callOptions?.timeout && !callOptions.signal) { + callOptions.signal = AbortSignal.timeout(callOptions.timeout); + } + return [runnableConfig, callOptions]; + } + async *_streamIterator(input, options) { + // Subclass check required to avoid double callbacks with default implementation + if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) { + yield this.invoke(input, options); + } + else { + const prompt = BaseLLM._convertInputToPromptValue(input); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); + const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], undefined, undefined, extra); + let generation = new schema/* GenerationChunk */.b6({ + text: "", + }); + try { + for await (const chunk of this._streamResponseChunks(input.toString(), callOptions, runManagers?.[0])) { + if (!generation) { + generation = chunk; + } + else { + generation = generation.concat(chunk); + } + if (typeof chunk.text === "string") { + yield chunk.text; + } + } + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + generations: [[generation]], + }))); + } + } + /** + * This method takes prompt values, options, and callbacks, and generates + * a result based on the prompts. + * @param promptValues Prompt values for the LLM. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns An LLMResult based on the prompts. + */ + async generatePrompt(promptValues, options, callbacks) { + const prompts = promptValues.map((promptValue) => promptValue.toString()); + return this.generate(prompts, options, callbacks); + } + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; + } + _flattenLLMResult(llmResult) { + const llmResults = []; + for (let i = 0; i < llmResult.generations.length; i += 1) { + const genList = llmResult.generations[i]; + if (i === 0) { + llmResults.push({ + generations: [genList], + llmOutput: llmResult.llmOutput, + }); + } + else { + const llmOutput = llmResult.llmOutput + ? { ...llmResult.llmOutput, tokenUsage: {} } + : undefined; + llmResults.push({ + generations: [genList], + llmOutput, + }); + } + } + return llmResults; + } + /** @ignore */ + async _generateUncached(prompts, parsedOptions, handledOptions) { + const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, undefined, undefined, extra); + let output; + try { + output = await this._generate(prompts, parsedOptions, runManagers?.[0]); + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + const flattenedOutputs = this._flattenLLMResult(output); + await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); + const runIds = runManagers?.map((manager) => manager.runId) || undefined; + // This defines RUN_KEY as a non-enumerable property on the output object + // so that it is not serialized when the output is stringified, and so that + // it isnt included when listing the keys of the output object. + Object.defineProperty(output, schema/* RUN_KEY */.WH, { + value: runIds ? { runIds } : undefined, + configurable: true, + }); + return output; + } + /** + * Run the LLM on the given prompts and input, handling caching. + */ + async generate(prompts, options, callbacks) { + if (!Array.isArray(prompts)) { + throw new Error("Argument 'prompts' is expected to be a string[]"); + } + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } + else { + parsedOptions = options; + } + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(prompts, callOptions, runnableConfig); + } + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const missingPromptIndices = []; + const generations = await Promise.all(prompts.map(async (prompt, index) => { + const result = await cache.lookup(prompt, llmStringKey); + if (!result) { + missingPromptIndices.push(index); + } + return result; + })); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + return cache.update(prompts[promptIndex], llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; + } + /** + * Convenience wrapper for {@link generate} that takes in a single string prompt and returns a single string output. + */ + async call(prompt, options, callbacks) { + const { generations } = await this.generate([prompt], options, callbacks); + return generations[0][0].text; + } + /** + * This method is similar to `call`, but it's used for making predictions + * based on the input text. + * @param text Input text for the prediction. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns A prediction based on the input text. + */ + async predict(text, options, callbacks) { + return this.call(text, options, callbacks); + } + /** + * This method takes a list of messages, options, and callbacks, and + * returns a predicted message. + * @param messages A list of messages for the prediction. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns A predicted message based on the list of messages. + */ + async predictMessages(messages, options, callbacks) { + const text = (0,base/* getBufferString */.zs)(messages); + const prediction = await this.call(text, options, callbacks); + return new schema/* AIMessage */.gY(prediction); + } + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + _modelType() { + return "base_llm"; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(data) { + const { _type, _model, ...rest } = data; + if (_model && _model !== "base_llm") { + throw new Error(`Cannot load LLM with model ${_model}`); + } + const Cls = { + openai: (await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 4624))).OpenAI, + }[_type]; + if (Cls === undefined) { + throw new Error(`Cannot load LLM with type ${_type}`); + } + return new Cls(rest); + } +} +/** + * LLM class that provides a simpler interface to subclass than {@link BaseLLM}. + * + * Requires only implementing a simpler {@link _call} method instead of {@link _generate}. + * + * @augments BaseLLM + */ +class LLM extends BaseLLM { + async _generate(prompts, options, runManager) { + const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { ...options, promptIndex }, runManager).then((text) => [{ text }]))); + return { generations }; + } +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/openai.js +var util_openai = __webpack_require__(8311); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/llms/openai-chat.js + + + + + + + +/** + * Wrapper around OpenAI large language models that use the Chat endpoint. + * + * To use you should have the `openai` package installed, with the + * `OPENAI_API_KEY` environment variable set. + * + * To use with Azure you should have the `openai` package installed, with the + * `AZURE_OPENAI_API_KEY`, + * `AZURE_OPENAI_API_INSTANCE_NAME`, + * `AZURE_OPENAI_API_DEPLOYMENT_NAME` + * and `AZURE_OPENAI_API_VERSION` environment variable set. + * + * @remarks + * Any parameters that are valid to be passed to {@link + * https://platform.openai.com/docs/api-reference/chat/create | + * `openai.createCompletion`} can be passed through {@link modelKwargs}, even + * if not explicitly available on this class. + * + * @augments BaseLLM + * @augments OpenAIInput + * @augments AzureOpenAIChatInput + */ +class OpenAIChat extends LLM { + static lc_name() { + return "OpenAIChat"; + } + get callKeys() { + return [...super.callKeys, "options", "promptIndex"]; + } + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION", + }; + } + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + azureOpenAIApiVersion: "azure_openai_api_version", + azureOpenAIApiKey: "azure_openai_api_key", + azureOpenAIApiInstanceName: "azure_openai_api_instance_name", + azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", + }; + } + constructor(fields, + /** @deprecated */ + configuration) { + super(fields ?? {}); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "temperature", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "topP", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "frequencyPenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "presencePenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "n", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "logitBias", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelName", { + enumerable: true, + configurable: true, + writable: true, + value: "gpt-3.5-turbo" + }); + Object.defineProperty(this, "prefixMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stop", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "user", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "streaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "openAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiVersion", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiInstanceName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiDeploymentName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIBasePath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "organization", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.openAIApiKey = + fields?.openAIApiKey ?? (0,env/* getEnvironmentVariable */.lS)("OPENAI_API_KEY"); + this.azureOpenAIApiKey = + fields?.azureOpenAIApiKey ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_KEY"); + if (!this.azureOpenAIApiKey && !this.openAIApiKey) { + throw new Error("OpenAI or Azure OpenAI API key not found"); + } + this.azureOpenAIApiInstanceName = + fields?.azureOpenAIApiInstanceName ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = + (fields?.azureOpenAIApiCompletionsDeploymentName || + fields?.azureOpenAIApiDeploymentName) ?? + ((0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_DEPLOYMENT_NAME")); + this.azureOpenAIApiVersion = + fields?.azureOpenAIApiVersion ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = + fields?.azureOpenAIBasePath ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_BASE_PATH"); + this.organization = + fields?.configuration?.organization ?? + (0,env/* getEnvironmentVariable */.lS)("OPENAI_ORGANIZATION"); + this.modelName = fields?.modelName ?? this.modelName; + this.prefixMessages = fields?.prefixMessages ?? this.prefixMessages; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.n = fields?.n ?? this.n; + this.logitBias = fields?.logitBias; + this.maxTokens = fields?.maxTokens; + this.stop = fields?.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.n > 1) { + throw new Error("Cannot use n > 1 in OpenAIChat LLM. Use ChatOpenAI Chat Model instead."); + } + if (this.azureOpenAIApiKey) { + if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { + throw new Error("Azure OpenAI API instance name not found"); + } + if (!this.azureOpenAIApiDeploymentName) { + throw new Error("Azure OpenAI API deployment name not found"); + } + if (!this.azureOpenAIApiVersion) { + throw new Error("Azure OpenAI API version not found"); + } + this.openAIApiKey = this.openAIApiKey ?? ""; + } + this.clientConfig = { + apiKey: this.openAIApiKey, + organization: this.organization, + baseURL: configuration?.basePath ?? fields?.configuration?.basePath, + dangerouslyAllowBrowser: true, + defaultHeaders: configuration?.baseOptions?.headers ?? + fields?.configuration?.baseOptions?.headers, + defaultQuery: configuration?.baseOptions?.params ?? + fields?.configuration?.baseOptions?.params, + ...configuration, + ...fields?.configuration, + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.modelName, + temperature: this.temperature, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + n: this.n, + logit_bias: this.logitBias, + max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens, + stop: options?.stop ?? this.stop, + user: this.user, + stream: this.streaming, + ...this.modelKwargs, + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + /** + * Formats the messages for the OpenAI API. + * @param prompt The prompt to be formatted. + * @returns Array of formatted messages. + */ + formatMessages(prompt) { + const message = { + role: "user", + content: prompt, + }; + return this.prefixMessages ? [...this.prefixMessages, message] : [message]; + } + async *_streamResponseChunks(prompt, options, runManager) { + const params = { + ...this.invocationParams(options), + messages: this.formatMessages(prompt), + stream: true, + }; + const stream = await this.completionWithRetry(params, options); + for await (const data of stream) { + const choice = data?.choices[0]; + if (!choice) { + continue; + } + const { delta } = choice; + const generationChunk = new schema/* GenerationChunk */.b6({ + text: delta.content ?? "", + }); + yield generationChunk; + const newTokenIndices = { + prompt: options.promptIndex ?? 0, + completion: choice.index ?? 0, + }; + // eslint-disable-next-line no-void + void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices); + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } + } + /** @ignore */ + async _call(prompt, options, runManager) { + const params = this.invocationParams(options); + if (params.stream) { + const stream = await this._streamResponseChunks(prompt, options, runManager); + let finalChunk; + for await (const chunk of stream) { + if (finalChunk === undefined) { + finalChunk = chunk; + } + else { + finalChunk = finalChunk.concat(chunk); + } + } + return finalChunk?.text ?? ""; + } + else { + const response = await this.completionWithRetry({ + ...params, + stream: false, + messages: this.formatMessages(prompt), + }, { + signal: options.signal, + ...options.options, + }); + return response?.choices[0]?.message?.content ?? ""; + } + } + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.chat.completions.create(request, requestOptions); + return res; + } + catch (e) { + const error = (0,util_openai/* wrapOpenAIClientError */.K)(e); + throw error; + } + }); + } + /** @ignore */ + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + baseURL: this.clientConfig.baseURL, + }; + const endpoint = (0,azure/* getEndpoint */.O)(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0, + }; + if (!params.baseURL) { + delete params.baseURL; + } + this.client = new openai/* OpenAI */.Pp(params); + } + const requestOptions = { + ...this.clientConfig, + ...options, + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers, + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query, + }; + } + return requestOptions; + } + _llmType() { + return "openai"; + } +} +/** + * PromptLayer wrapper to OpenAIChat + */ +class PromptLayerOpenAIChat extends OpenAIChat { + get lc_secrets() { + return { + promptLayerApiKey: "PROMPTLAYER_API_KEY", + }; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "promptLayerApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "plTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnPromptLayerId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.plTags = fields?.plTags ?? []; + this.returnPromptLayerId = fields?.returnPromptLayerId ?? false; + this.promptLayerApiKey = + fields?.promptLayerApiKey ?? + (0,env/* getEnvironmentVariable */.lS)("PROMPTLAYER_API_KEY"); + if (!this.promptLayerApiKey) { + throw new Error("Missing PromptLayer API key"); + } + } + async _generate(prompts, options, runManager) { + let choice; + const generations = await Promise.all(prompts.map(async (prompt) => { + const requestStartTime = Date.now(); + const text = await this._call(prompt, options, runManager); + const requestEndTime = Date.now(); + choice = [{ text }]; + const parsedResp = { + text, + }; + const promptLayerRespBody = await (0,prompt_layer/* promptLayerTrackRequest */.r)(this.caller, "langchain.PromptLayerOpenAIChat", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { ...this._identifyingParams(), prompt }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); + if (this.returnPromptLayerId === true && + promptLayerRespBody.success === true) { + choice[0].generationInfo = { + promptLayerRequestId: promptLayerRespBody.request_id, + }; + } + return choice; + })); + return { generations }; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/llms/openai.js + + + + + + + + + + +/** + * Wrapper around OpenAI large language models. + * + * To use you should have the `openai` package installed, with the + * `OPENAI_API_KEY` environment variable set. + * + * To use with Azure you should have the `openai` package installed, with the + * `AZURE_OPENAI_API_KEY`, + * `AZURE_OPENAI_API_INSTANCE_NAME`, + * `AZURE_OPENAI_API_DEPLOYMENT_NAME` + * and `AZURE_OPENAI_API_VERSION` environment variable set. + * + * @remarks + * Any parameters that are valid to be passed to {@link + * https://platform.openai.com/docs/api-reference/completions/create | + * `openai.createCompletion`} can be passed through {@link modelKwargs}, even + * if not explicitly available on this class. + */ +class OpenAI extends BaseLLM { + static lc_name() { + return "OpenAI"; + } + get callKeys() { + return [...super.callKeys, "options"]; + } + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION", + }; + } + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + azureOpenAIApiVersion: "azure_openai_api_version", + azureOpenAIApiKey: "azure_openai_api_key", + azureOpenAIApiInstanceName: "azure_openai_api_instance_name", + azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", + }; + } + constructor(fields, + /** @deprecated */ + configuration) { + if ((fields?.modelName?.startsWith("gpt-3.5-turbo") || + fields?.modelName?.startsWith("gpt-4")) && + !fields?.modelName?.includes("-instruct")) { + // eslint-disable-next-line no-constructor-return + return new OpenAIChat(fields, configuration); + } + super(fields ?? {}); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "temperature", { + enumerable: true, + configurable: true, + writable: true, + value: 0.7 + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: 256 + }); + Object.defineProperty(this, "topP", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "frequencyPenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "presencePenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "n", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "bestOf", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "logitBias", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelName", { + enumerable: true, + configurable: true, + writable: true, + value: "text-davinci-003" + }); + Object.defineProperty(this, "modelKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchSize", { + enumerable: true, + configurable: true, + writable: true, + value: 20 + }); + Object.defineProperty(this, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stop", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "user", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "streaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "openAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiVersion", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiInstanceName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiDeploymentName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIBasePath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "organization", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.openAIApiKey = + fields?.openAIApiKey ?? (0,env/* getEnvironmentVariable */.lS)("OPENAI_API_KEY"); + this.azureOpenAIApiKey = + fields?.azureOpenAIApiKey ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_KEY"); + if (!this.azureOpenAIApiKey && !this.openAIApiKey) { + throw new Error("OpenAI or Azure OpenAI API key not found"); + } + this.azureOpenAIApiInstanceName = + fields?.azureOpenAIApiInstanceName ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = + (fields?.azureOpenAIApiCompletionsDeploymentName || + fields?.azureOpenAIApiDeploymentName) ?? + ((0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_DEPLOYMENT_NAME")); + this.azureOpenAIApiVersion = + fields?.azureOpenAIApiVersion ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = + fields?.azureOpenAIBasePath ?? + (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_BASE_PATH"); + this.organization = + fields?.configuration?.organization ?? + (0,env/* getEnvironmentVariable */.lS)("OPENAI_ORGANIZATION"); + this.modelName = fields?.modelName ?? this.modelName; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.batchSize = fields?.batchSize ?? this.batchSize; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.maxTokens = fields?.maxTokens ?? this.maxTokens; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.n = fields?.n ?? this.n; + this.bestOf = fields?.bestOf ?? this.bestOf; + this.logitBias = fields?.logitBias; + this.stop = fields?.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.streaming && this.bestOf && this.bestOf > 1) { + throw new Error("Cannot stream results when bestOf > 1"); + } + if (this.azureOpenAIApiKey) { + if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { + throw new Error("Azure OpenAI API instance name not found"); + } + if (!this.azureOpenAIApiDeploymentName) { + throw new Error("Azure OpenAI API deployment name not found"); + } + if (!this.azureOpenAIApiVersion) { + throw new Error("Azure OpenAI API version not found"); + } + this.openAIApiKey = this.openAIApiKey ?? ""; + } + this.clientConfig = { + apiKey: this.openAIApiKey, + organization: this.organization, + baseURL: configuration?.basePath ?? fields?.configuration?.basePath, + dangerouslyAllowBrowser: true, + defaultHeaders: configuration?.baseOptions?.headers ?? + fields?.configuration?.baseOptions?.headers, + defaultQuery: configuration?.baseOptions?.params ?? + fields?.configuration?.baseOptions?.params, + ...configuration, + ...fields?.configuration, + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.modelName, + temperature: this.temperature, + max_tokens: this.maxTokens, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + n: this.n, + best_of: this.bestOf, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stop, + user: this.user, + stream: this.streaming, + ...this.modelKwargs, + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); + } + /** + * Call out to OpenAI's endpoint with k unique prompts + * + * @param [prompts] - The prompts to pass into the model. + * @param [options] - Optional list of stop words to use when generating. + * @param [runManager] - Optional callback manager to use when generating. + * + * @returns The full LLM output. + * + * @example + * ```ts + * import { OpenAI } from "langchain/llms/openai"; + * const openai = new OpenAI(); + * const response = await openai.generate(["Tell me a joke."]); + * ``` + */ + async _generate(prompts, options, runManager) { + const subPrompts = chunkArray(prompts, this.batchSize); + const choices = []; + const tokenUsage = {}; + const params = this.invocationParams(options); + if (params.max_tokens === -1) { + if (prompts.length !== 1) { + throw new Error("max_tokens set to -1 not supported for multiple inputs"); + } + params.max_tokens = await (0,count_tokens/* calculateMaxTokens */.F1)({ + prompt: prompts[0], + // Cast here to allow for other models that may not fit the union + modelName: this.modelName, + }); + } + for (let i = 0; i < subPrompts.length; i += 1) { + const data = params.stream + ? await (async () => { + const choices = []; + let response; + const stream = await this.completionWithRetry({ + ...params, + stream: true, + prompt: subPrompts[i], + }, options); + for await (const message of stream) { + // on the first message set the response properties + if (!response) { + response = { + id: message.id, + object: message.object, + created: message.created, + model: message.model, + }; + } + // on all messages, update choice + for (const part of message.choices) { + if (!choices[part.index]) { + choices[part.index] = part; + } + else { + const choice = choices[part.index]; + choice.text += part.text; + choice.finish_reason = part.finish_reason; + choice.logprobs = part.logprobs; + } + void runManager?.handleLLMNewToken(part.text, { + prompt: Math.floor(part.index / this.n), + completion: part.index % this.n, + }); + } + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } + return { ...response, choices }; + })() + : await this.completionWithRetry({ + ...params, + stream: false, + prompt: subPrompts[i], + }, { + signal: options.signal, + ...options.options, + }); + choices.push(...data.choices); + const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage + ? data.usage + : { + completion_tokens: undefined, + prompt_tokens: undefined, + total_tokens: undefined, + }; + if (completionTokens) { + tokenUsage.completionTokens = + (tokenUsage.completionTokens ?? 0) + completionTokens; + } + if (promptTokens) { + tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; + } + if (totalTokens) { + tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; + } + } + const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ + text: choice.text ?? "", + generationInfo: { + finishReason: choice.finish_reason, + logprobs: choice.logprobs, + }, + }))); + return { + generations, + llmOutput: { tokenUsage }, + }; + } + // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation? + async *_streamResponseChunks(input, options, runManager) { + const params = { + ...this.invocationParams(options), + prompt: input, + stream: true, + }; + const stream = await this.completionWithRetry(params, options); + for await (const data of stream) { + const choice = data?.choices[0]; + if (!choice) { + continue; + } + const chunk = new schema/* GenerationChunk */.b6({ + text: choice.text, + generationInfo: { + finishReason: choice.finish_reason, + }, + }); + yield chunk; + // eslint-disable-next-line no-void + void runManager?.handleLLMNewToken(chunk.text ?? ""); + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } + } + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.completions.create(request, requestOptions); + return res; + } + catch (e) { + const error = (0,util_openai/* wrapOpenAIClientError */.K)(e); + throw error; + } + }); + } + /** + * Calls the OpenAI API with retry logic in case of failures. + * @param request The request to send to the OpenAI API. + * @param options Optional configuration for the API call. + * @returns The response from the OpenAI API. + */ + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + baseURL: this.clientConfig.baseURL, + }; + const endpoint = (0,azure/* getEndpoint */.O)(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0, + }; + if (!params.baseURL) { + delete params.baseURL; + } + this.client = new openai/* OpenAI */.Pp(params); + } + const requestOptions = { + ...this.clientConfig, + ...options, + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers, + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query, + }; + } + return requestOptions; + } + _llmType() { + return "openai"; + } +} +/** + * PromptLayer wrapper to OpenAI + * @augments OpenAI + */ +class PromptLayerOpenAI extends OpenAI { + get lc_secrets() { + return { + promptLayerApiKey: "PROMPTLAYER_API_KEY", + }; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "promptLayerApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "plTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnPromptLayerId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.plTags = fields?.plTags ?? []; + this.promptLayerApiKey = + fields?.promptLayerApiKey ?? + (0,env/* getEnvironmentVariable */.lS)("PROMPTLAYER_API_KEY"); + this.returnPromptLayerId = fields?.returnPromptLayerId; + if (!this.promptLayerApiKey) { + throw new Error("Missing PromptLayer API key"); + } + } + async _generate(prompts, options, runManager) { + const requestStartTime = Date.now(); + const generations = await super._generate(prompts, options, runManager); + for (let i = 0; i < generations.generations.length; i += 1) { + const requestEndTime = Date.now(); + const parsedResp = { + text: generations.generations[i][0].text, + llm_output: generations.llmOutput, + }; + const promptLayerRespBody = await (0,prompt_layer/* promptLayerTrackRequest */.r)(this.caller, "langchain.PromptLayerOpenAI", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { ...this._identifyingParams(), prompt: prompts[i] }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); + let promptLayerRequestId; + if (this.returnPromptLayerId === true) { + if (promptLayerRespBody && promptLayerRespBody.success === true) { + promptLayerRequestId = promptLayerRespBody.request_id; + } + generations.generations[i][0].generationInfo = { + ...generations.generations[i][0].generationInfo, + promptLayerRequestId, + }; + } + } + return generations; + } +} + + + +/***/ }) + +}; diff --git a/dist/657.index.js b/dist/657.index.js new file mode 100644 index 0000000..f870bf6 --- /dev/null +++ b/dist/657.index.js @@ -0,0 +1,6928 @@ +export const id = 657; +export const ids = [657]; +export const modules = { + +/***/ 8882: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "E": () => (/* binding */ BaseCallbackHandler) +/* harmony export */ }); +/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1273); +/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4432); + + +/** + * Abstract class that provides a set of optional methods that can be + * overridden in derived classes to handle various events during the + * execution of a LangChain application. + */ +class BaseCallbackHandlerMethodsClass { +} +/** + * Abstract base class for creating callback handlers in the LangChain + * framework. It provides a set of optional methods that can be overridden + * in derived classes to handle various events during the execution of a + * LangChain application. + */ +class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { + get lc_namespace() { + return ["langchain", "callbacks", this.name]; + } + get lc_secrets() { + return undefined; + } + get lc_attributes() { + return undefined; + } + get lc_aliases() { + return undefined; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + (0,_load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .get_lc_unique_name */ .j)(this.constructor), + ]; + } + constructor(input) { + super(); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "ignoreLLM", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreChain", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreAgent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreRetriever", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "awaitHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.LANGCHAIN_CALLBACKS_BACKGROUND !== "true" + : true + }); + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable.prototype.toJSON.call */ .i.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable.prototype.toJSONNotImplemented.call */ .i.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: uuid__WEBPACK_IMPORTED_MODULE_1__.v4() + }); + Object.assign(this, methods); + } + } + return new Handler(); + } +} + + +/***/ }), + +/***/ 8763: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Z": () => (/* binding */ BaseTracer) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8882); + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; +} +class BaseTracer extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseCallbackHandler */ .E { + constructor(_fields) { + super(...arguments); + Object.defineProperty(this, "runMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + } + copy() { + return this; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + async _startTrace(run) { + if (run.parent_run_id !== undefined) { + const parentRun = this.runMap.get(run.parent_run_id); + if (parentRun) { + this._addChildRun(parentRun, run); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } + } + this.runMap.set(run.id, run); + await this.onRunCreate?.(run); + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); + if (parentRun) { + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } + else { + await this.persistRun(run); + } + this.runMap.delete(run.id); + await this.onRunUpdate?.(run); + } + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); + // If a run has no parent then execution order is 1 + if (!parentRun) { + return 1; + } + return parentRun.child_execution_order + 1; + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { prompts }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onLLMStart?.(run); + return run; + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; + } + async handleLLMError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onLLMError?.(run); + await this._endTrace(run); + return run; + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.runMap.get(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.runMap.get(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool.id[tool.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onToolStart?.(run); + return run; + } + async handleToolEnd(output, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; + } + async handleToolError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onToolError?.(run); + await this._endTrace(run); + return run; + } + async handleAgentAction(action, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: new Date().toISOString(), + kwargs: { action }, + }); + await this.onAgentAction?.(run); + } + async handleAgentEnd(action, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "agent_end", + time: new Date().toISOString(), + kwargs: { action }, + }); + await this.onAgentEnd?.(run); + } + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; + } + async handleRetrieverError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; + } + async handleText(text, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "text", + time: new Date().toISOString(), + kwargs: { text }, + }); + await this.onText?.(run); + } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + } + run.events.push({ + name: "new_token", + time: new Date().toISOString(), + kwargs: { token, idx, chunk: fields?.chunk }, + }); + await this.onLLMNewToken?.(run, token); + return run; + } +} + + +/***/ }), + +/***/ 6009: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "Ye": () => (/* binding */ CallbackManager), + "QH": () => (/* binding */ parseCallbackConfigArg) +}); + +// UNUSED EXPORTS: BaseCallbackManager, CallbackManagerForChainRun, CallbackManagerForLLMRun, CallbackManagerForRetrieverRun, CallbackManagerForToolRun, TraceGroup, traceAsGroup + +// EXTERNAL MODULE: ./node_modules/langchain/node_modules/uuid/wrapper.mjs +var wrapper = __webpack_require__(1273); +// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/base.js +var base = __webpack_require__(8882); +// EXTERNAL MODULE: ./node_modules/langchain/node_modules/ansi-styles/index.js +var ansi_styles = __webpack_require__(8964); +// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer.js +var tracer = __webpack_require__(8763); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/console.js + + +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); + } + catch (err) { + return fallback; + } +} +function elapsed(run) { + if (!run.end_time) + return ""; + const elapsed = run.end_time - run.start_time; + if (elapsed < 1000) { + return `${elapsed}ms`; + } + return `${(elapsed / 1000).toFixed(2)}s`; +} +const { color } = ansi_styles; +/** + * A tracer that logs all events to the console. It extends from the + * `BaseTracer` class and overrides its methods to provide custom logging + * functionality. + */ +class ConsoleCallbackHandler extends tracer/* BaseTracer */.Z { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "console_callback_handler" + }); + } + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + // utility methods + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; + } + else { + break; + } + } + return parents; + } + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string = [...parents, run] + .map((parent, i, arr) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; + }) + .join(" > "); + return wrap(color.grey, string); + } + // logging methods + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs + ? { prompts: run.inputs.prompts.map((p) => p.trim()) } + : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); + } + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${run.inputs.input?.trim()}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${run.outputs?.output?.trim()}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + } +} + +// EXTERNAL MODULE: ./node_modules/langsmith/node_modules/uuid/dist/index.js +var dist = __webpack_require__(9097); +;// CONCATENATED MODULE: ./node_modules/langsmith/node_modules/uuid/wrapper.mjs + +const v1 = dist.v1; +const v3 = dist.v3; +const v4 = dist.v4; +const v5 = dist.v5; +const NIL = dist.NIL; +const version = dist.version; +const validate = dist.validate; +const stringify = dist.stringify; +const parse = dist.parse; + +// EXTERNAL MODULE: ./node_modules/p-retry/index.js +var p_retry = __webpack_require__(2548); +// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js +var p_queue_dist = __webpack_require__(8983); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js + + +const STATUS_NO_RETRY = [ + 400, + 401, + 403, + 404, + 405, + 406, + 407, + 408, + 409, // Conflict +]; +/** + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. + */ +class AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } + }), { + onFailedAttempt(error) { + if (error.message.startsWith("Cancel") || + error.message.startsWith("TimeoutError") || + error.message.startsWith("AbortError")) { + throw error; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { + throw error; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const status = error?.response?.status; + if (status && STATUS_NO_RETRY.includes(+status)) { + throw error; + } + }, + retries: this.maxRetries, + randomize: true, + // If needed we can change some of the defaults here, + // but they're quite sensible. + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js +function isLangChainMessage(message) { + return typeof message?._getType === "function"; +} +function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content }, + }; + // Check for presence of keys in additional_kwargs + if (message?.additional_kwargs && + Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; + } + return converted; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js +const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && + (navigator.userAgent.includes("Node.js") || + navigator.userAgent.includes("jsdom"))); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !isDeno(); +const getEnv = () => { + let env; + if (isBrowser()) { + env = "browser"; + } + else if (isNode()) { + env = "node"; + } + else if (isWebWorker()) { + env = "webworker"; + } + else if (isJsDom()) { + env = "jsdom"; + } + else if (isDeno()) { + env = "deno"; + } + else { + env = "other"; + } + return env; +}; +let runtimeEnvironment; +async function env_getRuntimeEnvironment() { + if (runtimeEnvironment === undefined) { + const env = getEnv(); + const releaseEnv = getShas(); + runtimeEnvironment = { + library: "langsmith", + runtime: env, + ...releaseEnv, + }; + } + return runtimeEnvironment; +} +/** + * Retrieves the LangChain-specific environment variables from the current runtime environment. + * Sensitive keys (containing the word "key") have their values redacted for security. + * + * @returns {Record} + * - A record of LangChain-specific environment variables. + */ +function getLangChainEnvVars() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + for (const [key, value] of Object.entries(allEnvVars)) { + if (key.startsWith("LANGCHAIN_") && typeof value === "string") { + envVars[key] = value; + } + } + for (const key in envVars) { + if (key.toLowerCase().includes("key") && typeof envVars[key] === "string") { + const value = envVars[key]; + envVars[key] = + value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); + } + } + return envVars; +} +/** + * Retrieves the environment variables from the current runtime environment. + * + * This function is designed to operate in a variety of JS environments, + * including Node.js, Deno, browsers, etc. + * + * @returns {Record | undefined} + * - A record of environment variables if available. + * - `undefined` if the environment does not support or allows access to environment variables. + */ +function getEnvironmentVariables() { + try { + // Check for Node.js environment + // eslint-disable-next-line no-process-env + if (typeof process !== "undefined" && process.env) { + // eslint-disable-next-line no-process-env + Object.entries(process.env).reduce((acc, [key, value]) => { + acc[key] = String(value); + return acc; + }, {}); + } + // For browsers and other environments, we may not have direct access to env variables + // Return undefined or any other fallback as required. + return undefined; + } + catch (e) { + // Catch any errors that might occur while trying to access environment variables + return undefined; + } +} +function env_getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/hwchase17/langchainjs/issues/1412 + try { + return typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.[name] + : undefined; + } + catch (e) { + return undefined; + } +} +function setEnvironmentVariable(name, value) { + if (typeof process !== "undefined") { + // eslint-disable-next-line no-process-env + process.env[name] = value; + } +} +let cachedCommitSHAs; +/** + * Get the Git commit SHA from common environment variables + * used by different CI/CD platforms. + * @returns {string | undefined} The Git commit SHA or undefined if not found. + */ +function getShas() { + if (cachedCommitSHAs !== undefined) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT", + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = env_getEnvironmentVariable(env); + if (envVar !== undefined) { + shas[env] = envVar; + } + } + cachedCommitSHAs = shas; + return shas; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js + + + + +// utility functions +const isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); +}; +const raiseForStatus = async (response, operation) => { + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + const body = await response.text(); + if (!response.ok) { + throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`); + } +}; +async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return result; +} +function trimQuotes(str) { + if (str === undefined) { + return undefined; + } + return str + .trim() + .replace(/^"(.*)"$/, "$1") + .replace(/^'(.*)'$/, "$1"); +} +function hideInputs(inputs) { + if (env_getEnvironmentVariable("LANGCHAIN_HIDE_INPUTS") === "true") { + return {}; + } + return inputs; +} +function hideOutputs(outputs) { + if (env_getEnvironmentVariable("LANGCHAIN_HIDE_OUTPUTS") === "true") { + return {}; + } + return outputs; +} +class client_Client { + constructor(config = {}) { + Object.defineProperty(this, "apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "webUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + const defaultConfig = client_Client.getDefaultClientConfig(); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + this.validateApiKeyIfHosted(); + this.timeout_ms = config.timeout_ms ?? 4000; + this.caller = new AsyncCaller(config.callerOptions ?? {}); + } + static getDefaultClientConfig() { + const apiKey = env_getEnvironmentVariable("LANGCHAIN_API_KEY"); + const apiUrl = env_getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? + (apiKey ? "https://api.smith.langchain.com" : "http://localhost:1984"); + return { + apiUrl: apiUrl, + apiKey: apiKey, + webUrl: undefined, + }; + } + validateApiKeyIfHosted() { + const isLocal = isLocalhost(this.apiUrl); + if (!isLocal && !this.apiKey) { + throw new Error("API key must be provided when using hosted LangSmith API"); + } + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; + } + else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost"; + return "http://localhost"; + } + else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return "https://dev.smith.langchain.com"; + } + else { + this.webUrl = "https://smith.langchain.com"; + return "https://smith.langchain.com"; + } + } + get headers() { + const headers = {}; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; + } + return headers; + } + async _get(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(fetch, url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`); + } + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams()) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(fetch, url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`); + } + const items = await response.json(); + if (items.length === 0) { + break; + } + yield items; + if (items.length < limit) { + break; + } + offset += items.length; + } + } + async createRun(run) { + const headers = { ...this.headers, "Content-Type": "application/json" }; + const extra = run.extra ?? {}; + const runtimeEnv = await env_getRuntimeEnvironment(); + const session_name = run.project_name; + delete run.project_name; + const runCreate = { + session_name, + ...run, + extra: { + ...run.extra, + runtime: { + ...runtimeEnv, + ...extra.runtime, + }, + }, + }; + runCreate.inputs = hideInputs(runCreate.inputs); + if (runCreate.outputs) { + runCreate.outputs = hideOutputs(runCreate.outputs); + } + const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, { + method: "POST", + headers, + body: JSON.stringify(runCreate), + signal: AbortSignal.timeout(this.timeout_ms), + }); + await raiseForStatus(response, "create run"); + } + async updateRun(runId, run) { + if (run.inputs) { + run.inputs = hideInputs(run.inputs); + } + if (run.outputs) { + run.outputs = hideOutputs(run.outputs); + } + const headers = { ...this.headers, "Content-Type": "application/json" }; + const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + body: JSON.stringify(run), + signal: AbortSignal.timeout(this.timeout_ms), + }); + await raiseForStatus(response, "update run"); + } + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns && run.child_run_ids) { + run = await this._loadChildRuns(run); + } + return run; + } + async getRunUrl({ runId, run, projectOpts, }) { + if (run !== undefined) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; + } + else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + } + else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; + } + else { + const project = await this.readProject({ + projectName: env_getEnvironmentVariable("LANGCHAIN_PROJECT") || "default", + }); + sessionId = project.id; + } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; + } + else if (runId !== undefined) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); + } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; + } + else { + throw new Error("Must provide either runId or run"); + } + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ id: run.child_run_ids })); + const treemap = {}; + const runs = {}; + // TODO: make dotted order required when the migration finishes + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || + childRun.parent_run_id === undefined) { + throw new Error(`Child run ${childRun.id} has no parent`); + } + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; + } + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; + } + } + return run; + } + async *listRuns({ projectId, projectName, parentRunId, referenceExampleId, startTime, executionOrder, runType, error, id, limit, offset, query, filter, }) { + const queryParams = new URLSearchParams(); + let projectId_ = projectId; + if (projectName) { + if (projectId) { + throw new Error("Only one of projectId or projectName may be given"); + } + projectId_ = (await this.readProject({ projectName })).id; + } + if (projectId_) { + queryParams.append("session", projectId_); + } + if (parentRunId) { + queryParams.append("parent_run", parentRunId); + } + if (referenceExampleId) { + queryParams.append("reference_example", referenceExampleId); + } + if (startTime) { + queryParams.append("start_time", startTime.toISOString()); + } + if (executionOrder) { + queryParams.append("execution_order", executionOrder.toString()); + } + if (runType) { + queryParams.append("run_type", runType); + } + if (error !== undefined) { + queryParams.append("error", error.toString()); + } + if (id !== undefined) { + for (const id_ of id) { + queryParams.append("id", id_); + } + } + if (limit !== undefined) { + queryParams.append("limit", limit.toString()); + } + if (offset !== undefined) { + queryParams.append("offset", offset.toString()); + } + if (query !== undefined) { + queryParams.append("query", query); + } + if (filter !== undefined) { + queryParams.append("filter", filter); + } + for await (const runs of this._getPaginated("/runs", queryParams)) { + yield* runs; + } + } + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4(), + }; + const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async unshareRun(runId) { + const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + await raiseForStatus(response, "unshare run"); + } + async readRunSharedLink(runId) { + const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return undefined; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async createProject({ projectName, projectExtra, upsert, referenceDatasetId, }) { + const upsert_ = upsert ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const body = { + name: projectName, + }; + if (projectExtra !== undefined) { + body["extra"] = projectExtra; + } + if (referenceDatasetId !== undefined) { + body["reference_dataset_id"] = referenceDatasetId; + } + const response = await this.caller.call(fetch, endpoint, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + }); + const result = await response.json(); + if (!response.ok) { + throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`); + } + return result; + } + async readProject({ projectId, projectName, }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); + } + else { + throw new Error("Must provide projectName or projectId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; + } + else { + result = response; + } + return result; + } + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; + } + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; + } + throw new Error("No projects found to resolve tenant."); + } + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, } = {}) { + const params = new URLSearchParams(); + if (projectIds !== undefined) { + for (const projectId of projectIds) { + params.append("id", projectId); + } + } + if (name !== undefined) { + params.append("name", name); + } + if (nameContains !== undefined) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== undefined) { + params.append("reference_dataset", referenceDatasetId); + } + else if (referenceDatasetName !== undefined) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName, + }); + params.append("reference_dataset", dataset.id); + } + if (referenceFree !== undefined) { + params.append("reference_free", referenceFree.toString()); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; + } + } + async deleteProject({ projectId, projectName, }) { + let projectId_; + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide projectName or projectId"); + } + else if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId === undefined) { + projectId_ = (await this.readProject({ projectName })).id; + } + else { + projectId_ = projectId; + } + const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + await raiseForStatus(response, `delete session ${projectId_} (${projectName})`); + } + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); + } + if (dataType) { + formData.append("data_type", dataType); + } + if (name) { + formData.append("name", name); + } + const response = await this.caller.call(fetch, url, { + method: "POST", + headers: this.headers, + body: formData, + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + const result = await response.json(); + if (result.detail && result.detail.includes("already exists")) { + throw new Error(`Dataset ${fileName} already exists`); + } + throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`); + } + const result = await response.json(); + return result; + } + async createDataset(name, { description, dataType, } = {}) { + const body = { + name, + description, + }; + if (dataType) { + body.data_type = dataType; + } + const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + const result = await response.json(); + if (result.detail && result.detail.includes("already exists")) { + throw new Error(`Dataset ${name} already exists`); + } + throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`); + } + const result = await response.json(); + return result; + } + async readDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + // limit to 1 result + const params = new URLSearchParams({ limit: "1" }); + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId !== undefined) { + path += `/${datasetId}`; + } + else if (datasetName !== undefined) { + params.append("name", datasetName); + } + else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); + } + result = response[0]; + } + else { + result = response; + } + return result; + } + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString(), + }); + if (datasetIds !== undefined) { + for (const id_ of datasetIds) { + params.append("id", id_); + } + } + if (datasetName !== undefined) { + params.append("name", datasetName); + } + if (datasetNameContains !== undefined) { + params.append("name_contains", datasetNameContains); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; + } + } + async deleteDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + if (datasetId_ !== undefined) { + path += `/${datasetId_}`; + } + else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this.caller.call(fetch, this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); + } + await response.json(); + } + async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId }) { + let datasetId_ = datasetId; + if (datasetId_ === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + const createdAt_ = createdAt || new Date(); + const data = { + dataset_id: datasetId_, + inputs, + outputs, + created_at: createdAt_.toISOString(), + id: exampleId, + }; + const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to create example: ${response.status} ${response.statusText}`); + } + const result = await response.json(); + return result; + } + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); + } + return message; + }); + const finalOutput = isLangChainMessage(generations) + ? convertLangChainMessageToExample(generations) + : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + const path = `/examples/${exampleId}`; + return await this._get(path); + } + async *listExamples({ datasetId, datasetName, exampleIds, } = {}) { + let datasetId_; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId !== undefined) { + datasetId_ = datasetId; + } + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + throw new Error("Must provide a datasetName or datasetId"); + } + const params = new URLSearchParams({ dataset: datasetId_ }); + if (exampleIds !== undefined) { + for (const id_ of exampleIds) { + params.append("id", id_); + } + } + for await (const examples of this._getPaginated("/examples", params)) { + yield* examples; + } + } + async deleteExample(exampleId) { + const path = `/examples/${exampleId}`; + const response = await this.caller.call(fetch, this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); + } + await response.json(); + } + async updateExample(exampleId, update) { + const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(update), + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`); + } + const result = await response.json(); + return result; + } + async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, } = { loadChildRuns: false }) { + let run_; + if (typeof run === "string") { + run_ = await this.readRun(run, { loadChildRuns }); + } + else if (typeof run === "object" && "id" in run) { + run_ = run; + } + else { + throw new Error(`Invalid run type: ${typeof run}`); + } + let referenceExample = undefined; + if (run_.reference_example_id !== null && + run_.reference_example_id !== undefined) { + referenceExample = await this.readExample(run_.reference_example_id); + } + const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); + let sourceInfo_ = sourceInfo ?? {}; + if (feedbackResult.evaluatorInfo) { + sourceInfo_ = { ...sourceInfo_, ...feedbackResult.evaluatorInfo }; + } + return await this.createFeedback(run_.id, feedbackResult.key, { + score: feedbackResult.score, + value: feedbackResult.value, + comment: feedbackResult.comment, + correction: feedbackResult.correction, + sourceInfo: sourceInfo_, + feedbackSourceType: "model", + }); + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, }) { + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {}, + }; + if (sourceRunId !== undefined && + feedback_source?.metadata !== undefined && + !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + const feedback = { + id: feedbackId ?? v4(), + run_id: runId, + key, + score, + value, + correction, + comment, + feedback_source: feedback_source, + }; + const response = await this.caller.call(fetch, `${this.apiUrl}/feedback`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedback), + signal: AbortSignal.timeout(this.timeout_ms), + }); + await raiseForStatus(response, "create feedback"); + return feedback; + } + async updateFeedback(feedbackId, { score, value, correction, comment, }) { + const feedbackUpdate = {}; + if (score !== undefined && score !== null) { + feedbackUpdate["score"] = score; + } + if (value !== undefined && value !== null) { + feedbackUpdate["value"] = value; + } + if (correction !== undefined && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== undefined && comment !== null) { + feedbackUpdate["comment"] = comment; + } + const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedbackUpdate), + signal: AbortSignal.timeout(this.timeout_ms), + }); + await raiseForStatus(response, "update feedback"); + } + async readFeedback(feedbackId) { + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; + } + async deleteFeedback(feedbackId) { + const path = `/feedback/${feedbackId}`; + const response = await this.caller.call(fetch, this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + }); + if (!response.ok) { + throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); + } + await response.json(); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + queryParams.append("run", runIds.join(",")); + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); + } + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); + } + } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; + } + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js + + + +const warnedMessages = {}; +function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; + } +} +class RunTree { + constructor(config) { + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const defaultConfig = RunTree.getDefaultConfig(); + Object.assign(this, { ...defaultConfig, ...config }); + } + static getDefaultConfig() { + return { + id: uuid.v4(), + project_name: getEnvironmentVariable("LANGCHAIN_PROJECT") ?? + getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default", + child_runs: [], + execution_order: 1, + child_execution_order: 1, + api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time: Date.now(), + serialized: {}, + inputs: {}, + extra: {}, + client: new Client({}), + }; + } + async createChild(config) { + const child = new RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + client: this.client, + execution_order: this.child_execution_order + 1, + child_execution_order: this.child_execution_order + 1, + }); + this.child_runs.push(child); + return child; + } + async end(outputs, error, endTime = Date.now()) { + this.outputs = outputs; + this.error = error; + this.end_time = endTime; + if (this.parent_run) { + this.parent_run.child_execution_order = Math.max(this.parent_run.child_execution_order, this.child_execution_order); + } + } + async _convertToCreate(run, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + if (!runExtra.runtime) { + runExtra.runtime = {}; + } + const runtimeEnv = await getRuntimeEnvironment(); + for (const [k, v] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k]) { + runExtra.runtime[k] = v; + } + } + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = await Promise.all(run.child_runs.map((child_run) => this._convertToCreate(child_run, excludeChildRuns))); + parent_run_id = undefined; + } + else { + parent_run_id = run.parent_run?.id; + child_runs = []; + } + const persistedRun = { + id: run.id, + name: run.name, + start_time: run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + execution_order: run.execution_order, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs: child_runs, + parent_run_id: parent_run_id, + }; + return persistedRun; + } + async postRun(excludeChildRuns = true) { + const runCreate = await this._convertToCreate(this, true); + await this.client.createRun(runCreate); + if (!excludeChildRuns) { + warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); + } + } + } + async patchRun() { + const runUpdate = { + end_time: this.end_time, + error: this.error, + outputs: this.outputs, + parent_run_id: this.parent_run?.id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + }; + await this.client.updateRun(this.id, runUpdate); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js + + + +;// CONCATENATED MODULE: ./node_modules/langsmith/index.js + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/env.js +var env = __webpack_require__(5785); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer_langchain.js + + + +class tracer_langchain_LangChainTracer extends tracer/* BaseTracer */.Z { + constructor(fields = {}) { + super(fields); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" + }); + Object.defineProperty(this, "projectName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const { exampleId, projectName, client } = fields; + this.projectName = + projectName ?? + (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_PROJECT") ?? + (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_SESSION"); + this.exampleId = exampleId; + this.client = client ?? new client_Client({}); + } + async _convertToCreate(run, example_id = undefined) { + return { + ...run, + extra: { + ...run.extra, + runtime: await (0,env/* getRuntimeEnvironment */.sA)(), + }, + child_runs: undefined, + session_name: this.projectName, + reference_example_id: run.parent_run_id ? undefined : example_id, + }; + } + async persistRun(_run) { } + async _persistRunSingle(run) { + const persistedRun = await this._convertToCreate(run, this.exampleId); + await this.client.createRun(persistedRun); + } + async _updateRunSingle(run) { + const runUpdate = { + end_time: run.end_time, + error: run.error, + outputs: run.outputs, + events: run.events, + inputs: run.inputs, + }; + await this.client.updateRun(run.id, runUpdate); + } + async onRetrieverStart(run) { + await this._persistRunSingle(run); + } + async onRetrieverEnd(run) { + await this._updateRunSingle(run); + } + async onRetrieverError(run) { + await this._updateRunSingle(run); + } + async onLLMStart(run) { + await this._persistRunSingle(run); + } + async onLLMEnd(run) { + await this._updateRunSingle(run); + } + async onLLMError(run) { + await this._updateRunSingle(run); + } + async onChainStart(run) { + await this._persistRunSingle(run); + } + async onChainEnd(run) { + await this._updateRunSingle(run); + } + async onChainError(run) { + await this._updateRunSingle(run); + } + async onToolStart(run) { + await this._persistRunSingle(run); + } + async onToolEnd(run) { + await this._updateRunSingle(run); + } + async onToolError(run) { + await this._updateRunSingle(run); + } +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/memory/base.js +var memory_base = __webpack_require__(790); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer_langchain_v1.js + + + +class LangChainTracerV1 extends tracer/* BaseTracer */.Z { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" + }); + Object.defineProperty(this, "endpoint", { + enumerable: true, + configurable: true, + writable: true, + value: (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_ENDPOINT") || "http://localhost:1984" + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: { + "Content-Type": "application/json", + } + }); + Object.defineProperty(this, "session", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const apiKey = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_API_KEY"); + if (apiKey) { + this.headers["x-api-key"] = apiKey; + } + } + async newSession(sessionName) { + const sessionCreate = { + start_time: Date.now(), + name: sessionName, + }; + const session = await this.persistSession(sessionCreate); + this.session = session; + return session; + } + async loadSession(sessionName) { + const endpoint = `${this.endpoint}/sessions?name=${sessionName}`; + return this._handleSessionResponse(endpoint); + } + async loadDefaultSession() { + const endpoint = `${this.endpoint}/sessions?name=default`; + return this._handleSessionResponse(endpoint); + } + async convertV2RunToRun(run) { + const session = this.session ?? (await this.loadDefaultSession()); + const serialized = run.serialized; + let runResult; + if (run.run_type === "llm") { + const prompts = run.inputs.prompts + ? run.inputs.prompts + : run.inputs.messages.map((x) => (0,memory_base/* getBufferString */.zs)(x)); + const llmRun = { + uuid: run.id, + start_time: run.start_time, + end_time: run.end_time, + execution_order: run.execution_order, + child_execution_order: run.child_execution_order, + serialized, + type: run.run_type, + session_id: session.id, + prompts, + response: run.outputs, + }; + runResult = llmRun; + } + else if (run.run_type === "chain") { + const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); + const chainRun = { + uuid: run.id, + start_time: run.start_time, + end_time: run.end_time, + execution_order: run.execution_order, + child_execution_order: run.child_execution_order, + serialized, + type: run.run_type, + session_id: session.id, + inputs: run.inputs, + outputs: run.outputs, + child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), + child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), + child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"), + }; + runResult = chainRun; + } + else if (run.run_type === "tool") { + const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); + const toolRun = { + uuid: run.id, + start_time: run.start_time, + end_time: run.end_time, + execution_order: run.execution_order, + child_execution_order: run.child_execution_order, + serialized, + type: run.run_type, + session_id: session.id, + tool_input: run.inputs.input, + output: run.outputs?.output, + action: JSON.stringify(serialized), + child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), + child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), + child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"), + }; + runResult = toolRun; + } + else { + throw new Error(`Unknown run type: ${run.run_type}`); + } + return runResult; + } + async persistRun(run) { + let endpoint; + let v1Run; + if (run.run_type !== undefined) { + v1Run = await this.convertV2RunToRun(run); + } + else { + v1Run = run; + } + if (v1Run.type === "llm") { + endpoint = `${this.endpoint}/llm-runs`; + } + else if (v1Run.type === "chain") { + endpoint = `${this.endpoint}/chain-runs`; + } + else { + endpoint = `${this.endpoint}/tool-runs`; + } + const response = await fetch(endpoint, { + method: "POST", + headers: this.headers, + body: JSON.stringify(v1Run), + }); + if (!response.ok) { + console.error(`Failed to persist run: ${response.status} ${response.statusText}`); + } + } + async persistSession(sessionCreate) { + const endpoint = `${this.endpoint}/sessions`; + const response = await fetch(endpoint, { + method: "POST", + headers: this.headers, + body: JSON.stringify(sessionCreate), + }); + if (!response.ok) { + console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`); + return { + id: 1, + ...sessionCreate, + }; + } + return { + id: (await response.json()).id, + ...sessionCreate, + }; + } + async _handleSessionResponse(endpoint) { + const response = await fetch(endpoint, { + method: "GET", + headers: this.headers, + }); + let tracerSession; + if (!response.ok) { + console.error(`Failed to load session: ${response.status} ${response.statusText}`); + tracerSession = { + id: 1, + start_time: Date.now(), + }; + this.session = tracerSession; + return tracerSession; + } + const resp = (await response.json()); + if (resp.length === 0) { + tracerSession = { + id: 1, + start_time: Date.now(), + }; + this.session = tracerSession; + return tracerSession; + } + [tracerSession] = resp; + this.session = tracerSession; + return tracerSession; + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/initialize.js + + +/** + * Function that returns an instance of `LangChainTracerV1`. If a session + * is provided, it loads that session into the tracer; otherwise, it loads + * a default session. + * @param session Optional session to load into the tracer. + * @returns An instance of `LangChainTracerV1`. + */ +async function getTracingCallbackHandler(session) { + const tracer = new LangChainTracerV1(); + if (session) { + await tracer.loadSession(session); + } + else { + await tracer.loadDefaultSession(); + } + return tracer; +} +/** + * Function that returns an instance of `LangChainTracer`. It does not + * load any session data. + * @returns An instance of `LangChainTracer`. + */ +async function getTracingV2CallbackHandler() { + return new tracer_langchain_LangChainTracer(); +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/promises.js + +let queue; +/** + * Creates a queue using the p-queue library. The queue is configured to + * auto-start and has a concurrency of 1, meaning it will process tasks + * one at a time. + */ +function createQueue() { + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + return new PQueue({ + autoStart: true, + concurrency: 1, + }); +} +/** + * Consume a promise, either adding it to the queue or waiting for it to resolve + * @param promise Promise to consume + * @param wait Whether to wait for the promise to resolve or resolve immediately + */ +async function consumeCallback(promiseFn, wait) { + if (wait === true) { + await promiseFn(); + } + else { + if (typeof queue === "undefined") { + queue = createQueue(); + } + void queue.add(promiseFn); + } +} +/** + * Waits for all promises in the queue to resolve. If the queue is + * undefined, it immediately resolves a promise. + */ +function awaitAllCallbacks() { + return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/manager.js + + + + + + + + +function parseCallbackConfigArg(arg) { + if (!arg) { + return {}; + } + else if (Array.isArray(arg) || "name" in arg) { + return { callbacks: arg }; + } + else { + return arg; + } +} +/** + * Manage callbacks from different components of LangChain. + */ +class BaseCallbackManager { + setHandler(handler) { + return this.setHandlers([handler]); + } +} +/** + * Base class for run manager in LangChain. + */ +class BaseRunManager { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + Object.defineProperty(this, "runId", { + enumerable: true, + configurable: true, + writable: true, + value: runId + }); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: handlers + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableHandlers + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: tags + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableTags + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: metadata + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableMetadata + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: _parentRunId + }); + } + async handleText(text) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + } + }, handler.awaitHandlers))); + } +} +/** + * Manages callbacks for retriever runs. + */ +class CallbackManagerForRetrieverRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleRetriever`); + } + } + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (error) { + console.error(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManagerForLLMRun extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleLLMError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManagerForChainRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManagerForToolRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } +} +class CallbackManager extends BaseCallbackManager { + constructor(parentRunId) { + super(); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "callback_manager" + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.handlers = []; + this.inheritableHandlers = []; + this._parentRunId = parentRunId; + } + async handleLLMStart(llm, prompts, _runId = undefined, _parentRunId = undefined, extraParams = undefined) { + return Promise.all(prompts.map(async (prompt) => { + const runId = (0,wrapper.v4)(); + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMStart?.(llm, [prompt], runId, this._parentRunId, extraParams, this.tags, this.metadata); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, _runId = undefined, _parentRunId = undefined, extraParams = undefined) { + return Promise.all(messages.map(async (messageGroup) => { + const runId = (0,wrapper.v4)(); + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + if (handler.handleChatModelStart) + await handler.handleChatModelStart?.(llm, [messageGroup], runId, this._parentRunId, extraParams, this.tags, this.metadata); + else if (handler.handleLLMStart) { + const messageString = (0,memory_base/* getBufferString */.zs)(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId, this._parentRunId, extraParams, this.tags, this.metadata); + } + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = (0,wrapper.v4)(), runType = undefined) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool, input, runId = (0,wrapper.v4)()) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleRetrieverStart(retriever, query, runId = (0,wrapper.v4)(), _parentRunId = undefined) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) { + this.inheritableHandlers.push(handler); + } + } + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); + } + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) { + this.addHandler(handler, inherit); + } + } + addTags(tags, inherit = true) { + this.removeTags(tags); // Remove duplicates + this.tags.push(...tags); + if (inherit) { + this.inheritableTags.push(...tags); + } + } + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); + } + addMetadata(metadata, inherit = true) { + this.metadata = { ...this.metadata, ...metadata }; + if (inherit) { + this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + } + } + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; + } + } + copy(additionalHandlers = [], inherit = true) { + const manager = new CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); + } + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if ( + // Prevent multiple copies of console_callback_handler + manager.handlers + .filter((h) => h.name === "console_callback_handler") + .some((h) => h.name === handler.name)) { + continue; + } + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends base/* BaseCallbackHandler */.E { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: (0,wrapper.v4)() + }); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static async configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } + else { + callbackManager = inheritableHandlers; + } + callbackManager = callbackManager.copy(Array.isArray(localHandlers) + ? localHandlers.map(ensureHandler) + : localHandlers?.handlers, false); + } + const verboseEnabled = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_VERBOSE") || options?.verbose; + const tracingV2Enabled = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_TRACING_V2") === "true"; + const tracingEnabled = tracingV2Enabled || + ((0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) { + callbackManager = new CallbackManager(); + } + if (verboseEnabled && + !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && + !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + callbackManager.addHandler(await getTracingV2CallbackHandler(), true); + } + else { + const session = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_PROJECT") && + (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_SESSION"); + callbackManager.addHandler(await getTracingCallbackHandler(session), true); + } + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + return callbackManager; + } +} +function ensureHandler(handler) { + if ("name" in handler) { + return handler; + } + return base/* BaseCallbackHandler.fromMethods */.E.fromMethods(handler); +} +class TraceGroup { + constructor(groupName, options) { + Object.defineProperty(this, "groupName", { + enumerable: true, + configurable: true, + writable: true, + value: groupName + }); + Object.defineProperty(this, "options", { + enumerable: true, + configurable: true, + writable: true, + value: options + }); + Object.defineProperty(this, "runManager", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + async getTraceGroupCallbackManager(group_name, inputs, options) { + const cb = new LangChainTracer(options); + const cm = await CallbackManager.configure([cb]); + const runManager = await cm?.handleChainStart({ + lc: 1, + type: "not_implemented", + id: ["langchain", "callbacks", "groups", group_name], + }, inputs ?? {}); + if (!runManager) { + throw new Error("Failed to create run group callback manager."); + } + return runManager; + } + async start(inputs) { + if (!this.runManager) { + this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); + } + return this.runManager.getChild(); + } + async error(err) { + if (this.runManager) { + await this.runManager.handleChainError(err); + this.runManager = undefined; + } + } + async end(output) { + if (this.runManager) { + await this.runManager.handleChainEnd(output ?? {}); + this.runManager = undefined; + } + } +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function traceAsGroup(groupOptions, enclosedCode, ...args) { + const traceGroup = new TraceGroup(groupOptions.name, groupOptions); + const callbackManager = await traceGroup.start({ ...args }); + try { + const result = await enclosedCode(callbackManager, ...args); + await traceGroup.end(_coerceToDict(result, "output")); + return result; + } + catch (err) { + await traceGroup.error(err); + throw err; + } +} + + +/***/ }), + +/***/ 4432: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "i": () => (/* binding */ Serializable), + "j": () => (/* binding */ get_lc_unique_name) +}); + +// EXTERNAL MODULE: ./node_modules/decamelize/index.js +var decamelize = __webpack_require__(159); +// EXTERNAL MODULE: ./node_modules/langchain/node_modules/camelcase/index.js +var camelcase = __webpack_require__(996); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/load/map_keys.js + + +function keyToJson(key, map) { + return map?.[key] || decamelize(key); +} +function keyFromJson(key, map) { + return map?.[key] || camelCase(key); +} +function mapKeys(fields, mapper, map) { + const mapped = {}; + for (const key in fields) { + if (Object.hasOwn(fields, key)) { + mapped[mapper(key, map)] = fields[key]; + } + } + return mapped; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/load/serializable.js + +function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; +} +function replaceSecrets(root, secretsMap) { + const result = shallowCopy(root); + for (const [path, secretId] of Object.entries(secretsMap)) { + const [last, ...partsReverse] = path.split(".").reverse(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let current = result; + for (const part of partsReverse.reverse()) { + if (current[part] === undefined) { + break; + } + current[part] = shallowCopy(current[part]); + current = current[part]; + } + if (current[last] !== undefined) { + current[last] = { + lc: 1, + type: "secret", + id: [secretId], + }; + } + } + return result; +} +/** + * Get a unique name for the module, rather than parent class implementations. + * Should not be subclassed, subclass lc_name above instead. + */ +function get_lc_unique_name( +// eslint-disable-next-line @typescript-eslint/no-use-before-define +serializableClass) { + // "super" here would refer to the parent class of Serializable, + // when we want the parent class of the module actually calling this method. + const parentClass = Object.getPrototypeOf(serializableClass); + const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && + (typeof parentClass.lc_name !== "function" || + serializableClass.lc_name() !== parentClass.lc_name()); + if (lcNameIsSubclassed) { + return serializableClass.lc_name(); + } + else { + return serializableClass.name; + } +} +class Serializable { + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor), + ]; + } + /** + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. + */ + get lc_secrets() { + return undefined; + } + /** + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. + */ + get lc_attributes() { + return undefined; + } + /** + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. + */ + get lc_aliases() { + return undefined; + } + constructor(kwargs, ..._args) { + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.lc_kwargs = kwargs || {}; + } + toJSON() { + if (!this.lc_serializable) { + return this.toJSONNotImplemented(); + } + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + this.lc_kwargs instanceof Serializable || + typeof this.lc_kwargs !== "object" || + Array.isArray(this.lc_kwargs)) { + // We do not support serialization of classes with arg not a POJO + // I'm aware the check above isn't as strict as it could be + return this.toJSONNotImplemented(); + } + const aliases = {}; + const secrets = {}; + const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { + acc[key] = key in this ? this[key] : this.lc_kwargs[key]; + return acc; + }, {}); + // get secrets, attributes and aliases from all superclasses + for ( + // eslint-disable-next-line @typescript-eslint/no-this-alias + let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { + Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); + Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); + Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + } + // include all secrets used, even if not in kwargs, + // will be replaced with sentinel value in replaceSecrets + Object.keys(secrets).forEach((keyPath) => { + // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any + let read = this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let write = kwargs; + const [last, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === undefined) + return; + if (!(key in write) || write[key] === undefined) { + if (typeof read[key] === "object" && read[key] != null) { + write[key] = {}; + } + else if (Array.isArray(read[key])) { + write[key] = []; + } + } + read = read[key]; + write = write[key]; + } + if (last in read && read[last] !== undefined) { + write[last] = write[last] || read[last]; + } + }); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases), + }; + } + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id, + }; + } +} + + +/***/ }), + +/***/ 790: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "zs": () => (/* binding */ getBufferString) +/* harmony export */ }); +/* unused harmony exports BaseMemory, getInputValue, getOutputValue, getPromptInputKey */ +/** + * Abstract base class for memory in LangChain's Chains. Memory refers to + * the state in Chains. It can be used to store information about past + * executions of a Chain and inject that information into the inputs of + * future executions of the Chain. + */ +class BaseMemory { +} +const getValue = (values, key) => { + if (key !== undefined) { + return values[key]; + } + const keys = Object.keys(values); + if (keys.length === 1) { + return values[keys[0]]; + } +}; +/** + * This function is used by memory classes to select the input value + * to use for the memory. If there is only one input value, it is used. + * If there are multiple input values, the inputKey must be specified. + */ +const getInputValue = (inputValues, inputKey) => { + const value = getValue(inputValues, inputKey); + if (!value) { + const keys = Object.keys(inputValues); + throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); + } + return value; +}; +/** + * This function is used by memory classes to select the output value + * to use for the memory. If there is only one output value, it is used. + * If there are multiple output values, the outputKey must be specified. + * If no outputKey is specified, an error is thrown. + */ +const getOutputValue = (outputValues, outputKey) => { + const value = getValue(outputValues, outputKey); + if (!value) { + const keys = Object.keys(outputValues); + throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); + } + return value; +}; +/** + * This function is used by memory classes to get a string representation + * of the chat message history, based on the message content and role. + */ +function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m of messages) { + let role; + if (m._getType() === "human") { + role = humanPrefix; + } + else if (m._getType() === "ai") { + role = aiPrefix; + } + else if (m._getType() === "system") { + role = "System"; + } + else if (m._getType() === "function") { + role = "Function"; + } + else if (m._getType() === "generic") { + role = m.role; + } + else { + throw new Error(`Got unsupported message type: ${m}`); + } + const nameStr = m.name ? `${m.name}, ` : ""; + string_messages.push(`${role}: ${nameStr}${m.content}`); + } + return string_messages.join("\n"); +} +/** + * Function used by memory classes to get the key of the prompt input, + * excluding any keys that are memory variables or the "stop" key. If + * there is not exactly one prompt input key, an error is thrown. + */ +function getPromptInputKey(inputs, memoryVariables) { + const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); + if (promptInputKeys.length !== 1) { + throw new Error(`One input key expected, but got ${promptInputKeys.length}`); + } + return promptInputKeys[0]; +} + + +/***/ }), + +/***/ 5411: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Al": () => (/* binding */ BaseStringPromptTemplate), +/* harmony export */ "dy": () => (/* binding */ BasePromptTemplate), +/* harmony export */ "nw": () => (/* binding */ StringPromptValue) +/* harmony export */ }); +/* unused harmony export BaseExampleSelector */ +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4432); +/* harmony import */ var _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1972); +// Default generic "any" values are for backwards compatibility. +// Replace with "string" when we are comfortable with a breaking change. + + + +/** + * Represents a prompt value as a string. It extends the BasePromptValue + * class and overrides the toString and toChatMessages methods. + */ +class StringPromptValue extends _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BasePromptValue */ .MJ { + constructor(value) { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "prompts", "base"] + }); + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.value = value; + } + toString() { + return this.value; + } + toChatMessages() { + return [new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .HumanMessage */ .xk(this.value)]; + } +} +/** + * Base class for prompt templates. Exposes a format method that returns a + * string prompt given a set of input values. + */ +class BasePromptTemplate extends _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_2__/* .Runnable */ .eq { + get lc_attributes() { + return { + partialVariables: undefined, // python doesn't support this yet + }; + } + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "prompts", this._getPromptType()] + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "partialVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const { inputVariables } = input; + if (inputVariables.includes("stop")) { + throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); + } + Object.assign(this, input); + } + /** + * Merges partial variables and user variables. + * @param userVariables The user variables to merge with the partial variables. + * @returns A Promise that resolves to an object containing the merged variables. + */ + async mergePartialAndUserVariables(userVariables) { + const partialVariables = this.partialVariables ?? {}; + const partialValues = {}; + for (const [key, value] of Object.entries(partialVariables)) { + if (typeof value === "string") { + partialValues[key] = value; + } + else { + partialValues[key] = await value(); + } + } + const allKwargs = { + ...partialValues, + ...userVariables, + }; + return allKwargs; + } + /** + * Invokes the prompt template with the given input and options. + * @param input The input to invoke the prompt template with. + * @param options Optional configuration for the callback. + * @returns A Promise that resolves to the output of the prompt template. + */ + async invoke(input, options) { + return this._callWithConfig((input) => this.formatPromptValue(input), input, { ...options, runType: "prompt" }); + } + /** + * Return a json-like object representing this prompt template. + * @deprecated + */ + serialize() { + throw new Error("Use .toJSON() instead"); + } + /** + * @deprecated + * Load a prompt template from a json-like object describing it. + * + * @remarks + * Deserializing needs to be async because templates (e.g. {@link FewShotPromptTemplate}) can + * reference remote resources that we read asynchronously with a web + * request. + */ + static async deserialize(data) { + switch (data._type) { + case "prompt": { + const { PromptTemplate } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 4095)); + return PromptTemplate.deserialize(data); + } + case undefined: { + const { PromptTemplate } = await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 4095)); + return PromptTemplate.deserialize({ ...data, _type: "prompt" }); + } + case "few_shot": { + const { FewShotPromptTemplate } = await __webpack_require__.e(/* import() */ 806).then(__webpack_require__.bind(__webpack_require__, 609)); + return FewShotPromptTemplate.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } +} +/** + * Base class for string prompt templates. It extends the + * BasePromptTemplate class and overrides the formatPromptValue method to + * return a StringPromptValue. + */ +class BaseStringPromptTemplate extends BasePromptTemplate { + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + const formattedPrompt = await this.format(values); + return new StringPromptValue(formattedPrompt); + } +} +/** + * Base class for example selectors. + */ +class BaseExampleSelector extends (/* unused pure expression or super */ null && (Serializable)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "prompts", "selectors"] + }); + } +} + + +/***/ }), + +/***/ 4095: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "PromptTemplate": () => (/* binding */ PromptTemplate) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5411); +/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(837); +// Default generic "any" values are for backwards compatibility. +// Replace with "string" when we are comfortable with a breaking change. + + +/** + * Schema to represent a basic prompt for an LLM. + * @augments BasePromptTemplate + * @augments PromptTemplateInput + * + * @example + * ```ts + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = new PromptTemplate({ + * inputVariables: ["foo"], + * template: "Say {foo}", + * }); + * ``` + */ +class PromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { + static lc_name() { + return "PromptTemplate"; + } + constructor(input) { + super(input); + Object.defineProperty(this, "template", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.template, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "prompt"; + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(this.template, this.templateFormat, allValues); + } + /** + * Take examples in list format with prefix and suffix to create a prompt. + * + * Intended to be used a a way to dynamically create a prompt from examples. + * + * @param examples - List of examples to use in the prompt. + * @param suffix - String to go after the list of examples. Should generally set up the user's input. + * @param inputVariables - A list of variable names the final prompt template will expect + * @param exampleSeparator - The separator to use in between examples + * @param prefix - String that should go before any examples. Generally includes examples. + * + * @returns The final prompt template generated. + */ + static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { + const template = [prefix, ...examples, suffix].join(exampleSeparator); + return new PromptTemplate({ + inputVariables, + template, + }); + } + /** + * Load prompt template from a template f-string + */ + static fromTemplate(template, { templateFormat = "f-string", ...rest } = {}) { + if (templateFormat === "jinja2") { + throw new Error("jinja2 templates are not currently supported."); + } + const names = new Set(); + (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .parseTemplate */ .$M)(template, templateFormat).forEach((node) => { + if (node.type === "variable") { + names.add(node.name); + } + }); + return new PromptTemplate({ + // Rely on extracted types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + inputVariables: [...names], + templateFormat, + template, + ...rest, + }); + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of PromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables, + }; + return new PromptTemplate(promptDict); + } + serialize() { + if (this.outputParser !== undefined) { + throw new Error("Cannot serialize a prompt template with an output parser"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + template: this.template, + template_format: this.templateFormat, + }; + } + static async deserialize(data) { + if (!data.template) { + throw new Error("Prompt template must have a template"); + } + const res = new PromptTemplate({ + inputVariables: data.input_variables, + template: data.template, + templateFormat: data.template_format, + }); + return res; + } +} + + +/***/ }), + +/***/ 837: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "$M": () => (/* binding */ parseTemplate), +/* harmony export */ "SM": () => (/* binding */ renderTemplate), +/* harmony export */ "af": () => (/* binding */ checkValidTemplate) +/* harmony export */ }); +/* unused harmony exports parseFString, interpolateFString, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING */ +const parseFString = (template) => { + // Core logic replicated from internals of pythons built in Formatter class. + // https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/stringlib/unicode_format.h#L700-L706 + const chars = template.split(""); + const nodes = []; + const nextBracket = (bracket, start) => { + for (let i = start; i < chars.length; i += 1) { + if (bracket.includes(chars[i])) { + return i; + } + } + return -1; + }; + let i = 0; + while (i < chars.length) { + if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { + nodes.push({ type: "literal", text: "{" }); + i += 2; + } + else if (chars[i] === "}" && + i + 1 < chars.length && + chars[i + 1] === "}") { + nodes.push({ type: "literal", text: "}" }); + i += 2; + } + else if (chars[i] === "{") { + const j = nextBracket("}", i); + if (j < 0) { + throw new Error("Unclosed '{' in template."); + } + nodes.push({ + type: "variable", + name: chars.slice(i + 1, j).join(""), + }); + i = j + 1; + } + else if (chars[i] === "}") { + throw new Error("Single '}' in template."); + } + else { + const next = nextBracket("{}", i); + const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); + nodes.push({ type: "literal", text }); + i = next < 0 ? chars.length : next; + } + } + return nodes; +}; +const interpolateFString = (template, values) => parseFString(template).reduce((res, node) => { + if (node.type === "variable") { + if (node.name in values) { + return res + values[node.name]; + } + throw new Error(`Missing value for input ${node.name}`); + } + return res + node.text; +}, ""); +const DEFAULT_FORMATTER_MAPPING = { + "f-string": interpolateFString, + jinja2: (_, __) => "", +}; +const DEFAULT_PARSER_MAPPING = { + "f-string": parseFString, + jinja2: (_) => [], +}; +const renderTemplate = (template, templateFormat, inputValues) => DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); +const parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); +const checkValidTemplate = (template, templateFormat, inputVariables) => { + if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { + const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); + throw new Error(`Invalid template format. Got \`${templateFormat}\`; + should be one of ${validFormats}`); + } + try { + const dummyInputs = inputVariables.reduce((acc, v) => { + acc[v] = "foo"; + return acc; + }, {}); + renderTemplate(template, templateFormat, dummyInputs); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + throw new Error(`Invalid prompt schema: ${e.message}`); + } +}; + + +/***/ }), + +/***/ 8102: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Cr": () => (/* binding */ FunctionMessageChunk), +/* harmony export */ "E1": () => (/* binding */ coerceMessageLikeToMessage), +/* harmony export */ "GC": () => (/* binding */ AIMessageChunk), +/* harmony export */ "H2": () => (/* binding */ BaseCache), +/* harmony export */ "HD": () => (/* binding */ ChatMessageChunk), +/* harmony export */ "J": () => (/* binding */ ChatMessage), +/* harmony export */ "Ls": () => (/* binding */ ChatGenerationChunk), +/* harmony export */ "MJ": () => (/* binding */ BasePromptValue), +/* harmony export */ "QW": () => (/* binding */ isBaseMessage), +/* harmony export */ "WH": () => (/* binding */ RUN_KEY), +/* harmony export */ "b6": () => (/* binding */ GenerationChunk), +/* harmony export */ "gY": () => (/* binding */ AIMessage), +/* harmony export */ "jN": () => (/* binding */ SystemMessage), +/* harmony export */ "ku": () => (/* binding */ BaseMessage), +/* harmony export */ "ro": () => (/* binding */ HumanMessageChunk), +/* harmony export */ "xk": () => (/* binding */ HumanMessage), +/* harmony export */ "xq": () => (/* binding */ SystemMessageChunk) +/* harmony export */ }); +/* unused harmony exports BaseMessageChunk, BaseChatMessage, HumanChatMessage, AIChatMessage, SystemChatMessage, FunctionMessage, mapStoredMessageToChatMessage, BaseChatMessageHistory, BaseListChatMessageHistory, BaseFileStore, BaseEntityStore, Docstore */ +/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4432); + +const RUN_KEY = "__run"; +/** + * Chunk of a single generation. Used for streaming. + */ +class GenerationChunk { + constructor(fields) { + Object.defineProperty(this, "text", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "generationInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.text = fields.text; + this.generationInfo = fields.generationInfo; + } + concat(chunk) { + return new GenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo, + }, + }); + } +} +/** + * Base class for all types of messages in a conversation. It includes + * properties like `content`, `name`, and `additional_kwargs`. It also + * includes methods like `toDict()` and `_getType()`. + */ +class BaseMessage extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable */ .i { + /** + * @deprecated + * Use {@link BaseMessage.content} instead. + */ + get text() { + return this.content; + } + constructor(fields, + /** @deprecated */ + kwargs) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign + fields = { content: fields, additional_kwargs: kwargs }; + } + // Make sure the default value for additional_kwargs is passed into super() for serialization + if (!fields.additional_kwargs) { + // eslint-disable-next-line no-param-reassign + fields.additional_kwargs = {}; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + /** The text of the message. */ + Object.defineProperty(this, "content", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** The name of the message sender in a multi-user chat. */ + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** Additional keyword arguments */ + Object.defineProperty(this, "additional_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = fields.name; + this.content = fields.content; + this.additional_kwargs = fields.additional_kwargs; + } + toDict() { + return { + type: this._getType(), + data: this.toJSON() + .kwargs, + }; + } +} +/** + * Represents a chunk of a message, which can be concatenated with other + * message chunks. It includes a method `_merge_kwargs_dict()` for merging + * additional keyword arguments from another `BaseMessageChunk` into this + * one. It also overrides the `__add__()` method to support concatenation + * of `BaseMessageChunk` instances. + */ +class BaseMessageChunk extends BaseMessage { + static _mergeAdditionalKwargs(left, right) { + const merged = { ...left }; + for (const [key, value] of Object.entries(right)) { + if (merged[key] === undefined) { + merged[key] = value; + } + else if (typeof merged[key] !== typeof value) { + throw new Error(`additional_kwargs[${key}] already exists in the message chunk, but with a different type.`); + } + else if (typeof merged[key] === "string") { + merged[key] = merged[key] + value; + } + else if (!Array.isArray(merged[key]) && + typeof merged[key] === "object") { + merged[key] = this._mergeAdditionalKwargs(merged[key], value); + } + else { + throw new Error(`additional_kwargs[${key}] already exists in this message chunk.`); + } + } + return merged; + } +} +/** + * Represents a human message in a conversation. + */ +class HumanMessage extends BaseMessage { + static lc_name() { + return "HumanMessage"; + } + _getType() { + return "human"; + } +} +/** + * Represents a chunk of a human message, which can be concatenated with + * other human message chunks. + */ +class HumanMessageChunk extends BaseMessageChunk { + static lc_name() { + return "HumanMessageChunk"; + } + _getType() { + return "human"; + } + concat(chunk) { + return new HumanMessageChunk({ + content: this.content + chunk.content, + additional_kwargs: HumanMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), + }); + } +} +/** + * Represents an AI message in a conversation. + */ +class AIMessage extends BaseMessage { + static lc_name() { + return "AIMessage"; + } + _getType() { + return "ai"; + } +} +/** + * Represents a chunk of an AI message, which can be concatenated with + * other AI message chunks. + */ +class AIMessageChunk extends BaseMessageChunk { + static lc_name() { + return "AIMessageChunk"; + } + _getType() { + return "ai"; + } + concat(chunk) { + return new AIMessageChunk({ + content: this.content + chunk.content, + additional_kwargs: AIMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), + }); + } +} +/** + * Represents a system message in a conversation. + */ +class SystemMessage extends BaseMessage { + static lc_name() { + return "SystemMessage"; + } + _getType() { + return "system"; + } +} +/** + * Represents a chunk of a system message, which can be concatenated with + * other system message chunks. + */ +class SystemMessageChunk extends BaseMessageChunk { + static lc_name() { + return "SystemMessageChunk"; + } + _getType() { + return "system"; + } + concat(chunk) { + return new SystemMessageChunk({ + content: this.content + chunk.content, + additional_kwargs: SystemMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), + }); + } +} +/** + * @deprecated + * Use {@link BaseMessage} instead. + */ +const BaseChatMessage = (/* unused pure expression or super */ null && (BaseMessage)); +/** + * @deprecated + * Use {@link HumanMessage} instead. + */ +const HumanChatMessage = (/* unused pure expression or super */ null && (HumanMessage)); +/** + * @deprecated + * Use {@link AIMessage} instead. + */ +const AIChatMessage = (/* unused pure expression or super */ null && (AIMessage)); +/** + * @deprecated + * Use {@link SystemMessage} instead. + */ +const SystemChatMessage = (/* unused pure expression or super */ null && (SystemMessage)); +/** + * Represents a function message in a conversation. + */ +class FunctionMessage extends (/* unused pure expression or super */ null && (BaseMessage)) { + static lc_name() { + return "FunctionMessage"; + } + constructor(fields, + /** @deprecated */ + name) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, name: name }; + } + super(fields); + } + _getType() { + return "function"; + } +} +/** + * Represents a chunk of a function message, which can be concatenated + * with other function message chunks. + */ +class FunctionMessageChunk extends BaseMessageChunk { + static lc_name() { + return "FunctionMessageChunk"; + } + _getType() { + return "function"; + } + concat(chunk) { + return new FunctionMessageChunk({ + content: this.content + chunk.content, + additional_kwargs: FunctionMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), + name: this.name ?? "", + }); + } +} +/** + * Represents a chat message in a conversation. + */ +class ChatMessage extends BaseMessage { + static lc_name() { + return "ChatMessage"; + } + constructor(fields, role) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, role: role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + _getType() { + return "generic"; + } + static isInstance(message) { + return message._getType() === "generic"; + } +} +function isBaseMessage(messageLike) { + return typeof messageLike._getType === "function"; +} +function coerceMessageLikeToMessage(messageLike) { + if (typeof messageLike === "string") { + return new HumanMessage(messageLike); + } + else if (isBaseMessage(messageLike)) { + return messageLike; + } + const [type, content] = messageLike; + if (type === "human" || type === "user") { + return new HumanMessage({ content }); + } + else if (type === "ai" || type === "assistant") { + return new AIMessage({ content }); + } + else if (type === "system") { + return new SystemMessage({ content }); + } + else { + throw new Error(`Unable to coerce message from array: only human, AI, or system message coercion is currently supported.`); + } +} +/** + * Represents a chunk of a chat message, which can be concatenated with + * other chat message chunks. + */ +class ChatMessageChunk extends BaseMessageChunk { + static lc_name() { + return "ChatMessageChunk"; + } + constructor(fields, role) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { content: fields, role: role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + _getType() { + return "generic"; + } + concat(chunk) { + return new ChatMessageChunk({ + content: this.content + chunk.content, + additional_kwargs: ChatMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), + role: this.role, + }); + } +} +class ChatGenerationChunk extends GenerationChunk { + constructor(fields) { + super(fields); + Object.defineProperty(this, "message", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.message = fields.message; + } + concat(chunk) { + return new ChatGenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo, + }, + message: this.message.concat(chunk.message), + }); + } +} +/** + * Maps messages from an older format (V1) to the current `StoredMessage` + * format. If the message is already in the `StoredMessage` format, it is + * returned as is. Otherwise, it transforms the V1 message into a + * `StoredMessage`. This function is important for maintaining + * compatibility with older message formats. + */ +function mapV1MessageToStoredMessage(message) { + // TODO: Remove this mapper when we deprecate the old message format. + if (message.data !== undefined) { + return message; + } + else { + const v1Message = message; + return { + type: v1Message.type, + data: { + content: v1Message.text, + role: v1Message.role, + name: undefined, + }, + }; + } +} +function mapStoredMessageToChatMessage(message) { + const storedMessage = mapV1MessageToStoredMessage(message); + switch (storedMessage.type) { + case "human": + return new HumanMessage(storedMessage.data); + case "ai": + return new AIMessage(storedMessage.data); + case "system": + return new SystemMessage(storedMessage.data); + case "function": + if (storedMessage.data.name === undefined) { + throw new Error("Name must be defined for function messages"); + } + return new FunctionMessage(storedMessage.data); + case "chat": { + if (storedMessage.data.role === undefined) { + throw new Error("Role must be defined for chat messages"); + } + return new ChatMessage(storedMessage.data); + } + default: + throw new Error(`Got unexpected type: ${storedMessage.type}`); + } +} +/** + * Base PromptValue class. All prompt values should extend this class. + */ +class BasePromptValue extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable */ .i { +} +/** + * Base class for all chat message histories. All chat message histories + * should extend this class. + */ +class BaseChatMessageHistory extends (/* unused pure expression or super */ null && (Serializable)) { +} +/** + * Base class for all list chat message histories. All list chat message + * histories should extend this class. + */ +class BaseListChatMessageHistory extends (/* unused pure expression or super */ null && (Serializable)) { + addUserMessage(message) { + return this.addMessage(new HumanMessage(message)); + } + addAIChatMessage(message) { + return this.addMessage(new AIMessage(message)); + } +} +/** + * Base class for all caches. All caches should extend this class. + */ +class BaseCache { +} +/** + * Base class for all file stores. All file stores should extend this + * class. + */ +class BaseFileStore extends (/* unused pure expression or super */ null && (Serializable)) { +} +/** + * Base class for all entity stores. All entity stores should extend this + * class. + */ +class BaseEntityStore extends (/* unused pure expression or super */ null && (Serializable)) { +} +/** + * Abstract class for a document store. All document stores should extend + * this class. + */ +class Docstore { +} + + +/***/ }), + +/***/ 1972: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "eq": () => (/* reexport */ base_Runnable) +}); + +// UNUSED EXPORTS: RouterRunnable, RunnableBinding, RunnableBranch, RunnableEach, RunnableLambda, RunnableMap, RunnablePassthrough, RunnableRetry, RunnableSequence, RunnableWithFallbacks + +// NAMESPACE OBJECT: ./node_modules/langchain/dist/util/fast-json-patch/src/core.js +var core_namespaceObject = {}; +__webpack_require__.r(core_namespaceObject); +__webpack_require__.d(core_namespaceObject, { + "JsonPatchError": () => (JsonPatchError), + "_areEquals": () => (_areEquals), + "applyOperation": () => (applyOperation), + "applyPatch": () => (applyPatch), + "applyReducer": () => (applyReducer), + "deepClone": () => (deepClone), + "getValueByPointer": () => (getValueByPointer), + "validate": () => (validate), + "validator": () => (validator) +}); + +// EXTERNAL MODULE: ./node_modules/p-retry/index.js +var p_retry = __webpack_require__(2548); +// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/manager.js + 13 modules +var manager = __webpack_require__(6009); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/fast-json-patch/src/helpers.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */ +const _hasOwnProperty = Object.prototype.hasOwnProperty; +function helpers_hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys = new Array(obj.length); + for (let k = 0; k < keys.length; k++) { + keys[k] = "" + k; + } + return keys; + } + if (Object.keys) { + return Object.keys(obj); + } + let keys = []; + for (let i in obj) { + if (helpers_hasOwnProperty(obj, i)) { + keys.push(i); + } + } + return keys; +} +/** + * Deeply clone the object. + * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) + * @param {any} obj value to clone + * @return {any} cloned obj + */ +function _deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; //this is how JSON.stringify behaves for array items + default: + return obj; //no need to clone primitives + } +} +//3x faster than cached /^\d+$/.test(str) +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; + } + return false; + } + return true; +} +/** + * Escapes a json pointer path + * @param path The raw pointer + * @return the Escaped path + */ +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) + return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +/** + * Unescapes a json pointer path + * @param path The escaped pointer + * @return The unescaped path + */ +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +function _getPathRecursive(root, obj) { + let found; + for (let key in root) { + if (helpers_hasOwnProperty(root, key)) { + if (root[key] === obj) { + return escapePathComponent(key) + "/"; + } + else if (typeof root[key] === "object") { + found = _getPathRecursive(root[key], obj); + if (found != "") { + return escapePathComponent(key) + "/" + found; + } + } + } + } + return ""; +} +function getPath(root, obj) { + if (root === obj) { + return "/"; + } + const path = _getPathRecursive(root, obj); + if (path === "") { + throw new Error("Object not found in root"); + } + return `/${path}`; +} +/** + * Recursively checks whether an object has any undefined values inside. + */ +function hasUndefined(obj) { + if (obj === undefined) { + return true; + } + if (obj) { + if (Array.isArray(obj)) { + for (let i = 0, len = obj.length; i < len; i++) { + if (hasUndefined(obj[i])) { + return true; + } + } + } + else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) { + if (hasUndefined(obj[objKeys[i]])) { + return true; + } + } + } + } + return false; +} +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" + ? JSON.stringify(args[key], null, 2) + : args[key]; // pretty print + if (typeof value !== "undefined") { + messageParts.push(`${key}: ${value}`); + } + } + return messageParts.join("\n"); +} +class PatchError extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { name, index, operation, tree })); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: name + }); + Object.defineProperty(this, "index", { + enumerable: true, + configurable: true, + writable: true, + value: index + }); + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: operation + }); + Object.defineProperty(this, "tree", { + enumerable: true, + configurable: true, + writable: true, + value: tree + }); + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree, + }); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/fast-json-patch/src/core.js +// @ts-nocheck + +const JsonPatchError = PatchError; +const deepClone = _deepClone; +/* We use a Javascript hash to store each + function. Each hash entry (property) uses + the operation identifiers specified in rfc6902. + In this way, we can map each patch operation + to its dedicated function in efficient way. + */ +/* The operations applicable to an object */ +const objOps = { + add: function (obj, key, document) { + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function (obj, key, document) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document, removed }; + }, + replace: function (obj, key, document) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document, removed }; + }, + move: function (obj, key, document) { + /* in case move target overwrites an existing value, + return the removed value, this can be taxing performance-wise, + and is potentially unneeded */ + let removed = getValueByPointer(document, this.path); + if (removed) { + removed = _deepClone(removed); + } + const originalValue = applyOperation(document, { + op: "remove", + path: this.from, + }).removed; + applyOperation(document, { + op: "add", + path: this.path, + value: originalValue, + }); + return { newDocument: document, removed }; + }, + copy: function (obj, key, document) { + const valueToCopy = getValueByPointer(document, this.from); + // enforce copy by value so further operations don't affect source (see issue #177) + applyOperation(document, { + op: "add", + path: this.path, + value: _deepClone(valueToCopy), + }); + return { newDocument: document }; + }, + test: function (obj, key, document) { + return { newDocument: document, test: _areEquals(obj[key], this.value) }; + }, + _get: function (obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + }, +}; +/* The operations applicable to an array. Many are the same as for the object */ +var arrOps = { + add: function (arr, i, document) { + if (isInteger(i)) { + arr.splice(i, 0, this.value); + } + else { + // array props + arr[i] = this.value; + } + // this may be needed when using '-' in an array + return { newDocument: document, index: i }; + }, + remove: function (arr, i, document) { + var removedList = arr.splice(i, 1); + return { newDocument: document, removed: removedList[0] }; + }, + replace: function (arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { newDocument: document, removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get, +}; +/** + * Retrieves a value from a JSON document by a JSON pointer. + * Returns the value. + * + * @param document The document to get the value from + * @param pointer an escaped JSON pointer + * @return The retrieved value + */ +function getValueByPointer(document, pointer) { + if (pointer == "") { + return document; + } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; +} +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the {newDocument, result} of the operation. + * It modifies the `document` and `operation` objects - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. + * + * @param document The document to patch + * @param operation The operation to apply + * @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. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return `{newDocument, result}` after the operation + */ +function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) { + if (typeof validateOperation == "function") { + validateOperation(operation, 0, document, operation.path); + } + else { + validator(operation, 0); + } + } + /* ROOT OPERATIONS */ + if (operation.path === "") { + let returnValue = { newDocument: document }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; + } + else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document; //document we removed + return returnValue; + } + else if (operation.op === "move" || operation.op === "copy") { + // it's a move or copy to root + returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field + if (operation.op === "move") { + // report removed item + returnValue.removed = document; + } + return returnValue; + } + else if (operation.op === "test") { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + returnValue.newDocument = document; + return returnValue; + } + else if (operation.op === "remove") { + // a remove on root + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; + } + else if (operation.op === "_get") { + operation.value = document; + return returnValue; + } + else { + /* bad operation */ + if (validateOperation) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + } + else { + return returnValue; + } + } + } /* END ROOT OPERATIONS */ + else { + if (!mutateDocument) { + document = _deepClone(document); + } + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document; + let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift + let len = keys.length; + let existingPathFragment = undefined; + let key; + let validateFunction; + if (typeof validateOperation == "function") { + validateFunction = validateOperation; + } + else { + validateFunction = validator; + } + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) { + key = unescapePathComponent(key); + } + if (banPrototypeModifications && + (key == "__proto__" || + (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + } + if (validateOperation) { + if (existingPathFragment === undefined) { + if (obj[key] === undefined) { + existingPathFragment = keys.slice(0, t).join("/"); + } + else if (t == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== undefined) { + validateFunction(operation, 0, document, existingPathFragment); + } + } + } + t++; + if (Array.isArray(obj)) { + if (key === "-") { + key = obj.length; + } + else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); + } // only parse key when it's an integer for `arr.prop` to work + else if (isInteger(key)) { + key = ~~key; + } + } + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + } + const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + else { + if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + obj = obj[key]; + // If we have more keys in the path, but the next value isn't a non-null object, + // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. + if (validateOperation && t < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } + } + } +} +/** + * Apply a full JSON Patch array on a JSON document. + * Returns the {newDocument, result} of the patch. + * It modifies the `document` object and `patch` - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. + * + * @param document The document to patch + * @param patch The patch to apply + * @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. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return An array of `{newDocument, result}` after the patch + */ +function applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + } + if (!mutateDocument) { + document = _deepClone(document); + } + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; // in case root was replaced + } + results.newDocument = document; + return results; +} +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the updated document. + * Suitable as a reducer. + * + * @param document The document to patch + * @param operation The operation to apply + * @return The updated document + */ +function applyReducer(document, operation, index) { + const operationResult = applyOperation(document, operation); + if (operationResult.test === false) { + // failed test + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return operationResult.newDocument; +} +/** + * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. + * @param {object} operation - operation object (patch) + * @param {number} index - index of operation in the sequence + * @param {object} [document] - object where the operation is supposed to be applied + * @param {string} [existingPathFragment] - comes along with `document` + */ +function validator(operation, index, document, existingPathFragment) { + if (typeof operation !== "object" || + operation === null || + Array.isArray(operation)) { + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); + } + else if (!objOps[operation.op]) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + } + else if (typeof operation.path !== "string") { + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); + } + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { + // paths that aren't empty string should start with "/" + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); + } + else if ((operation.op === "move" || operation.op === "copy") && + typeof operation.from !== "string") { + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + } + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + operation.value === undefined) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + } + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + hasUndefined(operation.value)) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + } + else if (document) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); + } + } + else if (operation.op === "replace" || + operation.op === "remove" || + operation.op === "_get") { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } + } + else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: undefined, + }; + var error = validate([existingValue], document); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); + } + } + } +} +/** + * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. + * If error is encountered, returns a JsonPatchError object + * @param sequence + * @param document + * @returns {JsonPatchError|undefined} + */ +function validate(sequence, document, externalValidator) { + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + if (document) { + //clone document and sequence so that we can safely try applying operations + applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); + } + else { + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) { + externalValidator(sequence[i], i, document, undefined); + } + } + } + catch (e) { + if (e instanceof JsonPatchError) { + return e; + } + else { + throw e; + } + } +} +// based on https://github.com/epoberezkin/fast-deep-equal +// MIT License +// Copyright (c) 2017 Evgeny Poberezkin +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +function _areEquals(a, b) { + if (a === b) + return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length; i-- !== 0;) + if (!_areEquals(a[i], b[i])) + return false; + return true; + } + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length; i-- !== 0;) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; + } + return true; + } + return a !== a && b !== b; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/fast-json-patch/index.js + + +/** + * Default export for backwards compat + */ + + +/* harmony default export */ const fast_json_patch = ({ + ...core_namespaceObject, + // ...duplex, + JsonPatchError: PatchError, + deepClone: _deepClone, + escapePathComponent: escapePathComponent, + unescapePathComponent: unescapePathComponent, +}); + +// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer.js +var tracer = __webpack_require__(8763); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/stream.js +/* + * Support async iterator syntax for ReadableStreams in all environments. + * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +class IterableReadableStream extends ReadableStream { + constructor() { + super(...arguments); + Object.defineProperty(this, "reader", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + ensureReader() { + if (!this.reader) { + this.reader = this.getReader(); + } + } + async next() { + this.ensureReader(); + try { + const result = await this.reader.read(); + if (result.done) + this.reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + this.reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + } + async return() { + this.ensureReader(); + const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet + this.reader.releaseLock(); // release lock first + await cancelPromise; // now await it + return { done: true, value: undefined }; // This cast fixes TS typing, and convention is to ignore chunk value anyway + } + [Symbol.asyncIterator]() { + return this; + } + static fromReadableStream(stream) { + // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream + const reader = stream.getReader(); + return new IterableReadableStream({ + start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + // When no more data needs to be consumed, close the stream + if (done) { + controller.close(); + return; + } + // Enqueue the next data chunk into our target stream + controller.enqueue(value); + return pump(); + }); + } + }, + }); + } + static fromAsyncGenerator(generator) { + return new IterableReadableStream({ + async pull(controller) { + const { value, done } = await generator.next(); + if (done) { + controller.close(); + } + else if (value) { + controller.enqueue(value); + } + }, + }); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/log_stream.js + + + +/** + * List of jsonpatch JSONPatchOperations, which describe how to create the run state + * from an empty dict. This is the minimal representation of the log, designed to + * be serialized as JSON and sent over the wire to reconstruct the log on the other + * side. Reconstruction of the state can be done with any jsonpatch-compliant library, + * see https://jsonpatch.com for more information. + */ +class RunLogPatch { + constructor(fields) { + Object.defineProperty(this, "ops", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.ops = fields.ops; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch({}, ops); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunLog({ + ops, + state: states[states.length - 1].newDocument, + }); + } +} +class RunLog extends RunLogPatch { + constructor(fields) { + super(fields); + Object.defineProperty(this, "state", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.state = fields.state; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch(this.state, other.ops); + return new RunLog({ ops, state: states[states.length - 1].newDocument }); + } +} +/** + * Class that extends the `BaseTracer` class from the + * `langchain.callbacks.tracers.base` module. It represents a callback + * handler that logs the execution of runs and emits `RunLog` instances to a + * `RunLogStream`. + */ +class LogStreamCallbackHandler extends tracer/* BaseTracer */.Z { + constructor(fields) { + super(fields); + Object.defineProperty(this, "autoClose", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "indexMap", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "log_stream_tracer" + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) { + // This is a legacy method only called once for an entire run tree + // and is therefore not useful here + } + _includeRun(run) { + if (run.parent_run_id === undefined) { + return false; + } + const runTags = run.tags ?? []; + let include = this.includeNames === undefined && + this.includeTags === undefined && + this.includeTypes === undefined; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(run.run_type); + } + if (this.includeTags !== undefined) { + include = + include || + runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(run.run_type); + } + if (this.excludeTags !== undefined) { + include = + include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; + } + async onRunCreate(run) { + if (run.parent_run_id === undefined) { + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "replace", + path: "", + value: { + id: run.id, + streamed_output: [], + final_output: undefined, + logs: [], + }, + }, + ], + })); + } + if (!this._includeRun(run)) { + return; + } + this.indexMap[run.id] = Math.max(...Object.values(this.indexMap), -1) + 1; + const logEntry = { + id: run.id, + name: run.name, + type: run.run_type, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + start_time: new Date(run.start_time).toISOString(), + streamed_output_str: [], + final_output: undefined, + end_time: undefined, + }; + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${this.indexMap[run.id]}`, + value: logEntry, + }, + ], + })); + } + async onRunUpdate(run) { + try { + const index = this.indexMap[run.id]; + if (index === undefined) { + return; + } + const ops = [ + { + op: "add", + path: `/logs/${index}/final_output`, + value: run.outputs, + }, + ]; + if (run.end_time !== undefined) { + ops.push({ + op: "add", + path: `/logs/${index}/end_time`, + value: new Date(run.end_time).toISOString(), + }); + } + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } + finally { + if (run.parent_run_id === undefined) { + const patch = new RunLogPatch({ + ops: [ + { + op: "replace", + path: "/final_output", + value: run.outputs, + }, + ], + }); + await this.writer.write(patch); + if (this.autoClose) { + await this.writer.close(); + } + } + } + } + async onLLMNewToken(run, token) { + const index = this.indexMap[run.id]; + if (index === undefined) { + return; + } + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${index}/streamed_output_str/-`, + value: token, + }, + ], + }); + await this.writer.write(patch); + } +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/load/serializable.js + 1 modules +var serializable = __webpack_require__(4432); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/config.js + +async function getCallbackMangerForConfig(config) { + return manager/* CallbackManager.configure */.Ye.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); +} + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/async_caller.js +var async_caller = __webpack_require__(2723); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/base.js + + + + + + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; +} +/** + * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or + * transformed. + */ +class base_Runnable extends serializable/* Serializable */.i { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_runnable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + /** + * Bind arguments to a Runnable, returning a new Runnable. + * @param kwargs + * @returns A new RunnableBinding that, when invoked, will apply the bound args. + */ + bind(kwargs) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ bound: this, kwargs, config: {} }); + } + /** + * Return a new Runnable that maps a list of inputs to a list of outputs, + * by calling invoke() with each input. + */ + map() { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableEach({ bound: this }); + } + /** + * Add retry logic to an existing runnable. + * @param kwargs + * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. + */ + withRetry(fields) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields, + }); + } + /** + * Bind config to a Runnable, returning a new Runnable. + * @param config New configuration parameters to attach to the new runnable. + * @returns A new RunnableBinding with a config matching what's passed. + */ + withConfig(config) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ + bound: this, + config, + kwargs: {}, + }); + } + /** + * Create a new runnable from the current one that will try invoking + * other passed fallback runnables if the initial invocation fails. + * @param fields.fallbacks Other runnables to call if the runnable errors. + * @returns A new RunnableWithFallbacks. + */ + withFallbacks(fields) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableWithFallbacks({ + runnable: this, + fallbacks: fields.fallbacks, + }); + } + _getOptionsList(options, length = 0) { + if (Array.isArray(options)) { + if (options.length !== length) { + throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); + } + return options; + } + return Array.from({ length }, () => options); + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const caller = new async_caller/* AsyncCaller */.L({ + maxConcurrency: batchOptions?.maxConcurrency, + onFailedAttempt: (e) => { + throw e; + }, + }); + const batchCalls = inputs.map((input, i) => caller.call(async () => { + try { + const result = await this.invoke(input, configList[i]); + return result; + } + catch (e) { + if (batchOptions?.returnExceptions) { + return e; + } + throw e; + } + })); + return Promise.all(batchCalls); + } + /** + * Default streaming implementation. + * Subclasses should override this method if they support streaming output. + * @param input + * @param options + */ + async *_streamIterator(input, options) { + yield this.invoke(input, options); + } + /** + * Stream output in chunks. + * @param input + * @param options + * @returns A readable stream that is also an iterable. + */ + async stream(input, options) { + return IterableReadableStream.fromAsyncGenerator(this._streamIterator(input, options)); + } + _separateRunnableConfigFromCallOptions(options = {}) { + const runnableConfig = { + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + }; + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + return [runnableConfig, callOptions]; + } + async _callWithConfig(func, input, options) { + const callbackManager_ = await getCallbackMangerForConfig(options); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType); + let output; + try { + output = await func.bind(this)(input, options, runManager); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(output, "output")); + return output; + } + /** + * Internal method that handles batching and configuration for a runnable + * It takes a function, input values, and optional configuration, and + * returns a promise that resolves to the output values. + * @param func The function to be executed for each input value. + * @param input The input values to be processed. + * @param config Optional configuration for the function execution. + * @returns A promise that resolves to the output values. + */ + async _batchWithConfig(func, inputs, options, batchOptions) { + const configs = this._getOptionsList((options ?? {}), inputs.length); + const callbackManagers = await Promise.all(configs.map(getCallbackMangerForConfig)); + const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input")))); + let outputs; + try { + outputs = await func(inputs, configs, runManagers, batchOptions); + } + catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output")))); + return outputs; + } + /** + * Helper method to transform an Iterator of Input values into an Iterator of + * Output values, with callbacks. + * Use this to implement `stream()` or `transform()` in Runnable subclasses. + */ + async *_transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const callbackManager_ = await getCallbackMangerForConfig(options); + let runManager; + const serializedRepresentation = this.toJSON(); + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (!runManager) { + // Start the run manager AFTER the iterator starts to preserve + // tracing order + runManager = await callbackManager_?.handleChainStart(serializedRepresentation, { input: "" }, undefined, options?.runType); + } + if (finalInputSupported) { + if (finalInput === undefined) { + finalInput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalInput = finalInput.concat(chunk); + } + catch { + finalInput = undefined; + finalInputSupported = false; + } + } + } + yield chunk; + } + } + const wrappedInputGenerator = wrapInputForTracing(); + try { + const outputIterator = transformer(wrappedInputGenerator, runManager, options); + for await (const chunk of outputIterator) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = finalOutput.concat(chunk); + } + catch { + finalOutput = undefined; + finalOutputSupported = false; + } + } + } + } + } + catch (e) { + await runManager?.handleChainError(e, undefined, undefined, undefined, { + inputs: _coerceToDict(finalInput, "input"), + }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") }); + } + _patchConfig(config = {}, callbackManager = undefined) { + return { ...config, callbacks: callbackManager }; + } + /** + * Create a new runnable sequence that runs each individual runnable in series, + * piping the output of one runnable into another runnable or runnable-like. + * @param coerceable A runnable, function, or object whose values are functions or runnables. + * @returns A new runnable sequence. + */ + pipe(coerceable) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableSequence({ + first: this, + last: base_coerceToRunnable(coerceable), + }); + } + /** + * Default implementation of transform, which buffers input and then calls stream. + * Subclasses should override this method if they can start producing output while + * input is still being generated. + * @param generator + * @param options + */ + async *transform(generator, options) { + let finalChunk; + for await (const chunk of generator) { + if (finalChunk === undefined) { + finalChunk = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + // This method should throw an error if gathering fails. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalChunk = finalChunk.concat(chunk); + } + } + yield* this._streamIterator(finalChunk, options); + } + /** + * Stream all output from a runnable, as reported to the callback system. + * This includes all inner runs of LLMs, Retrievers, Tools, etc. + * Output is streamed as Log objects, which include a list of + * jsonpatch ops that describe how the state of the run has changed in each + * step, and the final state of the run. + * The jsonpatch ops can be applied in order to construct state. + * @param input + * @param options + * @param streamOptions + */ + async *streamLog(input, options, streamOptions) { + const stream = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + }); + const config = options ?? {}; + const { callbacks } = config; + if (callbacks === undefined) { + config.callbacks = [stream]; + } + else if (Array.isArray(callbacks)) { + config.callbacks = callbacks.concat([stream]); + } + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.inheritableHandlers.push(stream); + config.callbacks = copiedCallbacks; + } + const runnableStream = await this.stream(input, config); + async function consumeRunnableStream() { + try { + for await (const chunk of runnableStream) { + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: "/streamed_output/-", + value: chunk, + }, + ], + }); + await stream.writer.write(patch); + } + } + finally { + await stream.writer.close(); + } + } + const runnableStreamPromise = consumeRunnableStream(); + try { + for await (const log of stream) { + yield log; + } + } + finally { + await runnableStreamPromise; + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnable(thing) { + return thing.lc_runnable; + } +} +/** + * A runnable that delegates calls to another runnable with a set of kwargs. + */ +class RunnableBinding extends base_Runnable { + static lc_name() { + return "RunnableBinding"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "bound", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "config", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _mergeConfig(options) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const copy = { ...this.config }; + if (options) { + for (const key of Object.keys(options)) { + if (key === "metadata") { + copy[key] = { ...copy[key], ...options[key] }; + } + else if (key === "tags") { + copy[key] = (copy[key] ?? []).concat(options[key] ?? []); + } + else { + copy[key] = options[key] ?? copy[key]; + } + } + } + return copy; + } + bind(kwargs) { + return this.constructor({ + bound: this.bound, + kwargs: { ...this.kwargs, ...kwargs }, + config: this.config, + }); + } + withConfig(config) { + return this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { ...this.config, ...config }, + }); + } + withRetry(fields) { + return this.constructor({ + bound: this.bound.withRetry(fields), + kwargs: this.kwargs, + config: this.config, + }); + } + async invoke(input, options) { + return this.bound.invoke(input, this._mergeConfig({ ...options, ...this.kwargs })); + } + async batch(inputs, options, batchOptions) { + const mergedOptions = Array.isArray(options) + ? options.map((individualOption) => this._mergeConfig({ + ...individualOption, + ...this.kwargs, + })) + : this._mergeConfig({ ...options, ...this.kwargs }); + return this.bound.batch(inputs, mergedOptions, batchOptions); + } + async *_streamIterator(input, options) { + yield* this.bound._streamIterator(input, this._mergeConfig({ ...options, ...this.kwargs })); + } + async stream(input, options) { + return this.bound.stream(input, this._mergeConfig({ ...options, ...this.kwargs })); + } + async *transform( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + generator, options) { + yield* this.bound.transform(generator, this._mergeConfig({ ...options, ...this.kwargs })); + } + static isRunnableBinding( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + thing + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ) { + return thing.bound && base_Runnable.isRunnable(thing.bound); + } +} +/** + * A runnable that delegates calls to another runnable + * with each element of the input sequence. + */ +class RunnableEach extends base_Runnable { + static lc_name() { + return "RunnableEach"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "bound", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.bound = fields.bound; + } + /** + * Binds the runnable with the specified arguments. + * @param args The arguments to bind the runnable with. + * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. + */ + bind(kwargs) { + return new RunnableEach({ + bound: this.bound.bind(kwargs), + }); + } + /** + * Invokes the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(inputs, config) { + return this._callWithConfig(this._invoke, inputs, config); + } + /** + * A helper method that is used to invoke the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async _invoke(inputs, config, runManager) { + return this.bound.batch(inputs, this._patchConfig(config, runManager?.getChild())); + } +} +/** + * Base class for runnables that can be retried a + * specified number of times. + */ +class RunnableRetry extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "maxAttemptNumber", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: () => { } + }); + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; + } + _patchConfigForRetry(attempt, config, runManager) { + const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; + return this._patchConfig(config, runManager?.getChild(tag)); + } + async _invoke(input, config, runManager) { + return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { + onFailedAttempt: this.onFailedAttempt, + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true, + }); + } + /** + * Method that invokes the runnable with the specified input, run manager, + * and config. It handles the retry logic by catching any errors and + * recursively invoking itself with the updated config for the next retry + * attempt. + * @param input The input for the runnable. + * @param runManager The run manager for the runnable. + * @param config The config for the runnable. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(input, config) { + return this._callWithConfig(this._invoke, input, config); + } + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await p_retry(async (attemptNumber) => { + const remainingIndexes = inputs + .map((_, i) => i) + .filter((i) => resultsMap[i.toString()] === undefined || + // eslint-disable-next-line no-instanceof/no-instanceof + resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true, + }); + let firstException; + for (let i = 0; i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + // eslint-disable-next-line no-instanceof/no-instanceof + if (result instanceof Error) { + if (firstException === undefined) { + firstException = result; + } + } + resultsMap[resultMapIndex.toString()] = result; + } + if (firstException) { + throw firstException; + } + return results; + }, { + onFailedAttempt: this.onFailedAttempt, + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true, + }); + } + catch (e) { + if (batchOptions?.returnExceptions !== true) { + throw e; + } + } + return Object.keys(resultsMap) + .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) + .map((key) => resultsMap[parseInt(key, 10)]); + } + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); + } +} +/** + * A sequence of runnables, where the output of each is the input of the next. + */ +class RunnableSequence extends base_Runnable { + static lc_name() { + return "RunnableSequence"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "first", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "middle", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "last", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + } + get steps() { + return [this.first, ...this.middle, this.last]; + } + async invoke(input, options) { + const callbackManager_ = await getCallbackMangerForConfig(options); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input")); + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) { + const step = initialSteps[i]; + nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${i + 1}`))); + } + // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here + finalOutput = await this.last.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${this.steps.length}`))); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output")); + return finalOutput; + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map(getCallbackMangerForConfig)); + const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input")))); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let nextStepInputs = inputs; + let finalOutputs; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) { + const step = initialSteps[i]; + nextStepInputs = await step.batch(nextStepInputs, runManagers.map((runManager, j) => this._patchConfig(configList[j], runManager?.getChild(`seq:step:${i + 1}`))), batchOptions); + } + finalOutputs = await this.last.batch(nextStepInputs, runManagers.map((runManager) => this._patchConfig(configList[this.steps.length - 1], runManager?.getChild(`seq:step:${this.steps.length}`))), batchOptions); + } + catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(finalOutputs[i], "output")))); + return finalOutputs; + } + async *_streamIterator(input, options) { + const callbackManager_ = await getCallbackMangerForConfig(options); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input")); + let nextStepInput = input; + const steps = [this.first, ...this.middle, this.last]; + // Find the index of the last runnable in the sequence that doesn't have an overridden .transform() method + // and start streaming from there + const streamingStartStepIndex = Math.min(steps.length - 1, steps.length - + [...steps].reverse().findIndex((step) => { + const isDefaultImplementation = step.transform === base_Runnable.prototype.transform; + const boundRunnableIsDefaultImplementation = RunnableBinding.isRunnableBinding(step) && + step.bound?.transform === base_Runnable.prototype.transform; + return (isDefaultImplementation || boundRunnableIsDefaultImplementation); + }) - + 1); + try { + const invokeSteps = steps.slice(0, streamingStartStepIndex); + for (let i = 0; i < invokeSteps.length; i += 1) { + const step = invokeSteps[i]; + nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${i + 1}`))); + } + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + let concatSupported = true; + let finalOutput; + try { + let finalGenerator = await steps[streamingStartStepIndex]._streamIterator(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${streamingStartStepIndex + 1}`))); + const finalSteps = steps.slice(streamingStartStepIndex + 1); + for (let i = 0; i < finalSteps.length; i += 1) { + const step = finalSteps[i]; + finalGenerator = await step.transform(finalGenerator, this._patchConfig(options, runManager?.getChild(`seq:step:${streamingStartStepIndex + i + 2}`))); + } + for await (const chunk of finalGenerator) { + yield chunk; + if (concatSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = finalOutput.concat(chunk); + } + catch (e) { + finalOutput = undefined; + concatSupported = false; + } + } + } + } + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output")); + } + pipe(coerceable) { + if (RunnableSequence.isRunnableSequence(coerceable)) { + return new RunnableSequence({ + first: this.first, + middle: this.middle.concat([ + this.last, + coerceable.first, + ...coerceable.middle, + ]), + last: coerceable.last, + }); + } + else { + return new RunnableSequence({ + first: this.first, + middle: [...this.middle, this.last], + last: base_coerceToRunnable(coerceable), + }); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnableSequence(thing) { + return Array.isArray(thing.middle) && base_Runnable.isRunnable(thing); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from([first, ...runnables]) { + return new RunnableSequence({ + first: base_coerceToRunnable(first), + middle: runnables.slice(0, -1).map(base_coerceToRunnable), + last: base_coerceToRunnable(runnables[runnables.length - 1]), + }); + } +} +/** + * A runnable that runs a mapping of runnables in parallel, + * and returns a mapping of their outputs. + */ +class RunnableMap extends base_Runnable { + static lc_name() { + return "RunnableMap"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "steps", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) { + this.steps[key] = base_coerceToRunnable(value); + } + } + async invoke(input, options + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ) { + const callbackManager_ = await getCallbackMangerForConfig(options); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { + input, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const output = {}; + try { + await Promise.all(Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, this._patchConfig(options, runManager?.getChild(key))); + })); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; + } +} +/** + * A runnable that runs a callable. + */ +class RunnableLambda extends base_Runnable { + static lc_name() { + return "RunnableLambda"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "func", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.func = fields.func; + } + async _invoke(input, config, runManager) { + let output = await this.func(input); + if (output && base_Runnable.isRunnable(output)) { + output = await output.invoke(input, this._patchConfig(config, runManager?.getChild())); + } + return output; + } + async invoke(input, options) { + return this._callWithConfig(this._invoke, input, options); + } +} +/** + * A Runnable that can fallback to other Runnables if it fails. + */ +class RunnableWithFallbacks extends base_Runnable { + static lc_name() { + return "RunnableWithFallbacks"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "runnable", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fallbacks", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; + } + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) { + yield fallback; + } + } + async invoke(input, options) { + const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input")); + let firstError; + for (const runnable of this.runnables()) { + try { + const output = await runnable.invoke(input, this._patchConfig(options, runManager?.getChild())); + await runManager?.handleChainEnd(_coerceToDict(output, "output")); + return output; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (firstError === undefined) { + throw new Error("No error stored at end of fallback."); + } + await runManager?.handleChainError(firstError); + throw firstError; + } + async batch(inputs, options, batchOptions) { + if (batchOptions?.returnExceptions) { + throw new Error("Not implemented."); + } + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map((config) => manager/* CallbackManager.configure */.Ye.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata))); + const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input")))); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let firstError; + for (const runnable of this.runnables()) { + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => this._patchConfig(configList[j], runManager?.getChild())), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output")))); + return outputs; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (!firstError) { + throw new Error("No error stored at end of fallbacks."); + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; + } +} +// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type +function base_coerceToRunnable(coerceable) { + if (typeof coerceable === "function") { + return new RunnableLambda({ func: coerceable }); + } + else if (base_Runnable.isRunnable(coerceable)) { + return coerceable; + } + else if (!Array.isArray(coerceable) && typeof coerceable === "object") { + const runnables = {}; + for (const [key, value] of Object.entries(coerceable)) { + runnables[key] = base_coerceToRunnable(value); + } + return new RunnableMap({ + steps: runnables, + }); + } + else { + throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/passthrough.js + +/** + * A runnable that passes through the input. + */ +class RunnablePassthrough extends (/* unused pure expression or super */ null && (Runnable)) { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + static lc_name() { + return "RunnablePassthrough"; + } + async invoke(input, options) { + return this._callWithConfig((input) => Promise.resolve(input), input, options); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/router.js + +/** + * A runnable that routes to a set of runnables based on Input['key']. + * Returns the output of the selected runnable. + */ +class RouterRunnable extends (/* unused pure expression or super */ null && (Runnable)) { + static lc_name() { + return "RouterRunnable"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "schema", "runnable"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "runnables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnables = fields.runnables; + } + async invoke(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) { + throw new Error(`No runnable associated with key "${key}".`); + } + return runnable.invoke(actualInput, options); + } + async batch(inputs, options, batchOptions) { + const keys = inputs.map((input) => input.key); + const actualInputs = inputs.map((input) => input.input); + const missingKey = keys.find((key) => this.runnables[key] === undefined); + if (missingKey !== undefined) { + throw new Error(`One or more keys do not have a corresponding runnable.`); + } + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const batchSize = batchOptions?.maxConcurrency && batchOptions.maxConcurrency > 0 + ? batchOptions?.maxConcurrency + : inputs.length; + const batchResults = []; + for (let i = 0; i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs + .slice(i, i + batchSize) + .map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); + const batchResult = await Promise.all(batchPromises); + batchResults.push(batchResult); + } + return batchResults.flat(); + } + async stream(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) { + throw new Error(`No runnable associated with key "${key}".`); + } + return runnable.stream(actualInput, options); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/branch.js + +/** + * Class that represents a runnable branch. The RunnableBranch is + * initialized with an array of branches and a default branch. When invoked, + * it evaluates the condition of each branch in order and executes the + * corresponding branch if the condition is true. If none of the conditions + * are true, it executes the default branch. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class RunnableBranch extends (/* unused pure expression or super */ null && (Runnable)) { + static lc_name() { + return "RunnableBranch"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "runnable", "branch"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "default", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "branches", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.branches = fields.branches; + this.default = fields.default; + } + /** + * Convenience method for instantiating a RunnableBranch from + * RunnableLikes (objects, functions, or Runnables). + * + * Each item in the input except for the last one should be a + * tuple with two items. The first is a "condition" RunnableLike that + * returns "true" if the second RunnableLike in the tuple should run. + * + * The final item in the input should be a RunnableLike that acts as a + * default branch if no other branches match. + * + * @example + * ```ts + * import { RunnableBranch } from "langchain/schema/runnable"; + * + * const branch = RunnableBranch.from([ + * [(x: number) => x > 0, (x: number) => x + 1], + * [(x: number) => x < 0, (x: number) => x - 1], + * (x: number) => x + * ]); + * ``` + * @param branches An array where the every item except the last is a tuple of [condition, runnable] + * pairs. The last item is a default runnable which is invoked if no other condition matches. + * @returns A new RunnableBranch. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from(branches) { + if (branches.length < 1) { + throw new Error("RunnableBranch requires at least one branch"); + } + const branchLikes = branches.slice(0, -1); + const coercedBranches = branchLikes.map(([condition, runnable]) => [ + _coerceToRunnable(condition), + _coerceToRunnable(runnable), + ]); + const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); + return new this({ + branches: coercedBranches, + default: defaultBranch, + }); + } + async _invoke(input, config, runManager) { + let result; + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, this._patchConfig(config, runManager?.getChild(`condition:${i + 1}`))); + if (conditionValue) { + result = await branchRunnable.invoke(input, this._patchConfig(config, runManager?.getChild(`branch:${i + 1}`))); + break; + } + } + if (!result) { + result = await this.default.invoke(input, this._patchConfig(config, runManager?.getChild("default"))); + } + return result; + } + async invoke(input, config = {}) { + return this._callWithConfig(this._invoke, input, config); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + + + + + + +/***/ }), + +/***/ 2723: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "L": () => (/* binding */ AsyncCaller) +/* harmony export */ }); +/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2548); +/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8983); + + +const STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 408, + 409, // Conflict +]; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const defaultFailedAttemptHandler = (error) => { + if (error.message.startsWith("Cancel") || + error.message.startsWith("TimeoutError") || + error.name === "TimeoutError" || + error.message.startsWith("AbortError") || + error.name === "AbortError") { + throw error; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { + throw error; + } + const status = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error?.response?.status ?? error?.status; + if (status && STATUS_NO_RETRY.includes(+status)) { + throw error; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.error?.code === "insufficient_quota") { + const err = new Error(error?.message); + err.name = "InsufficientQuotaError"; + throw err; + } +}; +/** + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. + */ +class AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = + params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue = true ? p_queue__WEBPACK_IMPORTED_MODULE_1__["default"] : p_queue__WEBPACK_IMPORTED_MODULE_1__; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + return this.queue.add(() => p_retry__WEBPACK_IMPORTED_MODULE_0__(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } + }), { + onFailedAttempt: this.onFailedAttempt, + retries: this.maxRetries, + randomize: true, + // If needed we can change some of the defaults here, + // but they're quite sensible. + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); + } +} + + +/***/ }), + +/***/ 5785: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "lS": () => (/* binding */ getEnvironmentVariable), +/* harmony export */ "sA": () => (/* binding */ getRuntimeEnvironment) +/* harmony export */ }); +/* unused harmony exports isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv */ +const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && + (navigator.userAgent.includes("Node.js") || + navigator.userAgent.includes("jsdom"))); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !isDeno(); +const getEnv = () => { + let env; + if (isBrowser()) { + env = "browser"; + } + else if (isNode()) { + env = "node"; + } + else if (isWebWorker()) { + env = "webworker"; + } + else if (isJsDom()) { + env = "jsdom"; + } + else if (isDeno()) { + env = "deno"; + } + else { + env = "other"; + } + return env; +}; +let runtimeEnvironment; +async function getRuntimeEnvironment() { + if (runtimeEnvironment === undefined) { + const env = getEnv(); + runtimeEnvironment = { + library: "langchain-js", + runtime: env, + }; + } + return runtimeEnvironment; +} +function getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/hwchase17/langchainjs/issues/1412 + try { + return typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.[name] + : undefined; + } + catch (e) { + return undefined; + } +} + + +/***/ }), + +/***/ 1273: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "v4": () => (/* binding */ v4) +/* harmony export */ }); +/* unused harmony exports v1, v3, v5, NIL, version, validate, stringify, parse */ +/* harmony import */ var _dist_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8655); + +const v1 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v1; +const v3 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v3; +const v4 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v4; +const v5 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v5; +const NIL = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.NIL; +const version = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.version; +const validate = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.validate; +const stringify = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.stringify; +const parse = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.parse; + + +/***/ }) + +}; diff --git a/dist/679.index.js b/dist/679.index.js new file mode 100644 index 0000000..c789699 --- /dev/null +++ b/dist/679.index.js @@ -0,0 +1,1066 @@ +export const id = 679; +export const ids = [679]; +export const modules = { + +/***/ 8393: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "F1": () => (/* binding */ calculateMaxTokens), +/* harmony export */ "_i": () => (/* binding */ getModelNameForTiktoken) +/* harmony export */ }); +/* unused harmony exports getEmbeddingContextSize, getModelContextSize */ +/* harmony import */ var _util_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7573); + +// https://www.npmjs.com/package/js-tiktoken +const getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-3.5-turbo-16k")) { + return "gpt-3.5-turbo-16k"; + } + if (modelName.startsWith("gpt-3.5-turbo-")) { + return "gpt-3.5-turbo"; + } + if (modelName.startsWith("gpt-4-32k")) { + return "gpt-4-32k"; + } + if (modelName.startsWith("gpt-4-")) { + return "gpt-4"; + } + return modelName; +}; +const getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": + return 8191; + default: + return 2046; + } +}; +const getModelContextSize = (modelName) => { + switch (getModelNameForTiktoken(modelName)) { + case "gpt-3.5-turbo-16k": + return 16384; + case "gpt-3.5-turbo": + return 4096; + case "gpt-4-32k": + return 32768; + case "gpt-4": + return 8192; + case "text-davinci-003": + return 4097; + case "text-curie-001": + return 2048; + case "text-babbage-001": + return 2048; + case "text-ada-001": + return 2048; + case "code-davinci-002": + return 8000; + case "code-cushman-001": + return 2048; + default: + return 4097; + } +}; +const calculateMaxTokens = async ({ prompt, modelName, }) => { + let numTokens; + try { + numTokens = (await (0,_util_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__/* .encodingForModel */ .b)(getModelNameForTiktoken(modelName))).encode(prompt).length; + } + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + // fallback to approximate calculation if tiktoken is not available + // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# + numTokens = Math.ceil(prompt.length / 4); + } + const maxTokens = getModelContextSize(modelName); + return maxTokens - numTokens; +}; + + +/***/ }), + +/***/ 7679: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "BD": () => (/* binding */ BaseLangChain), + "qV": () => (/* binding */ BaseLanguageModel) +}); + +// UNUSED EXPORTS: calculateMaxTokens, getModelContextSize + +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js +var schema = __webpack_require__(8102); +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/async_caller.js +var async_caller = __webpack_require__(2723); +// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/count_tokens.js +var count_tokens = __webpack_require__(8393); +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/tiktoken.js + 3 modules +var tiktoken = __webpack_require__(7573); +// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules +var runnable = __webpack_require__(1972); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js +var base = __webpack_require__(5411); +// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/chat.js +var chat = __webpack_require__(6704); +// EXTERNAL MODULE: ./node_modules/object-hash/index.js +var object_hash = __webpack_require__(4856); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/cache/base.js + + +/** + * This cache key should be consistent across all versions of langchain. + * It is currently NOT consistent across versions of langchain. + * + * A huge benefit of having a remote cache (like redis) is that you can + * access the cache from different processes/machines. The allows you to + * seperate concerns and scale horizontally. + * + * TODO: Make cache key consistent across versions of langchain. + */ +const getCacheKey = (...strings) => object_hash(strings.join("_")); +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== undefined) { + return { + text: storedGeneration.text, + message: mapStoredMessageToChatMessage(storedGeneration.message), + }; + } + else { + return { text: storedGeneration.text }; + } +} +function serializeGeneration(generation) { + const serializedValue = { + text: generation.text, + }; + if (generation.message !== undefined) { + serializedValue.message = generation.message.toDict(); + } + return serializedValue; +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/cache/index.js + + +const GLOBAL_MAP = new Map(); +/** + * A cache for storing LLM generations that stores data in memory. + */ +class InMemoryCache extends schema/* BaseCache */.H2 { + constructor(map) { + super(); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cache = map ?? new Map(); + } + /** + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. + */ + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); + } + /** + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. + */ + async update(prompt, llmKey, value) { + this.cache.set(getCacheKey(prompt, llmKey), value); + } + /** + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. + */ + static global() { + return new InMemoryCache(GLOBAL_MAP); + } +} + +;// CONCATENATED MODULE: ./node_modules/langchain/dist/base_language/index.js + + + + + + + + +const getVerbosity = () => false; +/** + * Base class for language models, chains, tools. + */ +class BaseLangChain extends runnable/* Runnable */.eq { + get lc_attributes() { + return { + callbacks: undefined, + verbose: undefined, + }; + } + constructor(params) { + super(params); + /** + * Whether to print out response text. + */ + Object.defineProperty(this, "verbose", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "callbacks", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + } +} +/** + * Base class for language models. + */ +class BaseLanguageModel extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; + } + constructor({ callbacks, callbackManager, ...params }) { + super({ + callbacks: callbacks ?? callbackManager, + ...params, + }); + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_encoding", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (typeof params.cache === "object") { + this.cache = params.cache; + } + else if (params.cache) { + this.cache = InMemoryCache.global(); + } + else { + this.cache = undefined; + } + this.caller = new async_caller/* AsyncCaller */.L(params ?? {}); + } + async getNumTokens(text) { + // fallback to approximate calculation if tiktoken is not available + let numTokens = Math.ceil(text.length / 4); + if (!this._encoding) { + try { + this._encoding = await (0,tiktoken/* encodingForModel */.b)("modelName" in this + ? (0,count_tokens/* getModelNameForTiktoken */._i)(this.modelName) + : "gpt2"); + } + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + } + } + if (this._encoding) { + numTokens = this._encoding.encode(text).length; + } + return numTokens; + } + static _convertInputToPromptValue(input) { + if (typeof input === "string") { + return new base/* StringPromptValue */.nw(input); + } + else if (Array.isArray(input)) { + return new chat/* ChatPromptValue */.GU(input.map(schema/* coerceMessageLikeToMessage */.E1)); + } + else { + return input; + } + } + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. + */ + _getSerializedCacheKeyParametersForCall(callOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType(), + }; + const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); + const serializedEntries = filteredEntries + .map(([key, value]) => `${key}:${JSON.stringify(value)}`) + .sort() + .join(","); + return serializedEntries; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(data) { + const { _type, _model, ...rest } = data; + if (_model && _model !== "base_chat_model") { + throw new Error(`Cannot load LLM with model ${_model}`); + } + const Cls = { + openai: (await Promise.all(/* import() */[__webpack_require__.e(366), __webpack_require__.e(27)]).then(__webpack_require__.bind(__webpack_require__, 27))).ChatOpenAI, + }[_type]; + if (Cls === undefined) { + throw new Error(`Cannot load LLM with type ${_type}`); + } + return new Cls(rest); + } +} +/* + * Export utility functions for token calculations: + * - calculateMaxTokens: Calculate max tokens for a given model and prompt (the model context size - tokens in prompt). + * - getModelContextSize: Get the context size for a specific model. + */ + + + +/***/ }), + +/***/ 6704: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "GU": () => (/* binding */ ChatPromptValue), +/* harmony export */ "gc": () => (/* binding */ AIMessagePromptTemplate), +/* harmony export */ "kq": () => (/* binding */ HumanMessagePromptTemplate), +/* harmony export */ "ks": () => (/* binding */ ChatPromptTemplate), +/* harmony export */ "ov": () => (/* binding */ SystemMessagePromptTemplate) +/* harmony export */ }); +/* unused harmony exports BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate */ +/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8102); +/* harmony import */ var _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1972); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5411); +/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4095); +// Default generic "any" values are for backwards compatibility. +// Replace with "string" when we are comfortable with a breaking change. + + + + +/** + * Abstract class that serves as a base for creating message prompt + * templates. It defines how to format messages for different roles in a + * conversation. + */ +class BaseMessagePromptTemplate extends _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_1__/* .Runnable */ .eq { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "prompts", "chat"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + } + /** + * Calls the formatMessages method with the provided input and options. + * @param input Input for the formatMessages method + * @param options Optional BaseCallbackConfig + * @returns Formatted output messages + */ + async invoke(input, options) { + return this._callWithConfig((input) => this.formatMessages(input), input, { ...options, runType: "prompt" }); + } +} +/** + * Class that represents a chat prompt value. It extends the + * BasePromptValue and includes an array of BaseMessage instances. + */ +class ChatPromptValue extends _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BasePromptValue */ .MJ { + static lc_name() { + return "ChatPromptValue"; + } + constructor(fields) { + if (Array.isArray(fields)) { + // eslint-disable-next-line no-param-reassign + fields = { messages: fields }; + } + super(...arguments); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "prompts", "chat"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "messages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.messages = fields.messages; + } + toString() { + return JSON.stringify(this.messages); + } + toChatMessages() { + return this.messages; + } +} +/** + * Class that represents a placeholder for messages in a chat prompt. It + * extends the BaseMessagePromptTemplate. + */ +class MessagesPlaceholder extends (/* unused pure expression or super */ null && (BaseMessagePromptTemplate)) { + static lc_name() { + return "MessagesPlaceholder"; + } + constructor(fields) { + if (typeof fields === "string") { + // eslint-disable-next-line no-param-reassign + fields = { variableName: fields }; + } + super(fields); + Object.defineProperty(this, "variableName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.variableName = fields.variableName; + } + get inputVariables() { + return [this.variableName]; + } + formatMessages(values) { + return Promise.resolve(values[this.variableName]); + } +} +/** + * Abstract class that serves as a base for creating message string prompt + * templates. It extends the BaseMessagePromptTemplate. + */ +class BaseMessageStringPromptTemplate extends BaseMessagePromptTemplate { + constructor(fields) { + if (!("prompt" in fields)) { + // eslint-disable-next-line no-param-reassign + fields = { prompt: fields }; + } + super(fields); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + } + get inputVariables() { + return this.prompt.inputVariables; + } + async formatMessages(values) { + return [await this.format(values)]; + } +} +/** + * Abstract class that serves as a base for creating chat prompt + * templates. It extends the BasePromptTemplate. + */ +class BaseChatPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_2__/* .BasePromptTemplate */ .dy { + constructor(input) { + super(input); + } + async format(values) { + return (await this.formatPromptValue(values)).toString(); + } + async formatPromptValue(values) { + const resultMessages = await this.formatMessages(values); + return new ChatPromptValue(resultMessages); + } +} +/** + * Class that represents a chat message prompt template. It extends the + * BaseMessageStringPromptTemplate. + */ +class ChatMessagePromptTemplate extends BaseMessageStringPromptTemplate { + static lc_name() { + return "ChatMessagePromptTemplate"; + } + constructor(fields, role) { + if (!("prompt" in fields)) { + // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion + fields = { prompt: fields, role: role }; + } + super(fields); + Object.defineProperty(this, "role", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.role = fields.role; + } + async format(values) { + return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .ChatMessage */ .J(await this.prompt.format(values), this.role); + } + static fromTemplate(template, role) { + return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template), role); + } +} +/** + * Class that represents a human message prompt template. It extends the + * BaseMessageStringPromptTemplate. + */ +class HumanMessagePromptTemplate extends BaseMessageStringPromptTemplate { + static lc_name() { + return "HumanMessagePromptTemplate"; + } + async format(values) { + return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .HumanMessage */ .xk(await this.prompt.format(values)); + } + static fromTemplate(template) { + return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template)); + } +} +/** + * Class that represents an AI message prompt template. It extends the + * BaseMessageStringPromptTemplate. + */ +class AIMessagePromptTemplate extends BaseMessageStringPromptTemplate { + static lc_name() { + return "AIMessagePromptTemplate"; + } + async format(values) { + return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .AIMessage */ .gY(await this.prompt.format(values)); + } + static fromTemplate(template) { + return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template)); + } +} +/** + * Class that represents a system message prompt template. It extends the + * BaseMessageStringPromptTemplate. + */ +class SystemMessagePromptTemplate extends BaseMessageStringPromptTemplate { + static lc_name() { + return "SystemMessagePromptTemplate"; + } + async format(values) { + return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .SystemMessage */ .jN(await this.prompt.format(values)); + } + static fromTemplate(template) { + return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template)); + } +} +function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { + return (typeof baseMessagePromptTemplateLike + .formatMessages === "function"); +} +function _coerceMessagePromptTemplateLike(messagePromptTemplateLike) { + if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || + (0,_schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .isBaseMessage */ .QW)(messagePromptTemplateLike)) { + return messagePromptTemplateLike; + } + const message = (0,_schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .coerceMessageLikeToMessage */ .E1)(messagePromptTemplateLike); + if (message._getType() === "human") { + return HumanMessagePromptTemplate.fromTemplate(message.content); + } + else if (message._getType() === "ai") { + return AIMessagePromptTemplate.fromTemplate(message.content); + } + else if (message._getType() === "system") { + return SystemMessagePromptTemplate.fromTemplate(message.content); + } + else if (_schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .ChatMessage.isInstance */ .J.isInstance(message)) { + return ChatMessagePromptTemplate.fromTemplate(message.content, message.role); + } + else { + throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); + } +} +/** + * Class that represents a chat prompt. It extends the + * BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate + * instances to format a series of messages for a conversation. + */ +class ChatPromptTemplate extends BaseChatPromptTemplate { + static lc_name() { + return "ChatPromptTemplate"; + } + get lc_aliases() { + return { + promptMessages: "messages", + }; + } + constructor(input) { + super(input); + Object.defineProperty(this, "promptMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.validateTemplate) { + const inputVariablesMessages = new Set(); + for (const promptMessage of this.promptMessages) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (promptMessage instanceof _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseMessage */ .ku) + continue; + for (const inputVariable of promptMessage.inputVariables) { + inputVariablesMessages.add(inputVariable); + } + } + const totalInputVariables = this.inputVariables; + const inputVariablesInstance = new Set(this.partialVariables + ? totalInputVariables.concat(Object.keys(this.partialVariables)) + : totalInputVariables); + const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); + if (difference.size > 0) { + throw new Error(`Input variables \`${[ + ...difference, + ]}\` are not used in any of the prompt messages.`); + } + const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); + if (otherDifference.size > 0) { + throw new Error(`Input variables \`${[ + ...otherDifference, + ]}\` are used in prompt messages but not in the prompt template.`); + } + } + } + _getPromptType() { + return "chat"; + } + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let resultMessages = []; + for (const promptMessage of this.promptMessages) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (promptMessage instanceof _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseMessage */ .ku) { + resultMessages.push(promptMessage); + } + else { + const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { + if (!(inputVariable in allValues)) { + throw new Error(`Missing value for input variable \`${inputVariable.toString()}\``); + } + acc[inputVariable] = allValues[inputVariable]; + return acc; + }, {}); + const message = await promptMessage.formatMessages(inputValues); + resultMessages = resultMessages.concat(message); + } + } + return resultMessages; + } + async partial(values) { + // This is implemented in a way it doesn't require making + // BaseMessagePromptTemplate aware of .partial() + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables, + }; + return new ChatPromptTemplate(promptDict); + } + /** + * Create a chat model-specific prompt from individual chat messages + * or message-like tuples. + * @param promptMessages Messages to be passed to the chat model + * @returns A new ChatPromptTemplate + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromMessages(promptMessages) { + const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat( + // eslint-disable-next-line no-instanceof/no-instanceof + promptMessage instanceof ChatPromptTemplate + ? promptMessage.promptMessages + : [_coerceMessagePromptTemplateLike(promptMessage)]), []); + const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => + // eslint-disable-next-line no-instanceof/no-instanceof + promptMessage instanceof ChatPromptTemplate + ? Object.assign(acc, promptMessage.partialVariables) + : acc, Object.create(null)); + const inputVariables = new Set(); + for (const promptMessage of flattenedMessages) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (promptMessage instanceof _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseMessage */ .ku) + continue; + for (const inputVariable of promptMessage.inputVariables) { + if (inputVariable in flattenedPartialVariables) { + continue; + } + inputVariables.add(inputVariable); + } + } + return new ChatPromptTemplate({ + inputVariables: [...inputVariables], + promptMessages: flattenedMessages, + partialVariables: flattenedPartialVariables, + }); + } + /** @deprecated Renamed to .fromMessages */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static fromPromptMessages(promptMessages) { + return this.fromMessages(promptMessages); + } +} + + +/***/ }), + +/***/ 7573: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + + +// EXPORTS +__webpack_require__.d(__webpack_exports__, { + "b": () => (/* binding */ encodingForModel) +}); + +// UNUSED EXPORTS: getEncoding + +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-XXPGZHWZ.js +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + + + +// EXTERNAL MODULE: ./node_modules/base64-js/index.js +var base64_js = __webpack_require__(6463); +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-THGZSONF.js + + + +// src/utils.ts +function never(_) { +} +function bytePairMerge(piece, ranks) { + let parts = Array.from( + { length: piece.length }, + (_, i) => ({ start: i, end: i + 1 }) + ); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; + } + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } + } + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function escapeRegex(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = base64_js.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); + } + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); + } + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex( + Object.keys(this.specialTokens) + ); + const ret = []; + const allowedSpecialSet = new Set( + allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial + ); + const disallowedSpecialSet = new Set( + disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( + (x) => !allowedSpecialSet.has(x) + ) : disallowedSpecial + ); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error( + `The text contains a special token that is not allowed: ${specialMatch[0]}` + ); + } + } + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) + break; + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); + continue; + } + ret.push(...bytePairEncode(piece, this.rankMap)); + } + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; + } + return ret; + } + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); + } +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g"); +}); +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; + } + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; + } + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; + } + case "ada": + case "babbage": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; + } + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "text-embedding-ada-002": { + return "cl100k_base"; + } + default: + throw new Error("Unknown model"); + } +} + + + +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js + + + +// EXTERNAL MODULE: ./node_modules/langchain/dist/util/async_caller.js +var async_caller = __webpack_require__(2723); +;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/tiktoken.js + + +const cache = {}; +const caller = /* #__PURE__ */ new async_caller/* AsyncCaller */.L({}); +async function getEncoding(encoding, options) { + if (!(encoding in cache)) { + cache[encoding] = caller + .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`, { + signal: options?.signal, + }) + .then((res) => res.json()) + .catch((e) => { + delete cache[encoding]; + throw e; + }); + } + return new Tiktoken(await cache[encoding], options?.extendedSpecialTokens); +} +async function encodingForModel(model, options) { + return getEncoding(getEncodingNameForModel(model), options); +} + + +/***/ }) + +}; diff --git a/dist/806.index.js b/dist/806.index.js new file mode 100644 index 0000000..b4c93a7 --- /dev/null +++ b/dist/806.index.js @@ -0,0 +1,178 @@ +export const id = 806; +export const ids = [806,609]; +export const modules = { + +/***/ 609: +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FewShotPromptTemplate": () => (/* binding */ FewShotPromptTemplate) +/* harmony export */ }); +/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5411); +/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(837); +/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4095); + + + +/** + * Prompt template that contains few-shot examples. + * @augments BasePromptTemplate + * @augments FewShotPromptTemplateInput + */ +class FewShotPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { + constructor(input) { + super(input); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "examples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleSelector", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "examplePrompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "suffix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "exampleSeparator", { + enumerable: true, + configurable: true, + writable: true, + value: "\n\n" + }); + Object.defineProperty(this, "prefix", { + enumerable: true, + configurable: true, + writable: true, + value: "" + }); + Object.defineProperty(this, "templateFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "f-string" + }); + Object.defineProperty(this, "validateTemplate", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.assign(this, input); + if (this.examples !== undefined && this.exampleSelector !== undefined) { + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + } + if (this.examples === undefined && this.exampleSelector === undefined) { + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) { + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + } + (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "few_shot"; + } + async getExamples(inputVariables) { + if (this.examples !== undefined) { + return this.examples; + } + if (this.exampleSelector !== undefined) { + return this.exampleSelector.selectExamples(inputVariables); + } + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...(this.partialVariables ?? {}), + ...values, + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables, + }; + return new FewShotPromptTemplate(promptDict); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); + return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(template, this.templateFormat, allValues); + } + serialize() { + if (this.exampleSelector || !this.examples) { + throw new Error("Serializing an example selector is not currently supported"); + } + if (this.outputParser !== undefined) { + throw new Error("Serializing an output parser is not currently supported"); + } + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples, + }; + } + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) { + throw new Error("Missing example prompt"); + } + const examplePrompt = await _prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) { + examples = data.examples; + } + else { + throw new Error("Invalid examples format. Only list or string are supported."); + } + return new FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format, + }); + } +} + + +/***/ }) + +}; diff --git a/dist/index.js b/dist/index.js index 927c5b3..0a9b1bf 100644 --- a/dist/index.js +++ b/dist/index.js @@ -9809,5915 +9809,4840 @@ exports.isPlainObject = isPlainObject; /***/ }), -/***/ 8964: +/***/ 1917: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); - - -const ANSI_BACKGROUND_OFFSET = 10; - -const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; -const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], +var loader = __nccwpck_require__(1161); +var dumper = __nccwpck_require__(8866); - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - group[styleName] = styles[styleName]; +module.exports.Type = __nccwpck_require__(6073); +module.exports.Schema = __nccwpck_require__(1082); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(8562); +module.exports.JSON_SCHEMA = __nccwpck_require__(1035); +module.exports.CORE_SCHEMA = __nccwpck_require__(2011); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(8759); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = __nccwpck_require__(8179); - codes.set(style[0], style[1]); - } +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: __nccwpck_require__(7900), + float: __nccwpck_require__(2705), + map: __nccwpck_require__(6150), + null: __nccwpck_require__(721), + pairs: __nccwpck_require__(3328), + set: __nccwpck_require__(9548), + timestamp: __nccwpck_require__(9212), + bool: __nccwpck_require__(4993), + int: __nccwpck_require__(1615), + merge: __nccwpck_require__(6104), + omap: __nccwpck_require__(9046), + seq: __nccwpck_require__(7283), + str: __nccwpck_require__(3619) +}; - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load'); +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +module.exports.safeDump = renamed('safeDump', 'dump'); - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; +/***/ }), - styles.color.ansi256 = wrapAnsi256(); - styles.color.ansi16m = wrapAnsi16m(); - styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); +/***/ 6829: +/***/ ((module) => { - // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js - Object.defineProperties(styles, { - rgbToAnsi256: { - value: (red, green, blue) => { - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (red === green && green === blue) { - if (red < 8) { - return 16; - } - if (red > 248) { - return 231; - } - return Math.round(((red - 8) / 247) * 24) + 232; - } - return 16 + - (36 * Math.round(red / 255 * 5)) + - (6 * Math.round(green / 255 * 5)) + - Math.round(blue / 255 * 5); - }, - enumerable: false - }, - hexToRgb: { - value: hex => { - const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} - let {colorString} = matches.groups; - if (colorString.length === 3) { - colorString = colorString.split('').map(character => character + character).join(''); - } +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} - const integer = Number.parseInt(colorString, 16); - return [ - (integer >> 16) & 0xFF, - (integer >> 8) & 0xFF, - integer & 0xFF - ]; - }, - enumerable: false - }, - hexToAnsi256: { - value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), - enumerable: false - } - }); +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; - return styles; + return [ sequence ]; } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - - -/***/ }), -/***/ 996: -/***/ ((module) => { +function extend(target, source) { + var index, length, key, sourceKeys; + if (source) { + sourceKeys = Object.keys(source); + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } -const UPPERCASE = /[\p{Lu}]/u; -const LOWERCASE = /[\p{Ll}]/u; -const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; -const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; -const SEPARATORS = /[_.\- ]+/; + return target; +} -const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); -const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); -const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); -const preserveCamelCase = (string, toLowerCase, toUpperCase) => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; +function repeat(string, count) { + var result = '', cycle; - for (let i = 0; i < string.length; i++) { - const character = string[i]; + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } - if (isLastCharLower && UPPERCASE.test(character)) { - string = string.slice(0, i) + '-' + string.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { - string = string.slice(0, i - 1) + '-' + string.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; - } - } + return result; +} - return string; -}; -const preserveConsecutiveUppercase = (input, toLowerCase) => { - LEADING_CAPITAL.lastIndex = 0; +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} - return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); -}; -const postProcess = (input, toUpperCase) => { - SEPARATORS_AND_IDENTIFIER.lastIndex = 0; - NUMBERS_AND_IDENTIFIER.lastIndex = 0; +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; - return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) - .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); -}; -const camelCase = (input, options) => { - if (!(typeof input === 'string' || Array.isArray(input))) { - throw new TypeError('Expected the input to be `string | string[]`'); - } +/***/ }), - options = { - pascalCase: false, - preserveConsecutiveUppercase: false, - ...options - }; +/***/ 8866: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - if (input.length === 0) { - return ''; - } - const toLowerCase = options.locale === false ? - string => string.toLowerCase() : - string => string.toLocaleLowerCase(options.locale); - const toUpperCase = options.locale === false ? - string => string.toUpperCase() : - string => string.toLocaleUpperCase(options.locale); +/*eslint-disable no-use-before-define*/ - if (input.length === 1) { - return options.pascalCase ? toUpperCase(input) : toLowerCase(input); - } +var common = __nccwpck_require__(6829); +var YAMLException = __nccwpck_require__(8179); +var DEFAULT_SCHEMA = __nccwpck_require__(8759); - const hasUpperCase = input !== toLowerCase(input); +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; - if (hasUpperCase) { - input = preserveCamelCase(input, toLowerCase, toUpperCase); - } +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - input = input.replace(LEADING_SEPARATORS, ''); +var ESCAPE_SEQUENCES = {}; - if (options.preserveConsecutiveUppercase) { - input = preserveConsecutiveUppercase(input, toLowerCase); - } else { - input = toLowerCase(input); - } +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; - if (options.pascalCase) { - input = toUpperCase(input.charAt(0)) + input.slice(1); - } +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; - return postProcess(input, toUpperCase); -}; +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; -module.exports = camelCase; -// TODO: Remove this for the next major release -module.exports["default"] = camelCase; +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + if (map === null) return {}; -/***/ }), + result = {}; + keys = Object.keys(map); -/***/ 8655: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); -var __webpack_unused_export__; + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "zR", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "Qc", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "Pz", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "Gu", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "i8", ({ - enumerable: true, - get: function () { - return _version.default; + result[tag] = style; } -})); - -var _v = _interopRequireDefault(__nccwpck_require__(2811)); - -var _v2 = _interopRequireDefault(__nccwpck_require__(6240)); -var _v3 = _interopRequireDefault(__nccwpck_require__(2509)); - -var _v4 = _interopRequireDefault(__nccwpck_require__(9106)); + return result; +} -var _nil = _interopRequireDefault(__nccwpck_require__(5389)); +function encodeHex(character) { + var string, handle, length; -var _version = _interopRequireDefault(__nccwpck_require__(7660)); + string = character.toString(16).toUpperCase(); -var _validate = _interopRequireDefault(__nccwpck_require__(9475)); + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } -var _stringify = _interopRequireDefault(__nccwpck_require__(4831)); + return '\\' + handle + common.repeat('0', length - string.length) + string; +} -var _parse = _interopRequireDefault(__nccwpck_require__(6698)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; -/***/ }), +function State(options) { + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; -/***/ 7278: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + this.tag = null; + this.result = ''; + this.duplicates = []; + this.usedDuplicates = null; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (line.length && line !== '\n') result += ind; -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); + result += line; } - return _crypto.default.createHash('md5').update(bytes).digest(); + return result; } -var _default = md5; -exports["default"] = _default; +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} -/***/ }), +function testImplicitResolving(state, str) { + var index, length, type; -/***/ 4196: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + if (type.resolve(str)) { + return true; + } + } + return false; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _default = { - randomUUID: _crypto.default.randomUUID -}; -exports["default"] = _default; +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} -/***/ }), +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} -/***/ 5389: -/***/ ((__unused_webpack_module, exports) => { +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} -/***/ }), +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} -/***/ 6698: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} -var _validate = _interopRequireDefault(__nccwpck_require__(9475)); +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + return indentIndicator + chomp + '\n'; +} - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } -var _default = parse; -exports["default"] = _default; +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; -/***/ }), + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; -/***/ 1830: -/***/ ((__unused_webpack_module, exports) => { + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + return result; +} +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[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; -exports["default"] = _default; + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; -/***/ }), + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } -/***/ 534: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + return result; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; -let poolPtr = rnds8Pool.length; + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { - poolPtr = 0; + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } } - return rnds8Pool.slice(poolPtr, poolPtr += 16); + state.tag = _tag; + state.dump = '[' + _result + ']'; } -/***/ }), - -/***/ 2594: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); + _result += state.dump; + } } - return _crypto.default.createHash('sha1').update(bytes).digest(); + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. } -var _default = sha1; -exports["default"] = _default; +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; -/***/ }), + for (index = 0, length = objectKeyList.length; index < length; index += 1) { -/***/ 4831: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + if (state.condenseFlow) pairBuffer += '"'; + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } -var _validate = _interopRequireDefault(__nccwpck_require__(9475)); + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (state.dump.length > 1024) pairBuffer += '? '; -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; - -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - 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]]; -} + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields + pairBuffer += state.dump; - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); + // Both key and value are valid. + _result += pairBuffer; } - return uuid; + state.tag = _tag; + state.dump = '{' + _result + '}'; } -var _default = stringify; -exports["default"] = _default; - -/***/ }), - -/***/ 2811: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _rng = _interopRequireDefault(__nccwpck_require__(534)); - -var _stringify = __nccwpck_require__(4831); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; - -let _clockseq; // Previous uuid creation time +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + pairBuffer += state.dump; - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + pairBuffer += state.dump; - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + // Both key and value are valid. + _result += pairBuffer; } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} - msecs += 12219292800000; // `time_low` +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` + typeList = explicit ? state.explicitTypes : state.implicitTypes; - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; - b[i++] = clockseq & 0xff; // `node` + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; + state.dump = _result; + } + + return true; + } } - return buf || (0, _stringify.unsafeStringify)(b); + return false; } -var _default = v1; -exports["default"] = _default; - -/***/ }), - -/***/ 6240: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } -var _v = _interopRequireDefault(__nccwpck_require__(9545)); + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; -var _md = _interopRequireDefault(__nccwpck_require__(7278)); + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports["default"] = _default; + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } -/***/ }), + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); -/***/ 9545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + state.dump = tagStr + ' ' + state.dump; + } + } + return true; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; -var _stringify = __nccwpck_require__(4831); + inspectNode(object, objects, duplicatesIndexes); -var _parse = _interopRequireDefault(__nccwpck_require__(6698)); + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); - const bytes = []; + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } } - - return bytes; } -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; - -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; +function dump(input, options) { + options = options || {}; - if (typeof value === 'string') { - value = stringToBytes(value); - } + var state = new State(options); - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } + if (!state.noRefs) getDuplicateReferences(input, state); - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` + var value = input; + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; - if (buf) { - offset = offset || 0; + return ''; +} - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } +module.exports.dump = dump; - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); - } // Function#name is not settable on some platforms (#270) +/***/ }), +/***/ 8179: +/***/ ((module) => { - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support +// YAML error class. http://stackoverflow.com/questions/8458984 +// - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} -/***/ }), +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; -/***/ 2509: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!exception.mark) return message; + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } -var _native = _interopRequireDefault(__nccwpck_require__(4196)); + return message + ' ' + where; +} -var _rng = _interopRequireDefault(__nccwpck_require__(534)); -var _stringify = __nccwpck_require__(4831); +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; } +} - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } +module.exports = YAMLException; - return buf; - } - return (0, _stringify.unsafeStringify)(rnds); -} +/***/ }), -var _default = v4; -exports["default"] = _default; +/***/ 1161: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/***/ }), -/***/ 9106: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/*eslint-disable max-len,no-use-before-define*/ +var common = __nccwpck_require__(6829); +var YAMLException = __nccwpck_require__(8179); +var makeSnippet = __nccwpck_require__(6975); +var DEFAULT_SCHEMA = __nccwpck_require__(8759); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(9545)); +var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _sha = _interopRequireDefault(__nccwpck_require__(2594)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports["default"] = _default; -/***/ }), +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; -/***/ 9475: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _regex = _interopRequireDefault(__nccwpck_require__(1830)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _class(obj) { return Object.prototype.toString.call(obj); } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } -var _default = validate; -exports["default"] = _default; - -/***/ }), - -/***/ 7660: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +function fromHexCode(c) { + var lc; -var _validate = _interopRequireDefault(__nccwpck_require__(9475)); + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /*eslint-disable no-bitwise*/ + lc = c | 0x20; -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; } - return parseInt(uuid.slice(14, 15), 16); + return -1; } -var _default = version; -exports["default"] = _default; - -/***/ }), +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} -/***/ 9097: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -var __webpack_unused_export__; + return -1; +} +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "zR", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "Qc", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "Pz", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "Gu", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "i8", ({ - enumerable: true, - get: function () { - return _version.default; +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); } -})); - -var _v = _interopRequireDefault(__nccwpck_require__(4071)); + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} -var _v2 = _interopRequireDefault(__nccwpck_require__(7058)); +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} -var _v3 = _interopRequireDefault(__nccwpck_require__(5573)); -var _v4 = _interopRequireDefault(__nccwpck_require__(557)); +function State(input, options) { + this.input = input; -var _nil = _interopRequireDefault(__nccwpck_require__(9268)); + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; -var _version = _interopRequireDefault(__nccwpck_require__(6422)); + this.json = options['json'] || false; + this.listener = options['listener'] || null; -var _validate = _interopRequireDefault(__nccwpck_require__(2000)); + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; -var _stringify = _interopRequireDefault(__nccwpck_require__(2008)); + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; -var _parse = _interopRequireDefault(__nccwpck_require__(1813)); + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this.documents = []; -/***/ }), + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ -/***/ 9048: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +} +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + mark.snippet = makeSnippet(mark); -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + return new YAMLException(message, mark); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function throwError(state, message) { + throw generateError(state, message); +} -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); } - - return _crypto.default.createHash('md5').update(bytes).digest(); } -var _default = md5; -exports["default"] = _default; - -/***/ }), -/***/ 5696: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var directiveHandlers = { + YAML: function handleYamlDirective(state, name, args) { + var match, major, minor; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); -var _default = { - randomUUID: _crypto.default.randomUUID -}; -exports["default"] = _default; + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } -/***/ }), + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); -/***/ 9268: -/***/ ((__unused_webpack_module, exports) => { + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; + TAG: function handleTagDirective(state, name, args) { -/***/ }), + var handle, prefix; -/***/ 1813: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + handle = args[0]; + prefix = args[1]; + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } -var _validate = _interopRequireDefault(__nccwpck_require__(2000)); + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); + state.tagMap[handle] = prefix; } +}; - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ + if (start < end) { + _result = state.input.slice(start, end); - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; + state.result += _result; + } } -var _default = parse; -exports["default"] = _default; - -/***/ }), +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; -/***/ 1467: -/***/ ((__unused_webpack_module, exports) => { + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + sourceKeys = Object.keys(source); + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[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; -exports["default"] = _default; + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} -/***/ }), +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { -/***/ 4103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var index, quantity; + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + keyNode = String(keyNode); -let poolPtr = rnds8Pool.length; + if (_result === null) { + _result = {}; + } -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } - poolPtr = 0; + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; } - return rnds8Pool.slice(poolPtr, poolPtr += 16); + return _result; } -/***/ }), - -/***/ 86: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); +function readLineBreak(state) { + var ch; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + ch = state.input.charCodeAt(state.position); -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); } - return _crypto.default.createHash('sha1').update(bytes).digest(); + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; } -var _default = sha1; -exports["default"] = _default; +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); -/***/ }), + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } -/***/ 2008: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + if (is_EOL(ch)) { + readLineBreak(state); + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } -var _validate = _interopRequireDefault(__nccwpck_require__(2000)); + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return lineBreaks; +} -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; +function testDocumentSeparator(state) { + var _position = state.position, + ch; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} + ch = state.input.charCodeAt(_position); -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - 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]]; -} + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields + _position += 3; - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } } - return uuid; + return false; } -var _default = stringify; -exports["default"] = _default; - -/***/ }), +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} -/***/ 4071: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + ch = state.input.charCodeAt(state.position); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } -var _rng = _interopRequireDefault(__nccwpck_require__(4103)); + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); -var _stringify = __nccwpck_require__(2008); + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); -let _clockseq; // Previous uuid creation time + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + if (is_WS_OR_EOL(preceding)) { + break; + } -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + ch = state.input.charCodeAt(++state.position); + } - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + captureSegment(state, captureStart, captureEnd, false); - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval + if (state.result) { + return true; + } + state.kind = _kind; + state.result = _result; + return false; +} - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + ch = state.input.charCodeAt(state.position); - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + if (ch !== 0x27/* ' */) { + return false; } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - b[i++] = clockseq & 0xff; // `node` + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; + } else { + state.position++; + captureEnd = state.position; + } } - return buf || (0, _stringify.unsafeStringify)(b); + throwError(state, 'unexpected end of the stream within a single quoted scalar'); } -var _default = v1; -exports["default"] = _default; +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; -/***/ }), + ch = state.input.charCodeAt(state.position); -/***/ 7058: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (ch !== 0x22/* " */) { + return false; + } + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); -var _v = _interopRequireDefault(__nccwpck_require__(7329)); + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); -var _md = _interopRequireDefault(__nccwpck_require__(9048)); + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports["default"] = _default; + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); -/***/ }), + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; -/***/ 7329: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + } else { + throwError(state, 'expected hexadecimal character'); + } + } + state.result += charFromCodepoint(hexResult); + state.position++; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; + } else { + throwError(state, 'unknown escape sequence'); + } -var _stringify = __nccwpck_require__(2008); + captureStart = captureEnd = state.position; -var _parse = _interopRequireDefault(__nccwpck_require__(1813)); + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape + } else { + state.position++; + captureEnd = state.position; + } + } - const bytes = []; + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; } - return bytes; -} + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; + ch = state.input.charCodeAt(++state.position); -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); - if (typeof value === 'string') { - value = stringToBytes(value); - } + ch = state.input.charCodeAt(state.position); - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); } - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } - if (buf) { - offset = offset || 0; + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } + ch = state.input.charCodeAt(state.position); - return buf; + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; } - return (0, _stringify.unsafeStringify)(bytes); - } // Function#name is not settable on some platforms (#270) + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + skipSeparationSpace(state, true, nodeIndent); - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support + ch = state.input.charCodeAt(state.position); + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; + throwError(state, 'unexpected end of the stream within a flow collection'); } -/***/ }), - -/***/ 5573: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + ch = state.input.charCodeAt(state.position); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } -var _native = _interopRequireDefault(__nccwpck_require__(5696)); + state.kind = 'scalar'; + state.result = ''; -var _rng = _interopRequireDefault(__nccwpck_require__(4103)); + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); -var _stringify = __nccwpck_require__(2008); + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); + } else { + break; + } } - options = options || {}; - - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; - if (buf) { - offset = offset || 0; + ch = state.input.charCodeAt(state.position); - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - return buf; - } - - return (0, _stringify.unsafeStringify)(rnds); -} + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } -var _default = v4; -exports["default"] = _default; + if (is_EOL(ch)) { + emptyLines++; + continue; + } -/***/ }), + // End of the scalar. + if (state.lineIndent < textIndent) { -/***/ 557: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + // Folded style: use fancy rules to handle line breaks. + if (folding) { -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); -var _v = _interopRequireDefault(__nccwpck_require__(7329)); + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); -var _sha = _interopRequireDefault(__nccwpck_require__(86)); + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports["default"] = _default; + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } -/***/ }), + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; -/***/ 2000: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + captureSegment(state, captureStart, state.position, false); + } + return true; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; -var _regex = _interopRequireDefault(__nccwpck_require__(1467)); + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} + ch = state.input.charCodeAt(state.position); -var _default = validate; -exports["default"] = _default; + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } -/***/ }), + if (ch !== 0x2D/* - */) { + break; + } -/***/ 6422: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + following = state.input.charCodeAt(state.position + 1); + if (!is_WS_OR_EOL(following)) { + break; + } + detected = true; + state.position++; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } -var _validate = _interopRequireDefault(__nccwpck_require__(2000)); + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + ch = state.input.charCodeAt(state.position); -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } } - return parseInt(uuid.slice(14, 15), 16); + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; } -var _default = version; -exports["default"] = _default; +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; -/***/ }), + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; -/***/ 7426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - */ + ch = state.input.charCodeAt(state.position); -/** - * Module exports. - */ + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } -module.exports = __nccwpck_require__(3765) + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -/***/ }), + detected = true; + atExplicitKey = true; + allowCompact = true; -/***/ 3583: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + state.position += 1; + ch = following; + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; -/** - * Module dependencies. - * @private - */ + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } -var db = __nccwpck_require__(7426) -var extname = (__nccwpck_require__(1017).extname) + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); -/** - * Module variables. - * @private - */ + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); -/** - * Module exports. - * @public - */ + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - if (mime && mime.charset) { - return mime.charset - } + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } - return false -} + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } } - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str + // + // Epilogue. + // - if (!mime) { - return false + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; } - return mime + return detected; } -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) + ch = state.input.charCodeAt(state.position); - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] + if (ch !== 0x21/* ! */) return false; - if (!exts || !exts.length) { - return false + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); } - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ + ch = state.input.charCodeAt(++state.position); -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); - if (!extension) { - return false + } else { + tagHandle = '!'; } - return exports.types[extension] || false -} - -/** - * Populate the extensions and types maps. - * @private - */ + _position = state.position; -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - if (!exts || !exts.length) { - return + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { - // mime -> extensions - extensions[type] = exts - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); } } - // set the extension -> mime - types[extension] = type + ch = state.input.charCodeAt(++state.position); } - }) -} + tagName = state.input.slice(_position, state.position); -/***/ }), + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } -/***/ 900: -/***/ ((module) => { + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } -/** - * Helpers. - */ + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; + if (isVerbatim) { + state.tag = tagName; -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ + return true; +} -function parse(str) { - str = String(str); - if (str.length > 100) { - return; +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); } + + state.anchor = state.input.slice(_position, state.position); + return true; } -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function readAlias(state) { + var _position, alias, + ch; -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); } - return ms + 'ms'; + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; } -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this= d) { - return plural(ms, msAbs, d, 'day'); + if (state.listener !== null) { + state.listener('open', state); } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); + + state.tag = null; + state.anchor = null; + state.kind = null; + state.result = null; + + allowBlockStyles = allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT === nodeContext || + CONTEXT_BLOCK_IN === nodeContext; + + if (allowToSeek) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; } - return ms + ' ms'; -} -/** - * Pluralization helper. - */ + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + } else if (readAlias(state)) { + hasContent = true; -/***/ }), + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } -/***/ 7760: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; -/*! node-domexception. MIT License. Jimmy Wärting */ + if (state.tag === null) { + state.tag = '?'; + } + } -if (!globalThis.DOMException) { - try { - const { MessageChannel } = __nccwpck_require__(1267), - port = new MessageChannel().port1, - ab = new ArrayBuffer() - port.postMessage(ab, [ab, ab]) - } catch (err) { - err.constructor.name === 'DOMException' && ( - globalThis.DOMException = err.constructor - ) + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } } -} -module.exports = globalThis.DOMException + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } -/***/ }), + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; -/***/ 467: -/***/ ((module, exports, __nccwpck_require__) => { + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } -var Stream = _interopDefault(__nccwpck_require__(2781)); -var http = _interopDefault(__nccwpck_require__(3685)); -var Url = _interopDefault(__nccwpck_require__(7310)); -var whatwgUrl = _interopDefault(__nccwpck_require__(8665)); -var https = _interopDefault(__nccwpck_require__(5687)); -var zlib = _interopDefault(__nccwpck_require__(9796)); + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); -class Blob { - constructor() { - this[TYPE] = ''; + ch = state.input.charCodeAt(state.position); - const blobParts = arguments[0]; - const options = arguments[1]; + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } - const buffers = []; - let size = 0; + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } - this[BUFFER] = Buffer.concat(buffers); + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); + if (is_EOL(ch)) break; -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); + _position = state.position; -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); + directiveArgs.push(state.input.slice(_position, state.position)); + } - this.message = message; - this.type = type; + if (ch !== 0) readLineBreak(state); - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } } - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} - -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; + skipSeparationSpace(state, true, -1); -let convert; -try { - convert = (__nccwpck_require__(2877).convert); -} catch (e) {} + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); -const INTERNALS = Symbol('Body internals'); + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; + state.documents.push(state.result); - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + if (state.position === state.lineStart && testDocumentSeparator(state)) { - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } } -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, - get bodyUsed() { - return this[INTERNALS].disturbed; - }, +function loadDocuments(input, options) { + input = String(input); + options = options || {}; - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, + if (input.length !== 0) { - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, + var state = new State(input, options); - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, + var nullpos = input.indexOf('\0'); - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); + while (state.position < (state.length - 1)) { + readDocument(state); + } -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; + return state.documents; +} -/** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise - */ -function consumeBody() { - var _this4 = this; - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } - this[INTERNALS].disturbed = true; + var documents = loadDocuments(input, options); - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } + if (typeof iterator !== 'function') { + return documents; + } - let body = this.body; + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - // body is blob - if (isBlob(body)) { - body = body.stream(); - } +function load(input, options) { + var documents = loadDocuments(input, options); - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; +module.exports.loadAll = loadAll; +module.exports.load = load; - return new Body.Promise(function (resolve, reject) { - let resTimeout; - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } +/***/ }), - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); +/***/ 1082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } - accumBytes += chunk.length; - accum.push(chunk); - }); +/*eslint-disable max-len*/ - body.on('end', function () { - if (abort) { - return; - } +var YAMLException = __nccwpck_require__(8179); +var Type = __nccwpck_require__(6073); - clearTimeout(resTimeout); - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); -} +function compileList(schema, name) { + var result = []; -/** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String - */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } + schema[name].forEach(function (currentType) { + var newIndex = result.length; - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } + newIndex = previousIndex; + } + }); - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); + result[newIndex] = currentType; + }); - // html5 - if (!res && str) { - res = / { -/** - * Find the key in the map object given a header name. - * - * Returns undefined if not found. - * - * @param String name Header name - * @return String|Undefined - */ -function find(map, name) { - name = name.toLowerCase(); - for (const key in map) { - if (key.toLowerCase() === name) { - return key; - } - } - return undefined; -} +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. -const MAP = Symbol('map'); -class Headers { - /** - * Headers class - * - * @param Object headers Response headers - * @return Void - */ - constructor() { - let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - this[MAP] = Object.create(null); - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } - return; - } +module.exports = __nccwpck_require__(1035); - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } +/***/ }), - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } +/***/ 8759: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) - return this[MAP][key].join(', '); - } - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } +module.exports = (__nccwpck_require__(2011).extend)({ + implicit: [ + __nccwpck_require__(9212), + __nccwpck_require__(6104) + ], + explicit: [ + __nccwpck_require__(7900), + __nccwpck_require__(9046), + __nccwpck_require__(3328), + __nccwpck_require__(9548) + ] +}); - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } +/***/ }), - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } +/***/ 8562: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } -} -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); +var Schema = __nccwpck_require__(1082); -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(3619), + __nccwpck_require__(7283), + __nccwpck_require__(6150) + ] +}); -const INTERNAL = Symbol('internal'); -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} +/***/ }), -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } +/***/ 1035: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - this[INTERNAL].index = index + 1; - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true + +module.exports = (__nccwpck_require__(8562).extend)({ + implicit: [ + __nccwpck_require__(721), + __nccwpck_require__(4993), + __nccwpck_require__(1615), + __nccwpck_require__(2705) + ] }); -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } +/***/ }), - return obj; -} +/***/ 6975: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; -} - -const INTERNALS$1 = Symbol('Response internals'); -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - Body.call(this, body, opts); +var common = __nccwpck_require__(6829); - const status = opts.status || 200; - const headers = new Headers(opts.headers); - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } - get url() { - return this[INTERNALS$1].url || ''; - } + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } - get status() { - return this[INTERNALS$1].status; - } + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } - get redirected() { - return this[INTERNALS$1].counter > 0; - } +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} - get statusText() { - return this[INTERNALS$1].statusText; - } - get headers() { - return this[INTERNALS$1].headers; - } +function makeSnippet(mark, options) { + options = Object.create(options || null); - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } -} + if (!mark.buffer) return null; -Body.mixIn(Response.prototype); + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; -/** - * Wrapper around `new URL` to handle arbitrary URLs - * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 - */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; -} + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); + return result.replace(/\n$/, ''); } -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - let parsedURL; - - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +module.exports = makeSnippet; - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; +/***/ }), - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); +/***/ 6073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const headers = new Headers(init.headers || input.headers || {}); - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; +var YAMLException = __nccwpck_require__(8179); - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } +function compileStyleAliases(map) { + var result = {}; - get method() { - return this[INTERNALS$2].method; - } + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } + return result; +} - get headers() { - return this[INTERNALS$2].headers; - } +function Type(tag, options) { + options = options || {}; - get redirect() { - return this[INTERNALS$2].redirect; - } + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); - get signal() { - return this[INTERNALS$2].signal; - } + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } } -Body.mixIn(Request.prototype); +module.exports = Type; -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); +/***/ }), -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); +/***/ 7900: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } +/*eslint-disable no-bitwise*/ - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } +var Type = __nccwpck_require__(6073); - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js +function resolveYamlBinary(data) { + if (data === null) return false; - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); -} + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); + // Skip CR/LF + if (code > 64) continue; - this.type = 'aborted'; - this.message = message; + // Fail on illegal characters + if (code < 0) return false; - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; } -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; -const URL$1 = Url.URL || whatwgUrl.URL; + // Collect by 6*4 bits (3 bytes) -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; + // Dump tail -/** - * isSameProtocol reports whether the two provided URLs use the same protocol. - * - * Both domains must already be in canonical form. - * @param {string|URL} original - * @param {string|URL} destination - */ -const isSameProtocol = function isSameProtocol(destination, original) { - const orig = new URL$1(original).protocol; - const dest = new URL$1(destination).protocol; + tailbits = (max % 4) * 6; - return orig === dest; -}; + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { - - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } + return new Uint8Array(result); +} - Body.Promise = fetch.Promise; +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); + // Convert every three bytes to 4 ASCII characters. - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } - let response = null; + bits = (bits << 8) + object[idx]; + } - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - destroyStream(request.body, error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; + // Dump tail - if (signal && signal.aborted) { - abort(); - return; - } + tail = max % 3; - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } - // send request - const req = send(options); - let reqTimeout; + return result; +} - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); +/***/ }), - if (response && response.body) { - destroyStream(response.body, err); - } +/***/ 4993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - finalize(); - }); - fixResponseChunkedTransferBadEnding(req, function (err) { - if (signal && signal.aborted) { - return; - } - if (response && response.body) { - destroyStream(response.body, err); - } - }); +var Type = __nccwpck_require__(6073); - /* c8 ignore next 18 */ - if (parseInt(process.version.substring(1)) < 14) { - // Before Node.js 14, pipeline() does not fully support async iterators and does not always - // properly handle when the socket close/end events are out of order. - req.on('socket', function (s) { - s.addListener('close', function (hadError) { - // if a data listener is still present we didn't end cleanly - const hasDataListener = s.listenerCount('data') > 0; +function resolveYamlBoolean(data) { + if (data === null) return false; - // if end happened before close but the socket didn't emit an error, do it now - if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - response.body.emit('error', err); - } - }); - }); - } + var max = data.length; - req.on('response', function (res) { - clearTimeout(reqTimeout); + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} - const headers = createHeadersLenient(res.headers); +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} - // HTTP fetch step 5.3 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } +/***/ }), - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; +/***/ 2705: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } +var common = __nccwpck_require__(6829); +var Type = __nccwpck_require__(6073); - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); +function resolveYamlFloat(data) { + if (data === null) return false; - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); + return true; +} - // HTTP-network fetch step 12.1.1.4: handle content codings +function constructYamlFloat(data) { + var value, sign; - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - raw.on('end', function () { - // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. - if (!response) { - response = new Response(body, response_options); - resolve(response); - } - }); - return; - } + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - writeToStream(req, request); - }); -} -function fixResponseChunkedTransferBadEnding(request, errorCallback) { - let socket; +function representYamlFloat(object, style) { + var res; - request.on('socket', function (s) { - socket = s; - }); + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } - request.on('response', function (response) { - const headers = response.headers; + res = object.toString(10); - if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { - response.once('close', function (hadError) { - // tests for socket presence, as in some situations the - // the 'socket' event is not triggered for the request - // (happens in deno), avoids `TypeError` - // if a data listener is still present we didn't end cleanly - const hasDataListener = socket && socket.listenerCount('data') > 0; + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack - if (hasDataListener && !hadError) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - errorCallback(err); - } - }); - } - }); + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } -function destroyStream(stream, err) { - if (stream.destroy) { - stream.destroy(err); - } else { - // node < 8 - stream.emit('error', err); - stream.end(); - } +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); } -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; - -// expose Promise -fetch.Promise = global.Promise; - -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; -exports.AbortError = AbortError; +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); /***/ }), -/***/ 4856: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 1615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var crypto = __nccwpck_require__(6113); +var common = __nccwpck_require__(6829); +var Type = __nccwpck_require__(6073); -/** - * Exported function - * - * Options: - * - * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' - * - `excludeValues` {true|*false} hash object keys, values ignored - * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' - * - `ignoreUnknown` {true|*false} ignore unknown object types - * - `replacer` optional function that replaces values before hashing - * - `respectFunctionProperties` {*true|false} consider function properties when hashing - * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing - * - `respectType` {*true|false} Respect special properties (prototype, constructor) - * when hashing to distinguish between types - * - `unorderedArrays` {true|*false} Sort all arrays before hashing - * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing - * * = default - * - * @param {object} object value to hash - * @param {object} options hashing options - * @return {string} hash value - * @api public - */ -exports = module.exports = objectHash; +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} -function objectHash(object, options){ - options = applyDefaults(object, options); +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} - return hash(object, options); +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } -/** - * Exported sugar methods - * - * @param {object} object value to hash - * @return {string} hash value - * @api public - */ -exports.sha1 = function(object){ - return objectHash(object); -}; -exports.keys = function(object){ - return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); -}; -exports.MD5 = function(object){ - return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); -}; -exports.keysMD5 = function(object){ - return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); -}; +function resolveYamlInteger(data) { + if (data === null) return false; -// Internals -var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; -hashes.push('passthrough'); -var encodings = ['buffer', 'hex', 'binary', 'base64']; + var max = data.length, + index = 0, + hasDigits = false, + ch; -function applyDefaults(object, sourceOptions){ - sourceOptions = sourceOptions || {}; + if (!max) return false; - // create a copy rather than mutating - var options = {}; - options.algorithm = sourceOptions.algorithm || 'sha1'; - options.encoding = sourceOptions.encoding || 'hex'; - options.excludeValues = sourceOptions.excludeValues ? true : false; - options.algorithm = options.algorithm.toLowerCase(); - options.encoding = options.encoding.toLowerCase(); - options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false - options.respectType = sourceOptions.respectType === false ? false : true; // default to true - options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; - options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; - options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false - options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false - options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true - options.replacer = sourceOptions.replacer || undefined; - options.excludeKeys = sourceOptions.excludeKeys || undefined; + ch = data[index]; - if(typeof object === 'undefined') { - throw new Error('Object argument required.'); + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; } - // if there is a case-insensitive match in the hashes list, accept it - // (i.e. SHA256 for sha256) - for (var i = 0; i < hashes.length; ++i) { - if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { - options.algorithm = hashes[i]; + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - } - if(hashes.indexOf(options.algorithm) === -1){ - throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + - 'supported values: ' + hashes.join(', ')); - } - if(encodings.indexOf(options.encoding) === -1 && - options.algorithm !== 'passthrough'){ - throw new Error('Encoding "' + options.encoding + '" not supported. ' + - 'supported values: ' + encodings.join(', ')); + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } } - return options; -} + // base 10 (except 0) -/** Check if the given function is a native function */ -function isNativeFunction(f) { - if ((typeof f) !== 'function') { - return false; + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; } - var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; - return exp.exec(Function.prototype.toString.call(f)) != null; + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; } -function hash(object, options) { - var hashingStream; +function constructYamlInteger(data) { + var value = data, sign = 1, ch; - if (options.algorithm !== 'passthrough') { - hashingStream = crypto.createHash(options.algorithm); - } else { - hashingStream = new PassThrough(); + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); } - if (typeof hashingStream.write === 'undefined') { - hashingStream.write = hashingStream.update; - hashingStream.end = hashingStream.update; - } + ch = value[0]; - var hasher = typeHasher(options, hashingStream); - hasher.dispatch(object); - if (!hashingStream.update) { - hashingStream.end(''); + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; } - if (hashingStream.digest) { - return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); - } + if (value === '0') return 0; - var buf = hashingStream.read(); - if (options.encoding === 'buffer') { - return buf; + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); } - return buf.toString(options.encoding); + return sign * parseInt(value, 10); } -/** - * Expose streaming API - * - * @param {object} object Value to serialize - * @param {object} options Options, as for hash() - * @param {object} stream A stream to write the serializiation to - * @api public - */ -exports.writeToStream = function(object, options, stream) { - if (typeof stream === 'undefined') { - stream = options; - options = {}; +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] } +}); - options = applyDefaults(object, options); - return typeHasher(options, stream).dispatch(object); -}; +/***/ }), -function typeHasher(options, writeTo, context){ - context = context || []; - var write = function(str) { - if (writeTo.update) { - return writeTo.update(str, 'utf8'); - } else { - return writeTo.write(str, 'utf8'); - } - }; +/***/ 6150: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return { - dispatch: function(value){ - if (options.replacer) { - value = options.replacer(value); - } - var type = typeof value; - if (value === null) { - type = 'null'; - } - //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); +var Type = __nccwpck_require__(6073); - return this['_' + type](value); - }, - _object: function(object) { - var pattern = (/\[object (.*)\]/i); - var objString = Object.prototype.toString.call(object); - var objType = pattern.exec(objString); - if (!objType) { // object type did not match [object ...] - objType = 'unknown:[' + objString + ']'; - } else { - objType = objType[1]; // take only the class name - } +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); - objType = objType.toLowerCase(); - var objectNumber = null; +/***/ }), - if ((objectNumber = context.indexOf(object)) >= 0) { - return this.dispatch('[CIRCULAR:' + objectNumber + ']'); - } else { - context.push(object); - } +/***/ 6104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { - write('buffer:'); - return write(object); - } - if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { - if(this['_' + objType]) { - this['_' + objType](object); - } else if (options.ignoreUnknown) { - return write('[' + objType + ']'); - } else { - throw new Error('Unknown object type "' + objType + '"'); - } - }else{ - var keys = Object.keys(object); - if (options.unorderedObjects) { - keys = keys.sort(); - } - // Make sure to incorporate special properties, so - // Types with different prototypes will produce - // a different hash and objects derived from - // different functions (`new Foo`, `new Bar`) will - // produce different hashes. - // We never do this for native functions since some - // seem to break because of that. - if (options.respectType !== false && !isNativeFunction(object)) { - keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); - } - if (options.excludeKeys) { - keys = keys.filter(function(key) { return !options.excludeKeys(key); }); - } +var Type = __nccwpck_require__(6073); - write('object:' + keys.length + ':'); - var self = this; - return keys.forEach(function(key){ - self.dispatch(key); - write(':'); - if(!options.excludeValues) { - self.dispatch(object[key]); - } - write(','); - }); - } - }, - _array: function(arr, unordered){ - unordered = typeof unordered !== 'undefined' ? unordered : - options.unorderedArrays !== false; // default to options.unorderedArrays +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} - var self = this; - write('array:' + arr.length + ':'); - if (!unordered || arr.length <= 1) { - return arr.forEach(function(entry) { - return self.dispatch(entry); - }); - } +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); - // the unordered case is a little more complicated: - // since there is no canonical ordering on objects, - // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, - // we first serialize each entry using a PassThrough stream - // before sorting. - // also: we can’t use the same context array for all entries - // since the order of hashing should *not* matter. instead, - // we keep track of the additions to a copy of the context array - // and add all of them to the global context array when we’re done - var contextAdditions = []; - var entries = arr.map(function(entry) { - var strm = new PassThrough(); - var localContext = context.slice(); // make copy - var hasher = typeHasher(options, strm, localContext); - hasher.dispatch(entry); - // take only what was added to localContext and append it to contextAdditions - contextAdditions = contextAdditions.concat(localContext.slice(context.length)); - return strm.read().toString(); - }); - context = context.concat(contextAdditions); - entries.sort(); - return this._array(entries, false); - }, - _date: function(date){ - return write('date:' + date.toJSON()); - }, - _symbol: function(sym){ - return write('symbol:' + sym.toString()); - }, - _error: function(err){ - return write('error:' + err.toString()); - }, - _boolean: function(bool){ - return write('bool:' + bool.toString()); - }, - _string: function(string){ - write('string:' + string.length + ':'); - write(string.toString()); - }, - _function: function(fn){ - write('fn:'); - if (isNativeFunction(fn)) { - this.dispatch('[native]'); - } else { - this.dispatch(fn.toString()); - } - if (options.respectFunctionNames !== false) { - // Make sure we can still distinguish native functions - // by their name, otherwise String and Function will - // have the same hash - this.dispatch("function-name:" + String(fn.name)); - } +/***/ }), - if (options.respectFunctionProperties) { - this._object(fn); - } - }, - _number: function(number){ - return write('number:' + number.toString()); - }, - _xml: function(xml){ - return write('xml:' + xml.toString()); - }, - _null: function() { - return write('Null'); - }, - _undefined: function() { - return write('Undefined'); - }, - _regexp: function(regex){ - return write('regex:' + regex.toString()); - }, - _uint8array: function(arr){ - write('uint8array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint8clampedarray: function(arr){ - write('uint8clampedarray:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int8array: function(arr){ - write('int8array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint16array: function(arr){ - write('uint16array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int16array: function(arr){ - write('int16array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _uint32array: function(arr){ - write('uint32array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _int32array: function(arr){ - write('int32array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _float32array: function(arr){ - write('float32array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _float64array: function(arr){ - write('float64array:'); - return this.dispatch(Array.prototype.slice.call(arr)); - }, - _arraybuffer: function(arr){ - write('arraybuffer:'); - return this.dispatch(new Uint8Array(arr)); - }, - _url: function(url) { - return write('url:' + url.toString(), 'utf8'); - }, - _map: function(map) { - write('map:'); - var arr = Array.from(map); - return this._array(arr, options.unorderedSets !== false); - }, - _set: function(set) { - write('set:'); - var arr = Array.from(set); - return this._array(arr, options.unorderedSets !== false); - }, - _file: function(file) { - write('file:'); - return this.dispatch([file.name, file.size, file.type, file.lastModfied]); - }, - _blob: function() { - if (options.ignoreUnknown) { - return write('[blob]'); - } +/***/ 721: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - throw Error('Hashing Blob objects is currently not supported\n' + - '(see https://github.com/puleos/object-hash/issues/26)\n' + - 'Use "options.replacer" or "options.ignoreUnknown"\n'); - }, - _domwindow: function() { return write('domwindow'); }, - _bigint: function(number){ - return write('bigint:' + number.toString()); - }, - /* Node.js standard native objects */ - _process: function() { return write('process'); }, - _timer: function() { return write('timer'); }, - _pipe: function() { return write('pipe'); }, - _tcp: function() { return write('tcp'); }, - _udp: function() { return write('udp'); }, - _tty: function() { return write('tty'); }, - _statwatcher: function() { return write('statwatcher'); }, - _securecontext: function() { return write('securecontext'); }, - _connection: function() { return write('connection'); }, - _zlib: function() { return write('zlib'); }, - _context: function() { return write('context'); }, - _nodescript: function() { return write('nodescript'); }, - _httpparser: function() { return write('httpparser'); }, - _dataview: function() { return write('dataview'); }, - _signal: function() { return write('signal'); }, - _fsevent: function() { return write('fsevent'); }, - _tlswrap: function() { return write('tlswrap'); }, - }; -} -// Mini-implementation of stream.PassThrough -// We are far from having need for the full implementation, and we can -// make assumptions like "many writes, then only one final read" -// and we can ignore encoding specifics -function PassThrough() { - return { - buf: '', - write: function(b) { - this.buf += b; - }, +var Type = __nccwpck_require__(6073); - end: function(b) { - this.buf += b; - }, +function resolveYamlNull(data) { + if (data === null) return true; - read: function() { - return this.buf; - } - }; + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; } +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + /***/ }), -/***/ 1223: +/***/ 9046: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(2940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) +var Type = __nccwpck_require__(6073); -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } - f.called = false - return f + + return true; } -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f +function constructYamlOmap(data) { + return data !== null ? data : []; } +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + /***/ }), -/***/ 1330: -/***/ ((module) => { +/***/ 3328: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; +var Type = __nccwpck_require__(6073); +var _toString = Object.prototype.toString; -/***/ }), +function resolveYamlPairs(data) { + if (data === null) return true; -/***/ 8983: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var index, length, pair, keys, result, + object = data; + result = new Array(object.length); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const EventEmitter = __nccwpck_require__(1848); -const p_timeout_1 = __nccwpck_require__(6424); -const priority_queue_1 = __nccwpck_require__(8492); -// eslint-disable-next-line @typescript-eslint/no-empty-function -const empty = () => { }; -const timeoutError = new p_timeout_1.TimeoutError(); -/** -Promise queue with concurrency control. -*/ -class PQueue extends EventEmitter { - constructor(options) { - var _a, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; - } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; - } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit('next'); - } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit('idle'); - } - } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = undefined; - } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === undefined) { - const delay = this._intervalEnd - now; - if (delay < 0) { - // Act as the interval was done - // We don't need to resume it here because it will be resumed on line 160 - this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; - } - else { - // Act as the interval is pending - if (this._timeoutId === undefined) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - // We can clear the interval ("pause") - // Because we can redo it later ("resume") - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = undefined; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit('active'); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; - } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== undefined) { - return; - } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; - } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - // eslint-disable-next-line no-empty - while (this._tryToStartAnother()) { } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { - if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return undefined; - }); - resolve(await operation); - } - catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit('add'); - }); - } - /** - Same as `.add()`, but accepts an array of sync or async functions. + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; - } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); - } - /** - Can be called multiple times. Useful if you for example add additional items at a later time. + if (_toString.call(pair) !== '[object Object]') return false; - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - // Instantly resolve if the queue is empty - if (this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + keys = Object.keys(pair); - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - // Instantly resolve if none pending and if nothing else is queued - if (this._pendingCount === 0 && this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. + if (keys.length !== 1) return false; - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - return this._queue.filter(options).length; - } - /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; - } - /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; - } - /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; - } + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; } -exports["default"] = PQueue; +function constructYamlPairs(data) { + if (data === null) return []; -/***/ }), + var index, length, pair, keys, result, + object = data; -/***/ 2291: -/***/ ((__unused_webpack_module, exports) => { + result = new Array(object.length); + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound -// Used to compute insertion index to keep queue sorted after insertion -function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = (count / 2) | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count -= step + 1; - } - else { - count = step; - } - } - return first; + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; } -exports["default"] = lowerBound; + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); /***/ }), -/***/ 8492: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7283: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lower_bound_1 = __nccwpck_require__(2291); -class PriorityQueue { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; - } - const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); - this._queue.splice(index, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } -} -exports["default"] = PriorityQueue; + +var Type = __nccwpck_require__(6073); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); /***/ }), -/***/ 2548: +/***/ 9548: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const retry = __nccwpck_require__(4347); -const networkErrorMsgs = [ - 'Failed to fetch', // Chrome - 'NetworkError when attempting to fetch resource.', // Firefox - 'The Internet connection appears to be offline.', // Safari - 'Network request failed' // `cross-fetch` -]; +var Type = __nccwpck_require__(6073); -class AbortError extends Error { - constructor(message) { - super(); +var _hasOwnProperty = Object.prototype.hasOwnProperty; - if (message instanceof Error) { - this.originalError = message; - ({message} = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } +function resolveYamlSet(data) { + if (data === null) return true; - this.name = 'AbortError'; - this.message = message; - } + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; } -const decorateErrorWithCounts = (error, attemptNumber, options) => { - // Minus 1 from attemptNumber because the first attempt does not count as a retry - const retriesLeft = options.retries - (attemptNumber - 1); +function constructYamlSet(data) { + return data !== null ? data : {}; +} - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; -}; +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); -const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); -const pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => {}, - retries: 10, - ...options - }; +/***/ }), - const operation = retry.operation(options); +/***/ 3619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - operation.attempt(async attemptNumber => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - try { - await options.onFailedAttempt(error); - } catch (error) { - reject(error); - return; - } +var Type = __nccwpck_require__(6073); - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } }); -module.exports = pRetry; -// TODO: remove this in the next major version -module.exports["default"] = pRetry; - -module.exports.AbortError = AbortError; - /***/ }), -/***/ 6424: +/***/ 9212: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const pFinally = __nccwpck_require__(1330); - -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } -} - -const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== 'number' || milliseconds < 0) { - throw new TypeError('Expected `milliseconds` to be a positive number'); - } - - if (milliseconds === Infinity) { - resolve(promise); - return; - } - - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } - - return; - } - - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); - - if (typeof promise.cancel === 'function') { - promise.cancel(); - } - - reject(timeoutError); - }, milliseconds); - - // TODO: Use native `finally` keyword when targeting Node.js 10 - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); +var Type = __nccwpck_require__(6073); -module.exports = pTimeout; -// TODO: Remove this for the next major release -module.exports["default"] = pTimeout; +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day -module.exports.TimeoutError = TimeoutError; +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} -/***/ }), +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; -/***/ 3329: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + if (match === null) throw new Error('Date resolve error'); + // match: [1] year [2] month [3] day -var parseUrl = (__nccwpck_require__(7310).parse); + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); -var DEFAULT_PORTS = { - ftp: 21, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443, -}; + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } -var stringEndsWith = String.prototype.endsWith || function(s) { - return s.length <= this.length && - this.indexOf(s, this.length - s.length) !== -1; -}; + // match: [4] hour [5] minute [6] second [7] fraction -/** - * @param {string|object} url - The URL, or the result from url.parse. - * @return {string} The URL of the proxy that should handle the request to the - * given URL. If no proxy is set, this will be an empty string. - */ -function getProxyForUrl(url) { - var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; - var proto = parsedUrl.protocol; - var hostname = parsedUrl.host; - var port = parsedUrl.port; - if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { - return ''; // Don't proxy URLs without a valid scheme or host. - } + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); - proto = proto.split(':', 1)[0]; - // Stripping ports in this way instead of using parsedUrl.hostname to make - // sure that the brackets around IPv6 addresses are kept. - hostname = hostname.replace(/:\d*$/, ''); - port = parseInt(port) || DEFAULT_PORTS[proto] || 0; - if (!shouldProxy(hostname, port)) { - return ''; // Don't proxy URLs that match NO_PROXY. + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; } - var proxy = - getEnv('npm_config_' + proto + '_proxy') || - getEnv(proto + '_proxy') || - getEnv('npm_config_proxy') || - getEnv('all_proxy'); - if (proxy && proxy.indexOf('://') === -1) { - // Missing scheme in proxy, default to the requested URL's scheme. - proxy = proto + '://' + proxy; - } - return proxy; -} + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute -/** - * Determines whether a given URL should be proxied. - * - * @param {string} hostname - The host name of the URL. - * @param {number} port - The effective port of the URL. - * @returns {boolean} Whether the given URL should be proxied. - * @private - */ -function shouldProxy(hostname, port) { - var NO_PROXY = - (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); - if (!NO_PROXY) { - return true; // Always proxy if NO_PROXY is not set. - } - if (NO_PROXY === '*') { - return false; // Never proxy if wildcard is set. + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; } - return NO_PROXY.split(/[,\s]/).every(function(proxy) { - if (!proxy) { - return true; // Skip zero-length hosts. - } - var parsedProxy = proxy.match(/^(.+):(\d+)$/); - var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; - var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; - if (parsedProxyPort && parsedProxyPort !== port) { - return true; // Skip if ports don't match. - } + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - if (!/^[.*]/.test(parsedProxyHostname)) { - // No wildcards, so stop proxying if there is an exact match. - return hostname !== parsedProxyHostname; - } + if (delta) date.setTime(date.getTime() - delta); - if (parsedProxyHostname.charAt(0) === '*') { - // Remove leading wildcard. - parsedProxyHostname = parsedProxyHostname.slice(1); - } - // Stop proxying if the hostname ends with the no_proxy host. - return !stringEndsWith.call(hostname, parsedProxyHostname); - }); + return date; } -/** - * Get the value for an environment variable. - * - * @param {string} key - The name of the environment variable. - * @return {string} The value of the environment variable. - * @private - */ -function getEnv(key) { - return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); } -exports.j = getProxyForUrl; +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); /***/ }), -/***/ 4347: +/***/ 8964: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(6244); +/* module decorator */ module = __nccwpck_require__.nmd(module); -/***/ }), -/***/ 6244: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const ANSI_BACKGROUND_OFFSET = 10; -var RetryOperation = __nccwpck_require__(5369); +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); - } + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); - } + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); + group[styleName] = styles[styleName]; - return timeouts; -}; + codes.set(style[0], style[1]); + } -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); - return timeout; -}; + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } - } + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value: (red, green, blue) => { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; + if (red > 248) { + return 231; + } - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); + return Math.round(((red - 8) / 247) * 24) + 232; + } - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false + }, + hexToRgb: { + value: hex => { + const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; + let {colorString} = matches.groups; + if (colorString.length === 3) { + colorString = colorString.split('').map(character => character + character).join(''); + } -/***/ }), + const integer = Number.parseInt(colorString, 16); -/***/ 5369: -/***/ ((module) => { + return [ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF + ]; + }, + enumerable: false + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false + } + }); -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } + return styles; +} - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); -} +/***/ }), -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } +/***/ 996: +/***/ ((module) => { - this._timeouts = []; - this._cachedTimeouts = null; -}; -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; - } +const UPPERCASE = /[\p{Lu}]/u; +const LOWERCASE = /[\p{Ll}]/u; +const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; +const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; +const SEPARATORS = /[_.\- ]+/; - this._errors.push(err); +const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); +const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); +const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } - } +const preserveCamelCase = (string, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; - var self = this; - this._timer = setTimeout(function() { - self._attempts++; + for (let i = 0; i < string.length; i++) { + const character = string[i]; - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } - if (self._options.unref) { - self._timeout.unref(); - } - } + return string; +}; - self._fn(self._attempts); - }, timeout); +const preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; - if (this._options.unref) { - this._timer.unref(); - } + return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); +}; - return true; +const postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + + return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) + .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); }; -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } - this._operationStart = new Date().getTime(); + if (input.length === 0) { + return ''; + } - this._fn(this._attempts); -}; + const toLowerCase = options.locale === false ? + string => string.toLowerCase() : + string => string.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? + string => string.toUpperCase() : + string => string.toLocaleUpperCase(options.locale); -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; + const hasUpperCase = input !== toLowerCase(input); -RetryOperation.prototype.start = RetryOperation.prototype.try; + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } -RetryOperation.prototype.errors = function() { - return this._errors; -}; + input = input.replace(LEADING_SEPARATORS, ''); -RetryOperation.prototype.attempts = function() { - return this._attempts; + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + + return postProcess(input, toUpperCase); }; -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports["default"] = camelCase; - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; +/***/ }), - counts[message] = count; +/***/ 8655: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "NIL", ({ + enumerable: true, + get: function () { + return _nil.default; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parse.default; + } +})); +Object.defineProperty(exports, "stringify", ({ + enumerable: true, + get: function () { + return _stringify.default; + } +})); +Object.defineProperty(exports, "v1", ({ + enumerable: true, + get: function () { + return _v.default; + } +})); +Object.defineProperty(exports, "v3", ({ + enumerable: true, + get: function () { + return _v2.default; + } +})); +Object.defineProperty(exports, "v4", ({ + enumerable: true, + get: function () { + return _v3.default; + } +})); +Object.defineProperty(exports, "v5", ({ + enumerable: true, + get: function () { + return _v4.default; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.default; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.default; } +})); - return mainError; -}; +var _v = _interopRequireDefault(__nccwpck_require__(2811)); + +var _v2 = _interopRequireDefault(__nccwpck_require__(6240)); + +var _v3 = _interopRequireDefault(__nccwpck_require__(2509)); + +var _v4 = _interopRequireDefault(__nccwpck_require__(9106)); + +var _nil = _interopRequireDefault(__nccwpck_require__(5389)); + +var _version = _interopRequireDefault(__nccwpck_require__(7660)); + +var _validate = _interopRequireDefault(__nccwpck_require__(9475)); + +var _stringify = _interopRequireDefault(__nccwpck_require__(4831)); + +var _parse = _interopRequireDefault(__nccwpck_require__(6698)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 9318: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7278: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const os = __nccwpck_require__(2037); -const tty = __nccwpck_require__(6224); -const hasFlag = __nccwpck_require__(1621); -const {env} = process; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function translateLevel(level) { - if (level === 0) { - return false; - } +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; + return _crypto.default.createHash('md5').update(bytes).digest(); } -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } +var _default = md5; +exports["default"] = _default; - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } +/***/ }), - if (hasFlag('color=256')) { - return 2; - } +/***/ 4196: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === 'dumb') { - return min; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - return 1; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports["default"] = _default; - return min; - } +/***/ }), - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +/***/ 5389: +/***/ ((__unused_webpack_module, exports) => { - if (env.COLORTERM === 'truecolor') { - return 3; - } - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports["default"] = _default; - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +/***/ }), - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } +/***/ 6698: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ('COLORTERM' in env) { - return 1; - } - return min; -} -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(9475)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; } -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; +var _default = parse; +exports["default"] = _default; + +/***/ }), + +/***/ 1830: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = /^(?:[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; +exports["default"] = _default; + /***/ }), -/***/ 4256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 534: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var punycode = __nccwpck_require__(5477); -var mappingTable = __nccwpck_require__(2020); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; -var PROCESSING_OPTIONS = { - TRANSITIONAL: 0, - NONTRANSITIONAL: 1 -}; +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); -function normalize(str) { // fix bug in v8 - return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function findStatus(val) { - var start = 0; - var end = mappingTable.length - 1; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - while (start <= end) { - var mid = Math.floor((start + end) / 2); +let poolPtr = rnds8Pool.length; - var target = mappingTable[mid]; - if (target[0][0] <= val && target[0][1] >= val) { - return target; - } else if (target[0][0] > val) { - end = mid - 1; - } else { - start = mid + 1; - } +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; } - return null; + return rnds8Pool.slice(poolPtr, poolPtr += 16); } -var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; +/***/ }), -function countSymbols(string) { - return string - // replace every surrogate pair with a BMP symbol - .replace(regexAstralSymbols, '_') - // then get the length - .length; -} +/***/ 2594: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function mapChars(domain_name, useSTD3, processing_option) { - var hasError = false; - var processed = ""; - var len = countSymbols(domain_name); - for (var i = 0; i < len; ++i) { - var codePoint = domain_name.codePointAt(i); - var status = findStatus(codePoint); - - switch (status[1]) { - case "disallowed": - hasError = true; - processed += String.fromCodePoint(codePoint); - break; - case "ignored": - break; - case "mapped": - processed += String.fromCodePoint.apply(String, status[2]); - break; - case "deviation": - if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { - processed += String.fromCodePoint.apply(String, status[2]); - } else { - processed += String.fromCodePoint(codePoint); - } - break; - case "valid": - processed += String.fromCodePoint(codePoint); - break; - case "disallowed_STD3_mapped": - if (useSTD3) { - hasError = true; - processed += String.fromCodePoint(codePoint); - } else { - processed += String.fromCodePoint.apply(String, status[2]); - } - break; - case "disallowed_STD3_valid": - if (useSTD3) { - hasError = true; - } - - processed += String.fromCodePoint(codePoint); - break; - } - } - - return { - string: processed, - error: hasError - }; -} - -var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; -function validateLabel(label, processing_option) { - if (label.substr(0, 4) === "xn--") { - label = punycode.toUnicode(label); - processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - var error = false; +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - if (normalize(label) !== label || - (label[3] === "-" && label[4] === "-") || - label[0] === "-" || label[label.length - 1] === "-" || - label.indexOf(".") !== -1 || - label.search(combiningMarksRegex) === 0) { - error = true; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var len = countSymbols(label); - for (var i = 0; i < len; ++i) { - var status = findStatus(label.codePointAt(i)); - if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || - (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && - status[1] !== "valid" && status[1] !== "deviation")) { - error = true; - break; - } +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); } - return { - label: label, - error: error - }; + return _crypto.default.createHash('sha1').update(bytes).digest(); } -function processing(domain_name, useSTD3, processing_option) { - var result = mapChars(domain_name, useSTD3, processing_option); - result.string = normalize(result.string); +var _default = sha1; +exports["default"] = _default; - var labels = result.string.split("."); - for (var i = 0; i < labels.length; ++i) { - try { - var validation = validateLabel(labels[i]); - labels[i] = validation.label; - result.error = result.error || validation.error; - } catch(e) { - result.error = true; - } - } +/***/ }), - return { - string: labels.join("."), - error: result.error - }; -} +/***/ 4831: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { - var result = processing(domain_name, useSTD3, processing_option); - var labels = result.string.split("."); - labels = labels.map(function(l) { - try { - return punycode.toASCII(l); - } catch(e) { - result.error = true; - return l; - } - }); - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; - } - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; - } - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +exports.unsafeStringify = unsafeStringify; - if (result.error) return null; - return labels.join("."); -}; +var _validate = _interopRequireDefault(__nccwpck_require__(9475)); -module.exports.toUnicode = function(domain_name, useSTD3) { - var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return { - domain: result.string, - error: result.error - }; -}; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; -module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + 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]]; +} -/***/ }), +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields -/***/ 4294: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } -module.exports = __nccwpck_require__(4219); + return uuid; +} +var _default = stringify; +exports["default"] = _default; /***/ }), -/***/ 4219: +/***/ 2811: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var net = __nccwpck_require__(1808); -var tls = __nccwpck_require__(4404); -var http = __nccwpck_require__(3685); -var https = __nccwpck_require__(5687); -var events = __nccwpck_require__(2361); -var assert = __nccwpck_require__(9491); -var util = __nccwpck_require__(3837); - - -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} +var _rng = _interopRequireDefault(__nccwpck_require__(534)); -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} +var _stringify = __nccwpck_require__(4831); -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; +let _clockseq; // Previous uuid creation time - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); - function onFree() { - self.emit('free', socket, options); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } - }); -}; + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port - } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); - } + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested - function onError(cause) { - connectReq.removeAllListeners(); - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } -}; -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; + msecs += 12219292800000; // `time_low` -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + b[i++] = clockseq & 0xff; // `node` -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; } -} else { - debug = function() {}; + + return buf || (0, _stringify.unsafeStringify)(b); } -exports.debug = debug; // for test +var _default = v1; +exports["default"] = _default; /***/ }), -/***/ 5030: -/***/ ((__unused_webpack_module, exports) => { - +/***/ 6240: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } +var _v = _interopRequireDefault(__nccwpck_require__(9545)); - return ""; -} +var _md = _interopRequireDefault(__nccwpck_require__(7278)); -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports["default"] = _default; /***/ }), -/***/ 5840: +/***/ 9545: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -15725,84 +14650,291 @@ exports.getUserAgent = getUserAgent; Object.defineProperty(exports, "__esModule", ({ value: true })); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; +exports.URL = exports.DNS = void 0; +exports["default"] = v35; + +var _stringify = __nccwpck_require__(4831); + +var _parse = _interopRequireDefault(__nccwpck_require__(6698)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} + +/***/ }), + +/***/ 2509: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true })); -Object.defineProperty(exports, "v3", ({ +exports["default"] = void 0; + +var _native = _interopRequireDefault(__nccwpck_require__(4196)); + +var _rng = _interopRequireDefault(__nccwpck_require__(534)); + +var _stringify = __nccwpck_require__(4831); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports["default"] = _default; + +/***/ }), + +/***/ 9106: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(9545)); + +var _sha = _interopRequireDefault(__nccwpck_require__(2594)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports["default"] = _default; + +/***/ }), + +/***/ 9475: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _regex = _interopRequireDefault(__nccwpck_require__(1830)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports["default"] = _default; + +/***/ }), + +/***/ 7660: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(9475)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports["default"] = _default; + +/***/ }), + +/***/ 9097: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "NIL", ({ enumerable: true, get: function () { - return _v2.default; + return _nil.default; } })); -Object.defineProperty(exports, "v4", ({ +Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { - return _v3.default; + return _parse.default; } })); -Object.defineProperty(exports, "v5", ({ +Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { - return _v4.default; + return _stringify.default; } })); -Object.defineProperty(exports, "NIL", ({ +Object.defineProperty(exports, "v1", ({ enumerable: true, get: function () { - return _nil.default; + return _v.default; } })); -Object.defineProperty(exports, "version", ({ +Object.defineProperty(exports, "v3", ({ enumerable: true, get: function () { - return _version.default; + return _v2.default; } })); -Object.defineProperty(exports, "validate", ({ +Object.defineProperty(exports, "v4", ({ enumerable: true, get: function () { - return _validate.default; + return _v3.default; } })); -Object.defineProperty(exports, "stringify", ({ +Object.defineProperty(exports, "v5", ({ enumerable: true, get: function () { - return _stringify.default; + return _v4.default; } })); -Object.defineProperty(exports, "parse", ({ +Object.defineProperty(exports, "validate", ({ enumerable: true, get: function () { - return _parse.default; + return _validate.default; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.default; } })); -var _v = _interopRequireDefault(__nccwpck_require__(8628)); +var _v = _interopRequireDefault(__nccwpck_require__(4071)); -var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); +var _v2 = _interopRequireDefault(__nccwpck_require__(5632)); -var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); +var _v3 = _interopRequireDefault(__nccwpck_require__(5573)); -var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); +var _v4 = _interopRequireDefault(__nccwpck_require__(557)); -var _nil = _interopRequireDefault(__nccwpck_require__(5332)); +var _nil = _interopRequireDefault(__nccwpck_require__(9268)); -var _version = _interopRequireDefault(__nccwpck_require__(1595)); +var _version = _interopRequireDefault(__nccwpck_require__(6422)); -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(2000)); -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = _interopRequireDefault(__nccwpck_require__(2008)); -var _parse = _interopRequireDefault(__nccwpck_require__(2746)); +var _parse = _interopRequireDefault(__nccwpck_require__(1813)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 4569: +/***/ 9048: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -15831,7 +14963,28 @@ exports["default"] = _default; /***/ }), -/***/ 5332: +/***/ 5696: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports["default"] = _default; + +/***/ }), + +/***/ 9268: /***/ ((__unused_webpack_module, exports) => { @@ -15845,7 +14998,7 @@ exports["default"] = _default; /***/ }), -/***/ 2746: +/***/ 1813: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -15855,7 +15008,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(2000)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -15896,7 +15049,7 @@ exports["default"] = _default; /***/ }), -/***/ 814: +/***/ 1467: /***/ ((__unused_webpack_module, exports) => { @@ -15910,7 +15063,7 @@ exports["default"] = _default; /***/ }), -/***/ 807: +/***/ 4103: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -15940,7 +15093,7 @@ function rng() { /***/ }), -/***/ 5274: +/***/ 86: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -15969,7 +15122,7 @@ exports["default"] = _default; /***/ }), -/***/ 8950: +/***/ 2008: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -15978,8 +15131,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; +exports.unsafeStringify = unsafeStringify; -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(2000)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -15990,13 +15144,17 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de const byteToHex = []; for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); + byteToHex.push((i + 0x100).toString(16).slice(1)); } -function stringify(arr, offset = 0) { +function unsafeStringify(arr, offset = 0) { // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const uuid = (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]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + 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]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) @@ -16014,7 +15172,7 @@ exports["default"] = _default; /***/ }), -/***/ 8628: +/***/ 4071: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16024,9 +15182,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(807)); +var _rng = _interopRequireDefault(__nccwpck_require__(4103)); -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = __nccwpck_require__(2008); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -16119,7 +15277,7 @@ function v1(options, buf, offset) { b[i + n] = node[n]; } - return buf || (0, _stringify.default)(b); + return buf || (0, _stringify.unsafeStringify)(b); } var _default = v1; @@ -16127,7 +15285,7 @@ exports["default"] = _default; /***/ }), -/***/ 6409: +/***/ 5632: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16137,9 +15295,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(5998)); +var _v = _interopRequireDefault(__nccwpck_require__(7329)); -var _md = _interopRequireDefault(__nccwpck_require__(4569)); +var _md = _interopRequireDefault(__nccwpck_require__(9048)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -16149,7 +15307,7 @@ exports["default"] = _default; /***/ }), -/***/ 5998: +/***/ 7329: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16157,12 +15315,12 @@ exports["default"] = _default; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = _default; exports.URL = exports.DNS = void 0; +exports["default"] = v35; -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _stringify = __nccwpck_require__(2008); -var _parse = _interopRequireDefault(__nccwpck_require__(2746)); +var _parse = _interopRequireDefault(__nccwpck_require__(1813)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -16183,8 +15341,10 @@ exports.DNS = DNS; const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; exports.URL = URL; -function _default(name, version, hashfunc) { +function v35(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { + var _namespace; + if (typeof value === 'string') { value = stringToBytes(value); } @@ -16193,7 +15353,7 @@ function _default(name, version, hashfunc) { namespace = (0, _parse.default)(namespace); } - if (namespace.length !== 16) { + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); } // Compute hash of namespace and value, Per 4.3 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = @@ -16217,7 +15377,7 @@ function _default(name, version, hashfunc) { return buf; } - return (0, _stringify.default)(bytes); + return (0, _stringify.unsafeStringify)(bytes); } // Function#name is not settable on some platforms (#270) @@ -16233,7 +15393,7 @@ function _default(name, version, hashfunc) { /***/ }), -/***/ 5122: +/***/ 5573: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16243,13 +15403,19 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(807)); +var _native = _interopRequireDefault(__nccwpck_require__(5696)); -var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); +var _rng = _interopRequireDefault(__nccwpck_require__(4103)); + +var _stringify = __nccwpck_require__(2008); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + options = options || {}; const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` @@ -16268,7 +15434,7 @@ function v4(options, buf, offset) { return buf; } - return (0, _stringify.default)(rnds); + return (0, _stringify.unsafeStringify)(rnds); } var _default = v4; @@ -16276,7 +15442,7 @@ exports["default"] = _default; /***/ }), -/***/ 9120: +/***/ 557: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16286,9 +15452,9 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(5998)); +var _v = _interopRequireDefault(__nccwpck_require__(7329)); -var _sha = _interopRequireDefault(__nccwpck_require__(5274)); +var _sha = _interopRequireDefault(__nccwpck_require__(86)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -16298,7 +15464,7 @@ exports["default"] = _default; /***/ }), -/***/ 6900: +/***/ 2000: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16308,7 +15474,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(814)); +var _regex = _interopRequireDefault(__nccwpck_require__(1467)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -16321,7 +15487,7 @@ exports["default"] = _default; /***/ }), -/***/ 1595: +/***/ 6422: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { @@ -16331,7 +15497,7 @@ Object.defineProperty(exports, "__esModule", ({ })); exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6900)); +var _validate = _interopRequireDefault(__nccwpck_require__(2000)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -16340,7 +15506,7 @@ function version(uuid) { throw TypeError('Invalid UUID'); } - return parseInt(uuid.substr(14, 1), 16); + return parseInt(uuid.slice(14, 15), 16); } var _default = version; @@ -16348,31199 +15514,32813 @@ exports["default"] = _default; /***/ }), -/***/ 4886: -/***/ ((module) => { - +/***/ 7426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ -var conversions = {}; -module.exports = conversions; +/** + * Module exports. + */ -function sign(x) { - return x < 0 ? -1 : 1; -} +module.exports = __nccwpck_require__(3765) -function evenRound(x) { - // Round x to the nearest integer, choosing the even integer if it lies halfway between two. - if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) - return Math.floor(x); - } else { - return Math.round(x); - } -} -function createNumberConversion(bitLength, typeOpts) { - if (!typeOpts.unsigned) { - --bitLength; - } - const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); - const upperBound = Math.pow(2, bitLength) - 1; +/***/ }), - const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); - const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); +/***/ 3583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return function(V, opts) { - if (!opts) opts = {}; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - let x = +V; - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite number"); - } - x = sign(x) * Math.floor(Math.abs(x)); - if (x < lowerBound || x > upperBound) { - throw new TypeError("Argument is not in byte range"); - } +/** + * Module dependencies. + * @private + */ - return x; - } +var db = __nccwpck_require__(7426) +var extname = (__nccwpck_require__(1017).extname) - if (!isNaN(x) && opts.clamp) { - x = evenRound(x); +/** + * Module variables. + * @private + */ - if (x < lowerBound) x = lowerBound; - if (x > upperBound) x = upperBound; - return x; - } +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i - if (!Number.isFinite(x) || x === 0) { - return 0; - } +/** + * Module exports. + * @public + */ - x = sign(x) * Math.floor(Math.abs(x)); - x = x % moduloVal; +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) - if (!typeOpts.unsigned && x >= moduloBound) { - return x - moduloVal; - } else if (typeOpts.unsigned) { - if (x < 0) { - x += moduloVal; - } else if (x === -0) { // don't return negative zero - return 0; - } - } +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) - return x; - } -} +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -conversions["void"] = function () { - return undefined; -}; +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } -conversions["boolean"] = function (val) { - return !!val; -}; + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] -conversions["byte"] = createNumberConversion(8, { unsigned: false }); -conversions["octet"] = createNumberConversion(8, { unsigned: true }); + if (mime && mime.charset) { + return mime.charset + } -conversions["short"] = createNumberConversion(16, { unsigned: false }); -conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } -conversions["long"] = createNumberConversion(32, { unsigned: false }); -conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + return false +} -conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); -conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); - -conversions["double"] = function (V) { - const x = +V; +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite floating-point value"); - } +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } - return x; -}; + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str -conversions["unrestricted double"] = function (V) { - const x = +V; + if (!mime) { + return false + } - if (isNaN(x)) { - throw new TypeError("Argument is NaN"); - } + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } - return x; -}; + return mime +} -// not quite valid, but good enough for JS -conversions["float"] = conversions["double"]; -conversions["unrestricted float"] = conversions["unrestricted double"]; +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -conversions["DOMString"] = function (V, opts) { - if (!opts) opts = {}; +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) - return String(V); -}; + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] -conversions["ByteString"] = function (V, opts) { - const x = String(V); - let c = undefined; - for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { - if (c > 255) { - throw new TypeError("Argument is not a valid bytestring"); - } - } + if (!exts || !exts.length) { + return false + } - return x; -}; + return exts[0] +} -conversions["USVString"] = function (V) { - const S = String(V); - const n = S.length; - const U = []; - for (let i = 0; i < n; ++i) { - const c = S.charCodeAt(i); - if (c < 0xD800 || c > 0xDFFF) { - U.push(String.fromCodePoint(c)); - } else if (0xDC00 <= c && c <= 0xDFFF) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - if (i === n - 1) { - U.push(String.fromCodePoint(0xFFFD)); - } else { - const d = S.charCodeAt(i + 1); - if (0xDC00 <= d && d <= 0xDFFF) { - const a = c & 0x3FF; - const b = d & 0x3FF; - U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); - ++i; - } else { - U.push(String.fromCodePoint(0xFFFD)); - } - } - } - } +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ - return U.join(''); -}; +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } -conversions["Date"] = function (V, opts) { - if (!(V instanceof Date)) { - throw new TypeError("Argument is not a Date object"); - } - if (isNaN(V)) { - return undefined; - } + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) - return V; -}; + if (!extension) { + return false + } -conversions["RegExp"] = function (V, opts) { - if (!(V instanceof RegExp)) { - V = new RegExp(V); - } + return exports.types[extension] || false +} - return V; -}; +/** + * Populate the extensions and types maps. + * @private + */ +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] -/***/ }), + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions -/***/ 7537: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!exts || !exts.length) { + return + } + // mime -> extensions + extensions[type] = exts -const usm = __nccwpck_require__(2158); + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] -exports.implementation = class URLImpl { - constructor(constructorArgs) { - const url = constructorArgs[0]; - const base = constructorArgs[1]; + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) - let parsedBase = null; - if (base !== undefined) { - parsedBase = usm.basicURLParse(base); - if (parsedBase === "failure") { - throw new TypeError("Invalid base URL"); + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } } - } - const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); + // set the extension -> mime + types[extension] = type } + }) +} - this._url = parsedURL; - // TODO: query stuff - } +/***/ }), - get href() { - return usm.serializeURL(this._url); - } +/***/ 900: +/***/ ((module) => { - set href(v) { - const parsedURL = usm.basicURLParse(v); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } +/** + * Helpers. + */ - this._url = parsedURL; - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; - get origin() { - return usm.serializeURLOrigin(this._url); - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - get protocol() { - return this._url.scheme + ":"; +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - set protocol(v) { - usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); - } +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - get username() { - return this._url.username; +function parse(str) { + str = String(str); + if (str.length > 100) { + return; } - - set username(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - usm.setTheUsername(this._url, v); + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; } - - get password() { - return this._url.password; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; } +} - set password(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - usm.setThePassword(this._url, v); +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; } - - get host() { - const url = this._url; - - if (url.host === null) { - return ""; - } - - if (url.port === null) { - return usm.serializeHost(url.host); - } - - return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; } - - set host(v) { - if (this._url.cannotBeABaseURL) { - return; - } - - usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; } - - get hostname() { - if (this._url.host === null) { - return ""; - } - - return usm.serializeHost(this._url.host); + if (msAbs >= s) { + return Math.round(ms / s) + 's'; } + return ms + 'ms'; +} - set hostname(v) { - if (this._url.cannotBeABaseURL) { - return; - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); } - - get port() { - if (this._url.port === null) { - return ""; - } - - return usm.serializeInteger(this._url.port); + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); } - - set port(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } - - if (v === "") { - this._url.port = null; - } else { - usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); - } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); } + return ms + ' ms'; +} - get pathname() { - if (this._url.cannotBeABaseURL) { - return this._url.path[0]; - } +/** + * Pluralization helper. + */ - if (this._url.path.length === 0) { - return ""; - } +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} - return "/" + this._url.path.join("/"); - } - set pathname(v) { - if (this._url.cannotBeABaseURL) { - return; - } +/***/ }), - this._url.path = []; - usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); - } +/***/ 7760: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get search() { - if (this._url.query === null || this._url.query === "") { - return ""; - } +/*! node-domexception. MIT License. Jimmy Wärting */ - return "?" + this._url.query; +if (!globalThis.DOMException) { + try { + const { MessageChannel } = __nccwpck_require__(1267), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) } +} - set search(v) { - // TODO: query stuff +module.exports = globalThis.DOMException - const url = this._url; - if (v === "") { - url.query = null; - return; - } +/***/ }), - const input = v[0] === "?" ? v.substring(1) : v; - url.query = ""; - usm.basicURLParse(input, { url, stateOverride: "query" }); - } +/***/ 467: +/***/ ((module, exports, __nccwpck_require__) => { - get hash() { - if (this._url.fragment === null || this._url.fragment === "") { - return ""; - } - return "#" + this._url.fragment; - } - set hash(v) { - if (v === "") { - this._url.fragment = null; - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - const input = v[0] === "#" ? v.substring(1) : v; - this._url.fragment = ""; - usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); - } +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - toJSON() { - return this.href; - } -}; +var Stream = _interopDefault(__nccwpck_require__(2781)); +var http = _interopDefault(__nccwpck_require__(3685)); +var Url = _interopDefault(__nccwpck_require__(7310)); +var whatwgUrl = _interopDefault(__nccwpck_require__(8665)); +var https = _interopDefault(__nccwpck_require__(5687)); +var zlib = _interopDefault(__nccwpck_require__(9796)); +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js -/***/ }), +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; -/***/ 3394: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); +class Blob { + constructor() { + this[TYPE] = ''; + const blobParts = arguments[0]; + const options = arguments[1]; -const conversions = __nccwpck_require__(4886); -const utils = __nccwpck_require__(3185); -const Impl = __nccwpck_require__(7537); + const buffers = []; + let size = 0; -const impl = utils.implSymbol; + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } -function URL(url) { - if (!this || this[impl] || !(this instanceof URL)) { - throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); - } - if (arguments.length < 1) { - throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); - } - const args = []; - for (let i = 0; i < arguments.length && i < 2; ++i) { - args[i] = arguments[i]; - } - args[0] = conversions["USVString"](args[0]); - if (args[1] !== undefined) { - args[1] = conversions["USVString"](args[1]); - } + this[BUFFER] = Buffer.concat(buffers); - module.exports.setup(this, args); + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } -URL.prototype.toJSON = function toJSON() { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); - } - const args = []; - for (let i = 0; i < arguments.length && i < 0; ++i) { - args[i] = arguments[i]; - } - return this[impl].toJSON.apply(this[impl], args); -}; -Object.defineProperty(URL.prototype, "href", { - get() { - return this[impl].href; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].href = V; - }, - enumerable: true, - configurable: true +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } }); -URL.prototype.toString = function () { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; } - return this.href; -}; -Object.defineProperty(URL.prototype, "origin", { - get() { - return this[impl].origin; - }, - enumerable: true, - configurable: true -}); + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} -Object.defineProperty(URL.prototype, "protocol", { - get() { - return this[impl].protocol; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].protocol = V; - }, - enumerable: true, - configurable: true -}); +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; -Object.defineProperty(URL.prototype, "username", { - get() { - return this[impl].username; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].username = V; - }, - enumerable: true, - configurable: true -}); +let convert; +try { + convert = (__nccwpck_require__(2877).convert); +} catch (e) {} -Object.defineProperty(URL.prototype, "password", { - get() { - return this[impl].password; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].password = V; - }, - enumerable: true, - configurable: true -}); +const INTERNALS = Symbol('Body internals'); -Object.defineProperty(URL.prototype, "host", { - get() { - return this[impl].host; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].host = V; - }, - enumerable: true, - configurable: true -}); +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; -Object.defineProperty(URL.prototype, "hostname", { - get() { - return this[impl].hostname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hostname = V; - }, - enumerable: true, - configurable: true -}); +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; -Object.defineProperty(URL.prototype, "port", { - get() { - return this[impl].port; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].port = V; - }, - enumerable: true, - configurable: true -}); + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; -Object.defineProperty(URL.prototype, "pathname", { - get() { - return this[impl].pathname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].pathname = V; - }, - enumerable: true, - configurable: true -}); + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; -Object.defineProperty(URL.prototype, "search", { - get() { - return this[impl].search; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].search = V; - }, - enumerable: true, - configurable: true -}); + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; -Object.defineProperty(URL.prototype, "hash", { - get() { - return this[impl].hash; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hash = V; - }, - enumerable: true, - configurable: true -}); + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, -module.exports = { - is(obj) { - return !!obj && obj[impl] instanceof Impl.implementation; - }, - create(constructorArgs, privateData) { - let obj = Object.create(URL.prototype); - this.setup(obj, constructorArgs, privateData); - return obj; - }, - setup(obj, constructorArgs, privateData) { - if (!privateData) privateData = {}; - privateData.wrapper = obj; + get bodyUsed() { + return this[INTERNALS].disturbed; + }, - obj[impl] = new Impl.implementation(constructorArgs, privateData); - obj[impl][utils.wrapperSymbol] = obj; - }, - interface: URL, - expose: { - Window: { URL: URL }, - Worker: { URL: URL } - } + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } }; +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; -/***/ }), +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; -/***/ 8665: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + this[INTERNALS].disturbed = true; + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } -exports.URL = __nccwpck_require__(3394)["interface"]; -exports.serializeURL = __nccwpck_require__(2158).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(2158).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(2158).basicURLParse; -exports.setTheUsername = __nccwpck_require__(2158).setTheUsername; -exports.setThePassword = __nccwpck_require__(2158).setThePassword; -exports.serializeHost = __nccwpck_require__(2158).serializeHost; -exports.serializeInteger = __nccwpck_require__(2158).serializeInteger; -exports.parseURL = __nccwpck_require__(2158).parseURL; + let body = this.body; + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } -/***/ }), + // body is blob + if (isBlob(body)) { + body = body.stream(); + } -/***/ 2158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } - -const punycode = __nccwpck_require__(5477); -const tr46 = __nccwpck_require__(4256); - -const specialSchemes = { - ftp: 21, - file: null, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443 -}; - -const failure = Symbol("failure"); - -function countSymbols(str) { - return punycode.ucs2.decode(str).length; -} - -function at(input, idx) { - const c = input[idx]; - return isNaN(c) ? undefined : String.fromCodePoint(c); -} - -function isASCIIDigit(c) { - return c >= 0x30 && c <= 0x39; -} - -function isASCIIAlpha(c) { - return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); -} - -function isASCIIAlphanumeric(c) { - return isASCIIAlpha(c) || isASCIIDigit(c); -} - -function isASCIIHex(c) { - return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); -} - -function isSingleDot(buffer) { - return buffer === "." || buffer.toLowerCase() === "%2e"; -} - -function isDoubleDot(buffer) { - buffer = buffer.toLowerCase(); - return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; -} - -function isWindowsDriveLetterCodePoints(cp1, cp2) { - return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); -} - -function isWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); -} - -function isNormalizedWindowsDriveLetterString(string) { - return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; -} - -function containsForbiddenHostCodePoint(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function containsForbiddenHostCodePointExcludingPercent(string) { - return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; -} - -function isSpecialScheme(scheme) { - return specialSchemes[scheme] !== undefined; -} - -function isSpecial(url) { - return isSpecialScheme(url.scheme); -} - -function defaultPort(scheme) { - return specialSchemes[scheme]; -} - -function percentEncode(c) { - let hex = c.toString(16).toUpperCase(); - if (hex.length === 1) { - hex = "0" + hex; - } - - return "%" + hex; -} - -function utf8PercentEncode(c) { - const buf = new Buffer(c); - - let str = ""; - - for (let i = 0; i < buf.length; ++i) { - str += percentEncode(buf[i]); - } - - return str; -} - -function utf8PercentDecode(str) { - const input = new Buffer(str); - const output = []; - for (let i = 0; i < input.length; ++i) { - if (input[i] !== 37) { - output.push(input[i]); - } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { - output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); - i += 2; - } else { - output.push(input[i]); - } - } - return new Buffer(output).toString(); -} - -function isC0ControlPercentEncode(c) { - return c <= 0x1F || c > 0x7E; -} - -const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); -function isPathPercentEncode(c) { - return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); -} - -const extraUserinfoPercentEncodeSet = - new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); -function isUserinfoPercentEncode(c) { - return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); -} - -function percentEncodeChar(c, encodeSetPredicate) { - const cStr = String.fromCodePoint(c); - - if (encodeSetPredicate(c)) { - return utf8PercentEncode(cStr); - } - - return cStr; -} - -function parseIPv4Number(input) { - let R = 10; - - if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { - input = input.substring(2); - R = 16; - } else if (input.length >= 2 && input.charAt(0) === "0") { - input = input.substring(1); - R = 8; - } - - if (input === "") { - return 0; - } - - const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); - if (regex.test(input)) { - return failure; - } - - return parseInt(input, R); -} - -function parseIPv4(input) { - const parts = input.split("."); - if (parts[parts.length - 1] === "") { - if (parts.length > 1) { - parts.pop(); - } - } - - if (parts.length > 4) { - return input; - } - - const numbers = []; - for (const part of parts) { - if (part === "") { - return input; - } - const n = parseIPv4Number(part); - if (n === failure) { - return input; - } - - numbers.push(n); - } - - for (let i = 0; i < numbers.length - 1; ++i) { - if (numbers[i] > 255) { - return failure; - } - } - if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { - return failure; - } - - let ipv4 = numbers.pop(); - let counter = 0; - - for (const n of numbers) { - ipv4 += n * Math.pow(256, 3 - counter); - ++counter; - } - - return ipv4; -} - -function serializeIPv4(address) { - let output = ""; - let n = address; - - for (let i = 1; i <= 4; ++i) { - output = String(n % 256) + output; - if (i !== 4) { - output = "." + output; - } - n = Math.floor(n / 256); - } - - return output; -} - -function parseIPv6(input) { - const address = [0, 0, 0, 0, 0, 0, 0, 0]; - let pieceIndex = 0; - let compress = null; - let pointer = 0; - - input = punycode.ucs2.decode(input); - - if (input[pointer] === 58) { - if (input[pointer + 1] !== 58) { - return failure; - } - - pointer += 2; - ++pieceIndex; - compress = pieceIndex; - } - - while (pointer < input.length) { - if (pieceIndex === 8) { - return failure; - } - - if (input[pointer] === 58) { - if (compress !== null) { - return failure; - } - ++pointer; - ++pieceIndex; - compress = pieceIndex; - continue; - } - - let value = 0; - let length = 0; - - while (length < 4 && isASCIIHex(input[pointer])) { - value = value * 0x10 + parseInt(at(input, pointer), 16); - ++pointer; - ++length; - } - - if (input[pointer] === 46) { - if (length === 0) { - return failure; - } - - pointer -= length; - - if (pieceIndex > 6) { - return failure; - } - - let numbersSeen = 0; - - while (input[pointer] !== undefined) { - let ipv4Piece = null; - - if (numbersSeen > 0) { - if (input[pointer] === 46 && numbersSeen < 4) { - ++pointer; - } else { - return failure; - } - } - - if (!isASCIIDigit(input[pointer])) { - return failure; - } - - while (isASCIIDigit(input[pointer])) { - const number = parseInt(at(input, pointer)); - if (ipv4Piece === null) { - ipv4Piece = number; - } else if (ipv4Piece === 0) { - return failure; - } else { - ipv4Piece = ipv4Piece * 10 + number; - } - if (ipv4Piece > 255) { - return failure; - } - ++pointer; - } - - address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; - - ++numbersSeen; - - if (numbersSeen === 2 || numbersSeen === 4) { - ++pieceIndex; - } - } - - if (numbersSeen !== 4) { - return failure; - } - - break; - } else if (input[pointer] === 58) { - ++pointer; - if (input[pointer] === undefined) { - return failure; - } - } else if (input[pointer] !== undefined) { - return failure; - } - - address[pieceIndex] = value; - ++pieceIndex; - } - - if (compress !== null) { - let swaps = pieceIndex - compress; - pieceIndex = 7; - while (pieceIndex !== 0 && swaps > 0) { - const temp = address[compress + swaps - 1]; - address[compress + swaps - 1] = address[pieceIndex]; - address[pieceIndex] = temp; - --pieceIndex; - --swaps; - } - } else if (compress === null && pieceIndex !== 8) { - return failure; - } - - return address; -} - -function serializeIPv6(address) { - let output = ""; - const seqResult = findLongestZeroSequence(address); - const compress = seqResult.idx; - let ignore0 = false; - - for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { - if (ignore0 && address[pieceIndex] === 0) { - continue; - } else if (ignore0) { - ignore0 = false; - } - - if (compress === pieceIndex) { - const separator = pieceIndex === 0 ? "::" : ":"; - output += separator; - ignore0 = true; - continue; - } - - output += address[pieceIndex].toString(16); - - if (pieceIndex !== 7) { - output += ":"; - } - } - - return output; -} - -function parseHost(input, isSpecialArg) { - if (input[0] === "[") { - if (input[input.length - 1] !== "]") { - return failure; - } - - return parseIPv6(input.substring(1, input.length - 1)); - } - - if (!isSpecialArg) { - return parseOpaqueHost(input); - } - - const domain = utf8PercentDecode(input); - const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); - if (asciiDomain === null) { - return failure; - } - - if (containsForbiddenHostCodePoint(asciiDomain)) { - return failure; - } - - const ipv4Host = parseIPv4(asciiDomain); - if (typeof ipv4Host === "number" || ipv4Host === failure) { - return ipv4Host; - } - - return asciiDomain; -} - -function parseOpaqueHost(input) { - if (containsForbiddenHostCodePointExcludingPercent(input)) { - return failure; - } - - let output = ""; - const decoded = punycode.ucs2.decode(input); - for (let i = 0; i < decoded.length; ++i) { - output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); - } - return output; -} - -function findLongestZeroSequence(arr) { - let maxIdx = null; - let maxLen = 1; // only find elements > 1 - let currStart = null; - let currLen = 0; - - for (let i = 0; i < arr.length; ++i) { - if (arr[i] !== 0) { - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - currStart = null; - currLen = 0; - } else { - if (currStart === null) { - currStart = i; - } - ++currLen; - } - } - - // if trailing zeros - if (currLen > maxLen) { - maxIdx = currStart; - maxLen = currLen; - } - - return { - idx: maxIdx, - len: maxLen - }; -} - -function serializeHost(host) { - if (typeof host === "number") { - return serializeIPv4(host); - } - - // IPv6 serializer - if (host instanceof Array) { - return "[" + serializeIPv6(host) + "]"; - } - - return host; -} - -function trimControlChars(url) { - return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); -} - -function trimTabAndNewline(url) { - return url.replace(/\u0009|\u000A|\u000D/g, ""); -} - -function shortenPath(url) { - const path = url.path; - if (path.length === 0) { - return; - } - if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { - return; - } - - path.pop(); -} - -function includesCredentials(url) { - return url.username !== "" || url.password !== ""; -} - -function cannotHaveAUsernamePasswordPort(url) { - return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; -} - -function isNormalizedWindowsDriveLetter(string) { - return /^[A-Za-z]:$/.test(string); -} - -function URLStateMachine(input, base, encodingOverride, url, stateOverride) { - this.pointer = 0; - this.input = input; - this.base = base || null; - this.encodingOverride = encodingOverride || "utf-8"; - this.stateOverride = stateOverride; - this.url = url; - this.failure = false; - this.parseError = false; - - if (!this.url) { - this.url = { - scheme: "", - username: "", - password: "", - host: null, - port: null, - path: [], - query: null, - fragment: null, - - cannotBeABaseURL: false - }; - - const res = trimControlChars(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - } - - const res = trimTabAndNewline(this.input); - if (res !== this.input) { - this.parseError = true; - } - this.input = res; - - this.state = stateOverride || "scheme start"; - - this.buffer = ""; - this.atFlag = false; - this.arrFlag = false; - this.passwordTokenSeenFlag = false; - - this.input = punycode.ucs2.decode(this.input); - - for (; this.pointer <= this.input.length; ++this.pointer) { - const c = this.input[this.pointer]; - const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); - - // exec state machine - const ret = this["parse " + this.state](c, cStr); - if (!ret) { - break; // terminate algorithm - } else if (ret === failure) { - this.failure = true; - break; - } - } -} - -URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { - if (isASCIIAlpha(c)) { - this.buffer += cStr.toLowerCase(); - this.state = "scheme"; - } else if (!this.stateOverride) { - this.state = "no scheme"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { - if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { - this.buffer += cStr.toLowerCase(); - } else if (c === 58) { - if (this.stateOverride) { - if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { - return false; - } - - if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { - return false; - } - - if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { - return false; - } - - if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { - return false; - } - } - this.url.scheme = this.buffer; - this.buffer = ""; - if (this.stateOverride) { - return false; - } - if (this.url.scheme === "file") { - if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { - this.parseError = true; - } - this.state = "file"; - } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { - this.state = "special relative or authority"; - } else if (isSpecial(this.url)) { - this.state = "special authority slashes"; - } else if (this.input[this.pointer + 1] === 47) { - this.state = "path or authority"; - ++this.pointer; - } else { - this.url.cannotBeABaseURL = true; - this.url.path.push(""); - this.state = "cannot-be-a-base-URL path"; - } - } else if (!this.stateOverride) { - this.buffer = ""; - this.state = "no scheme"; - this.pointer = -1; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { - if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { - return failure; - } else if (this.base.cannotBeABaseURL && c === 35) { - this.url.scheme = this.base.scheme; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.url.cannotBeABaseURL = true; - this.state = "fragment"; - } else if (this.base.scheme === "file") { - this.state = "file"; - --this.pointer; - } else { - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "relative"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { - if (c === 47) { - this.state = "authority"; - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative"] = function parseRelative(c) { - this.url.scheme = this.base.scheme; - if (isNaN(c)) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 47) { - this.state = "relative slash"; - } else if (c === 63) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else if (isSpecial(this.url) && c === 92) { - this.parseError = true; - this.state = "relative slash"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.url.path = this.base.path.slice(0, this.base.path.length - 1); - - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { - if (isSpecial(this.url) && (c === 47 || c === 92)) { - if (c === 92) { - this.parseError = true; - } - this.state = "special authority ignore slashes"; - } else if (c === 47) { - this.state = "authority"; - } else { - this.url.username = this.base.username; - this.url.password = this.base.password; - this.url.host = this.base.host; - this.url.port = this.base.port; - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { - if (c === 47 && this.input[this.pointer + 1] === 47) { - this.state = "special authority ignore slashes"; - ++this.pointer; - } else { - this.parseError = true; - this.state = "special authority ignore slashes"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { - if (c !== 47 && c !== 92) { - this.state = "authority"; - --this.pointer; - } else { - this.parseError = true; - } - - return true; -}; - -URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { - if (c === 64) { - this.parseError = true; - if (this.atFlag) { - this.buffer = "%40" + this.buffer; - } - this.atFlag = true; - - // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars - const len = countSymbols(this.buffer); - for (let pointer = 0; pointer < len; ++pointer) { - const codePoint = this.buffer.codePointAt(pointer); - - if (codePoint === 58 && !this.passwordTokenSeenFlag) { - this.passwordTokenSeenFlag = true; - continue; - } - const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); - if (this.passwordTokenSeenFlag) { - this.url.password += encodedCodePoints; - } else { - this.url.username += encodedCodePoints; - } - } - this.buffer = ""; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - if (this.atFlag && this.buffer === "") { - this.parseError = true; - return failure; - } - this.pointer -= countSymbols(this.buffer) + 1; - this.buffer = ""; - this.state = "host"; - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse hostname"] = -URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { - if (this.stateOverride && this.url.scheme === "file") { - --this.pointer; - this.state = "file host"; - } else if (c === 58 && !this.arrFlag) { - if (this.buffer === "") { - this.parseError = true; - return failure; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "port"; - if (this.stateOverride === "hostname") { - return false; - } - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92)) { - --this.pointer; - if (isSpecial(this.url) && this.buffer === "") { - this.parseError = true; - return failure; - } else if (this.stateOverride && this.buffer === "" && - (includesCredentials(this.url) || this.url.port !== null)) { - this.parseError = true; - return false; - } - - const host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - - this.url.host = host; - this.buffer = ""; - this.state = "path start"; - if (this.stateOverride) { - return false; - } - } else { - if (c === 91) { - this.arrFlag = true; - } else if (c === 93) { - this.arrFlag = false; - } - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { - if (isASCIIDigit(c)) { - this.buffer += cStr; - } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || - (isSpecial(this.url) && c === 92) || - this.stateOverride) { - if (this.buffer !== "") { - const port = parseInt(this.buffer); - if (port > Math.pow(2, 16) - 1) { - this.parseError = true; - return failure; - } - this.url.port = port === defaultPort(this.url.scheme) ? null : port; - this.buffer = ""; - } - if (this.stateOverride) { - return false; - } - this.state = "path start"; - --this.pointer; - } else { - this.parseError = true; - return failure; - } - - return true; -}; - -const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); - -URLStateMachine.prototype["parse file"] = function parseFile(c) { - this.url.scheme = "file"; - - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file slash"; - } else if (this.base !== null && this.base.scheme === "file") { - if (isNaN(c)) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - } else if (c === 63) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - this.url.query = this.base.query; - this.url.fragment = ""; - this.state = "fragment"; - } else { - if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points - !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || - (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points - !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { - this.url.host = this.base.host; - this.url.path = this.base.path.slice(); - shortenPath(this.url); - } else { - this.parseError = true; - } - - this.state = "path"; - --this.pointer; - } - } else { - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { - if (c === 47 || c === 92) { - if (c === 92) { - this.parseError = true; - } - this.state = "file host"; - } else { - if (this.base !== null && this.base.scheme === "file") { - if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { - this.url.path.push(this.base.path[0]); - } else { - this.url.host = this.base.host; - } - } - this.state = "path"; - --this.pointer; - } - - return true; -}; - -URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { - if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { - --this.pointer; - if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { - this.parseError = true; - this.state = "path"; - } else if (this.buffer === "") { - this.url.host = ""; - if (this.stateOverride) { - return false; - } - this.state = "path start"; - } else { - let host = parseHost(this.buffer, isSpecial(this.url)); - if (host === failure) { - return failure; - } - if (host === "localhost") { - host = ""; - } - this.url.host = host; - - if (this.stateOverride) { - return false; - } - - this.buffer = ""; - this.state = "path start"; - } - } else { - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { - if (isSpecial(this.url)) { - if (c === 92) { - this.parseError = true; - } - this.state = "path"; - - if (c !== 47 && c !== 92) { - --this.pointer; - } - } else if (!this.stateOverride && c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (!this.stateOverride && c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else if (c !== undefined) { - this.state = "path"; - if (c !== 47) { - --this.pointer; - } - } - - return true; -}; - -URLStateMachine.prototype["parse path"] = function parsePath(c) { - if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || - (!this.stateOverride && (c === 63 || c === 35))) { - if (isSpecial(this.url) && c === 92) { - this.parseError = true; - } - - if (isDoubleDot(this.buffer)) { - shortenPath(this.url); - if (c !== 47 && !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } - } else if (isSingleDot(this.buffer) && c !== 47 && - !(isSpecial(this.url) && c === 92)) { - this.url.path.push(""); - } else if (!isSingleDot(this.buffer)) { - if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { - if (this.url.host !== "" && this.url.host !== null) { - this.parseError = true; - this.url.host = ""; - } - this.buffer = this.buffer[0] + ":"; - } - this.url.path.push(this.buffer); - } - this.buffer = ""; - if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { - while (this.url.path.length > 1 && this.url.path[0] === "") { - this.parseError = true; - this.url.path.shift(); - } - } - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += percentEncodeChar(c, isPathPercentEncode); - } - - return true; -}; - -URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { - if (c === 63) { - this.url.query = ""; - this.state = "query"; - } else if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } else { - // TODO: Add: not a URL code point - if (!isNaN(c) && c !== 37) { - this.parseError = true; - } - - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - if (!isNaN(c)) { - this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); - } - } - - return true; -}; - -URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { - if (isNaN(c) || (!this.stateOverride && c === 35)) { - if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { - this.encodingOverride = "utf-8"; - } - - const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead - for (let i = 0; i < buffer.length; ++i) { - if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || - buffer[i] === 0x3C || buffer[i] === 0x3E) { - this.url.query += percentEncode(buffer[i]); - } else { - this.url.query += String.fromCodePoint(buffer[i]); - } - } - - this.buffer = ""; - if (c === 35) { - this.url.fragment = ""; - this.state = "fragment"; - } - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.buffer += cStr; - } - - return true; -}; - -URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { - if (isNaN(c)) { // do nothing - } else if (c === 0x0) { - this.parseError = true; - } else { - // TODO: If c is not a URL code point and not "%", parse error. - if (c === 37 && - (!isASCIIHex(this.input[this.pointer + 1]) || - !isASCIIHex(this.input[this.pointer + 2]))) { - this.parseError = true; - } - - this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); - } - - return true; -}; - -function serializeURL(url, excludeFragment) { - let output = url.scheme + ":"; - if (url.host !== null) { - output += "//"; - - if (url.username !== "" || url.password !== "") { - output += url.username; - if (url.password !== "") { - output += ":" + url.password; - } - output += "@"; - } - - output += serializeHost(url.host); - - if (url.port !== null) { - output += ":" + url.port; - } - } else if (url.host === null && url.scheme === "file") { - output += "//"; - } - - if (url.cannotBeABaseURL) { - output += url.path[0]; - } else { - for (const string of url.path) { - output += "/" + string; - } - } - - if (url.query !== null) { - output += "?" + url.query; - } - - if (!excludeFragment && url.fragment !== null) { - output += "#" + url.fragment; - } - - return output; -} - -function serializeOrigin(tuple) { - let result = tuple.scheme + "://"; - result += serializeHost(tuple.host); - - if (tuple.port !== null) { - result += ":" + tuple.port; - } - - return result; -} - -module.exports.serializeURL = serializeURL; - -module.exports.serializeURLOrigin = function (url) { - // https://url.spec.whatwg.org/#concept-url-origin - switch (url.scheme) { - case "blob": - try { - return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); - } catch (e) { - // serializing an opaque origin returns "null" - return "null"; - } - case "ftp": - case "gopher": - case "http": - case "https": - case "ws": - case "wss": - return serializeOrigin({ - scheme: url.scheme, - host: url.host, - port: url.port - }); - case "file": - // spec says "exercise to the reader", chrome says "file://" - return "file://"; - default: - // serializing an opaque origin returns "null" - return "null"; - } -}; - -module.exports.basicURLParse = function (input, options) { - if (options === undefined) { - options = {}; - } - - const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); - if (usm.failure) { - return "failure"; - } - - return usm.url; -}; - -module.exports.setTheUsername = function (url, username) { - url.username = ""; - const decoded = punycode.ucs2.decode(username); - for (let i = 0; i < decoded.length; ++i) { - url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.setThePassword = function (url, password) { - url.password = ""; - const decoded = punycode.ucs2.decode(password); - for (let i = 0; i < decoded.length; ++i) { - url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); - } -}; - -module.exports.serializeHost = serializeHost; - -module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; - -module.exports.serializeInteger = function (integer) { - return String(integer); -}; - -module.exports.parseURL = function (input, options) { - if (options === undefined) { - options = {}; - } - - // We don't handle blobs, so this just delegates: - return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); -}; - - -/***/ }), - -/***/ 3185: -/***/ ((module) => { - - - -module.exports.mixin = function mixin(target, source) { - const keys = Object.getOwnPropertyNames(source); - for (let i = 0; i < keys.length; ++i) { - Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); - } -}; - -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); - -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; - -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; - - - -/***/ }), - -/***/ 2940: -/***/ ((module) => { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), - -/***/ 8707: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; - -__webpack_unused_export__ = ({ value: true }); -exports.Y_ = void 0; -const zodToJsonSchema_1 = __nccwpck_require__(5110); -Object.defineProperty(exports, "Y_", ({ enumerable: true, get: function () { return zodToJsonSchema_1.zodToJsonSchema; } })); -__webpack_unused_export__ = zodToJsonSchema_1.zodToJsonSchema; - - -/***/ }), - -/***/ 977: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getDefaultOptions = exports.defaultOptions = void 0; -exports.defaultOptions = { - name: undefined, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "string", - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - emailStrategy: "format:email", -}; -const getDefaultOptions = (options) => (typeof options === "string" - ? Object.assign(Object.assign({}, exports.defaultOptions), { name: options }) : Object.assign(Object.assign({}, exports.defaultOptions), options)); -exports.getDefaultOptions = getDefaultOptions; - - -/***/ }), - -/***/ 9345: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRefs = void 0; -const Options_1 = __nccwpck_require__(977); -const getRefs = (options) => { - const _options = (0, Options_1.getDefaultOptions)(options); - const currentPath = _options.name !== undefined - ? [..._options.basePath, _options.definitionPath, _options.name] - : _options.basePath; - return Object.assign(Object.assign({}, _options), { currentPath: currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - def._def, - { - def: def._def, - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: undefined, - }, - ])) }); -}; -exports.getRefs = getRefs; - - -/***/ }), - -/***/ 1564: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setResponseValueAndErrors = exports.addErrorMessage = void 0; -function addErrorMessage(res, key, errorMessage, refs) { - if (!(refs === null || refs === void 0 ? void 0 : refs.errorMessages)) - return; - if (errorMessage) { - res.errorMessage = Object.assign(Object.assign({}, res.errorMessage), { [key]: errorMessage }); - } -} -exports.addErrorMessage = addErrorMessage; -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); -} -exports.setResponseValueAndErrors = setResponseValueAndErrors; - - -/***/ }), - -/***/ 2265: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseDef = void 0; -const zod_1 = __nccwpck_require__(3301); -const any_1 = __nccwpck_require__(4742); -const array_1 = __nccwpck_require__(9719); -const bigint_1 = __nccwpck_require__(9552); -const boolean_1 = __nccwpck_require__(4037); -const branded_1 = __nccwpck_require__(8944); -const catch_1 = __nccwpck_require__(6651); -const date_1 = __nccwpck_require__(8221); -const default_1 = __nccwpck_require__(6681); -const effects_1 = __nccwpck_require__(2015); -const enum_1 = __nccwpck_require__(9144); -const intersection_1 = __nccwpck_require__(8358); -const literal_1 = __nccwpck_require__(2071); -const map_1 = __nccwpck_require__(291); -const nativeEnum_1 = __nccwpck_require__(6969); -const never_1 = __nccwpck_require__(4668); -const null_1 = __nccwpck_require__(8739); -const nullable_1 = __nccwpck_require__(5879); -const number_1 = __nccwpck_require__(4265); -const object_1 = __nccwpck_require__(2887); -const optional_1 = __nccwpck_require__(8817); -const pipeline_1 = __nccwpck_require__(1097); -const promise_1 = __nccwpck_require__(2354); -const record_1 = __nccwpck_require__(6414); -const set_1 = __nccwpck_require__(4562); -const string_1 = __nccwpck_require__(1876); -const tuple_1 = __nccwpck_require__(1809); -const undefined_1 = __nccwpck_require__(594); -const union_1 = __nccwpck_require__(9878); -const unknown_1 = __nccwpck_require__(2709); -function parseDef(def, refs, forceResolution = false // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61. -) { - const seenItem = refs.seen.get(def); - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== undefined) { - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; - refs.seen.set(def, newItem); - const jsonSchema = selectParser(def, def.typeName, refs); - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -exports.parseDef = parseDef; -const get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { - $ref: item.path.length === 0 - ? "" - : item.path.length === 1 - ? `${item.path[0]}/` - : item.path.join("/"), - }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return {}; - } - return undefined; - } - case "seen": { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return {}; - } - else { - return item.jsonSchema; - } - } - } -}; -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; -const selectParser = (def, typeName, refs) => { - switch (typeName) { - case zod_1.ZodFirstPartyTypeKind.ZodString: - return (0, string_1.parseStringDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodNumber: - return (0, number_1.parseNumberDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodObject: - return (0, object_1.parseObjectDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodBigInt: - return (0, bigint_1.parseBigintDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodBoolean: - return (0, boolean_1.parseBooleanDef)(); - case zod_1.ZodFirstPartyTypeKind.ZodDate: - return (0, date_1.parseDateDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodUndefined: - return (0, undefined_1.parseUndefinedDef)(); - case zod_1.ZodFirstPartyTypeKind.ZodNull: - return (0, null_1.parseNullDef)(refs); - case zod_1.ZodFirstPartyTypeKind.ZodArray: - return (0, array_1.parseArrayDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodUnion: - case zod_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return (0, union_1.parseUnionDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodIntersection: - return (0, intersection_1.parseIntersectionDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodTuple: - return (0, tuple_1.parseTupleDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodRecord: - return (0, record_1.parseRecordDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodLiteral: - return (0, literal_1.parseLiteralDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodEnum: - return (0, enum_1.parseEnumDef)(def); - case zod_1.ZodFirstPartyTypeKind.ZodNativeEnum: - return (0, nativeEnum_1.parseNativeEnumDef)(def); - case zod_1.ZodFirstPartyTypeKind.ZodNullable: - return (0, nullable_1.parseNullableDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodOptional: - return (0, optional_1.parseOptionalDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodMap: - return (0, map_1.parseMapDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodSet: - return (0, set_1.parseSetDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodLazy: - return parseDef(def.getter()._def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodPromise: - return (0, promise_1.parsePromiseDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodNaN: - case zod_1.ZodFirstPartyTypeKind.ZodNever: - return (0, never_1.parseNeverDef)(); - case zod_1.ZodFirstPartyTypeKind.ZodEffects: - return (0, effects_1.parseEffectsDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodAny: - return (0, any_1.parseAnyDef)(); - case zod_1.ZodFirstPartyTypeKind.ZodUnknown: - return (0, unknown_1.parseUnknownDef)(); - case zod_1.ZodFirstPartyTypeKind.ZodDefault: - return (0, default_1.parseDefaultDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodBranded: - return (0, branded_1.parseBrandedDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodCatch: - return (0, catch_1.parseCatchDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodPipeline: - return (0, pipeline_1.parsePipelineDef)(def, refs); - case zod_1.ZodFirstPartyTypeKind.ZodFunction: - case zod_1.ZodFirstPartyTypeKind.ZodVoid: - case zod_1.ZodFirstPartyTypeKind.ZodSymbol: - return undefined; - default: - return ((_) => undefined)(typeName); - } -}; -const addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; - - -/***/ }), - -/***/ 4742: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseAnyDef = void 0; -function parseAnyDef() { - return {}; -} -exports.parseAnyDef = parseAnyDef; - - -/***/ }), - -/***/ 9719: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseArrayDef = void 0; -const zod_1 = __nccwpck_require__(3301); -const errorMessages_1 = __nccwpck_require__(1564); -const parseDef_1 = __nccwpck_require__(2265); -function parseArrayDef(def, refs) { - var _a, _b; - const res = { - type: "array", - }; - if (((_b = (_a = def.type) === null || _a === void 0 ? void 0 : _a._def) === null || _b === void 0 ? void 0 : _b.typeName) !== zod_1.ZodFirstPartyTypeKind.ZodAny) { - res.items = (0, parseDef_1.parseDef)(def.type._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items"] })); - } - if (def.minLength) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs); - } - if (def.maxLength) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - } - if (def.exactLength) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - (0, errorMessages_1.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; -} -exports.parseArrayDef = parseArrayDef; - - -/***/ }), - -/***/ 9552: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseBigintDef = void 0; -const errorMessages_1 = __nccwpck_require__(1564); -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64", - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); - } - else { - (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); - } - else { - (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - (0, errorMessages_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} -exports.parseBigintDef = parseBigintDef; - - -/***/ }), - -/***/ 4037: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseBooleanDef = void 0; -function parseBooleanDef() { - return { - type: "boolean", - }; -} -exports.parseBooleanDef = parseBooleanDef; - - -/***/ }), - -/***/ 8944: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseBrandedDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parseBrandedDef(_def, refs) { - return (0, parseDef_1.parseDef)(_def.type._def, refs); -} -exports.parseBrandedDef = parseBrandedDef; - - -/***/ }), - -/***/ 6651: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseCatchDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -const parseCatchDef = (def, refs) => { - return (0, parseDef_1.parseDef)(def.innerType._def, refs); -}; -exports.parseCatchDef = parseCatchDef; - - -/***/ }), - -/***/ 8221: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseDateDef = void 0; -const errorMessages_1 = __nccwpck_require__(1564); -function parseDateDef(def, refs) { - if (refs.dateStrategy == "integer") { - return integerDateParser(def, refs); - } - else { - return { - type: "string", - format: "date-time", - }; - } -} -exports.parseDateDef = parseDateDef; -const integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time", - }; - for (const check of def.checks) { - switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") { - (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, // This is in milliseconds - check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, // This is in milliseconds - check.message, refs); - } - break; - } - } - return res; -}; - - -/***/ }), - -/***/ 6681: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseDefaultDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parseDefaultDef(_def, refs) { - return Object.assign(Object.assign({}, (0, parseDef_1.parseDef)(_def.innerType._def, refs)), { default: _def.defaultValue() }); -} -exports.parseDefaultDef = parseDefaultDef; - - -/***/ }), - -/***/ 2015: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseEffectsDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" - ? (0, parseDef_1.parseDef)(_def.schema._def, refs) - : {}; -} -exports.parseEffectsDef = parseEffectsDef; - - -/***/ }), - -/***/ 9144: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseEnumDef = void 0; -function parseEnumDef(def) { - return { - type: "string", - enum: def.values, - }; -} -exports.parseEnumDef = parseEnumDef; - - -/***/ }), - -/***/ 8358: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseIntersectionDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -const isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") - return false; - return "allOf" in type; -}; -function parseIntersectionDef(def, refs) { - const allOf = [ - (0, parseDef_1.parseDef)(def.left._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })), - (0, parseDef_1.parseDef)(def.right._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "1"] })), - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" - ? { unevaluatedProperties: false } - : undefined; - const mergedAllOf = []; - // If either of the schemas is an allOf, merge them into a single allOf - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === undefined) { - // If one of the schemas has no unevaluatedProperties set, - // the merged schema should also have no unevaluatedProperties set - unevaluatedProperties = undefined; - } - } - else { - let nestedSchema = schema; - if ("additionalProperties" in schema && - schema.additionalProperties === false) { - const { additionalProperties } = schema, rest = __rest(schema, ["additionalProperties"]); - nestedSchema = rest; - } - else { - // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties - unevaluatedProperties = undefined; - } - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length - ? Object.assign({ allOf: mergedAllOf }, unevaluatedProperties) : undefined; -} -exports.parseIntersectionDef = parseIntersectionDef; - - -/***/ }), - -/***/ 2071: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseLiteralDef = void 0; -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && - parsedType !== "number" && - parsedType !== "boolean" && - parsedType !== "string") { - return { - type: Array.isArray(def.value) ? "array" : "object", - }; - } - if (refs.target === "openApi3") { - return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value], - }; - } - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value, - }; -} -exports.parseLiteralDef = parseLiteralDef; - - -/***/ }), - -/***/ 291: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseMapDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parseMapDef(def, refs) { - const keys = (0, parseDef_1.parseDef)(def.keyType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", "items", "0"] })) || {}; - const values = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", "items", "1"] })) || {}; - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2, - }, - }; -} -exports.parseMapDef = parseMapDef; - - -/***/ }), - -/***/ 6969: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseNativeEnumDef = void 0; -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 - ? parsedTypes[0] === "string" - ? "string" - : "number" - : ["string", "number"], - enum: actualValues, - }; -} -exports.parseNativeEnumDef = parseNativeEnumDef; - - -/***/ }), - -/***/ 4668: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseNeverDef = void 0; -function parseNeverDef() { - return { - not: {}, - }; -} -exports.parseNeverDef = parseNeverDef; - - -/***/ }), - -/***/ 8739: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseNullDef = void 0; -function parseNullDef(refs) { - return refs.target === "openApi3" - ? { - enum: ["null"], - nullable: true, - } - : { - type: "null", - }; -} -exports.parseNullDef = parseNullDef; - - -/***/ }), - -/***/ 5879: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseNullableDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -const union_1 = __nccwpck_require__(9878); -function parseNullableDef(def, refs) { - if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && - (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") { - return { - type: union_1.primitiveMappings[def.innerType._def.typeName], - nullable: true, - }; - } - return { - type: [ - union_1.primitiveMappings[def.innerType._def.typeName], - "null", - ], - }; - } - if (refs.target === "openApi3") { - const base = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath] })); - return base && Object.assign(Object.assign({}, base), { nullable: true }); - } - const base = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", "0"] })); - return base && { anyOf: [base, { type: "null" }] }; -} -exports.parseNullableDef = parseNullableDef; - - -/***/ }), - -/***/ 4265: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseNumberDef = void 0; -const errorMessages_1 = __nccwpck_require__(1564); -function parseNumberDef(def, refs) { - const res = { - type: "number", - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "int": - res.type = "integer"; - (0, errorMessages_1.addErrorMessage)(res, "type", check.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); - } - else { - (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); - } - else { - (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - (0, errorMessages_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} -exports.parseNumberDef = parseNumberDef; - - -/***/ }), - -/***/ 2887: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseObjectDef = exports.parseObjectDefX = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parseObjectDefX(def, refs) { - var _a, _b; - Object.keys(def.shape()).reduce((schema, key) => { - let prop = def.shape()[key]; - const isOptional = prop.isOptional(); - if (!isOptional) { - prop = Object.assign({}, prop._def.innerSchema); - } - const propSchema = (0, parseDef_1.parseDef)(prop._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", key], propertyPath: [...refs.currentPath, "properties", key] })); - if (propSchema !== undefined) { - schema.properties[key] = propSchema; - if (!isOptional) { - if (!schema.required) { - schema.required = []; - } - schema.required.push(key); - } - } - return schema; - }, { - type: "object", - properties: {}, - additionalProperties: def.catchall._def.typeName === "ZodNever" - ? def.unknownKeys === "passthrough" - : (_a = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _a !== void 0 ? _a : true, - }); - const result = Object.assign(Object.assign({ type: "object" }, Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { - if (propDef === undefined || propDef._def === undefined) - return acc; - const parsedDef = (0, parseDef_1.parseDef)(propDef._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] })); - if (parsedDef === undefined) - return acc; - return { - properties: Object.assign(Object.assign({}, acc.properties), { [propName]: parsedDef }), - required: propDef.isOptional() - ? acc.required - : [...acc.required, propName], - }; - }, { properties: {}, required: [] })), { additionalProperties: def.catchall._def.typeName === "ZodNever" - ? def.unknownKeys === "passthrough" - : (_b = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _b !== void 0 ? _b : true }); - if (!result.required.length) - delete result.required; - return result; -} -exports.parseObjectDefX = parseObjectDefX; -function parseObjectDef(def, refs) { - var _a; - const result = Object.assign(Object.assign({ type: "object" }, Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { - if (propDef === undefined || propDef._def === undefined) - return acc; - const parsedDef = (0, parseDef_1.parseDef)(propDef._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] })); - if (parsedDef === undefined) - return acc; - return { - properties: Object.assign(Object.assign({}, acc.properties), { [propName]: parsedDef }), - required: propDef.isOptional() - ? acc.required - : [...acc.required, propName], - }; - }, { properties: {}, required: [] })), { additionalProperties: def.catchall._def.typeName === "ZodNever" - ? def.unknownKeys === "passthrough" - : (_a = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _a !== void 0 ? _a : true }); - if (!result.required.length) - delete result.required; - return result; -} -exports.parseObjectDef = parseObjectDef; - - -/***/ }), - -/***/ 8817: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseOptionalDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -const parseOptionalDef = (def, refs) => { - var _a; - if (refs.currentPath.toString() === ((_a = refs.propertyPath) === null || _a === void 0 ? void 0 : _a.toString())) { - return (0, parseDef_1.parseDef)(def.innerType._def, refs); - } - const innerSchema = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", "1"] })); - return innerSchema - ? { - anyOf: [ - { - not: {}, - }, - innerSchema, - ], - } - : {}; -}; -exports.parseOptionalDef = parseOptionalDef; - - -/***/ }), - -/***/ 1097: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parsePipelineDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -const parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") { - return (0, parseDef_1.parseDef)(def.in._def, refs); - } - const a = (0, parseDef_1.parseDef)(def.in._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })); - const b = (0, parseDef_1.parseDef)(def.out._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] })); - return { - allOf: [a, b].filter((x) => x !== undefined), - }; -}; -exports.parsePipelineDef = parsePipelineDef; - - -/***/ }), - -/***/ 2354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parsePromiseDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parsePromiseDef(def, refs) { - return (0, parseDef_1.parseDef)(def.type._def, refs); -} -exports.parsePromiseDef = parsePromiseDef; - - -/***/ }), - -/***/ 6414: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseRecordDef = void 0; -const zod_1 = __nccwpck_require__(3301); -const parseDef_1 = __nccwpck_require__(2265); -const string_1 = __nccwpck_require__(1876); -function parseRecordDef(def, refs) { - var _a, _b, _c, _d, _e; - if (refs.target === "openApi3" && - ((_a = def.keyType) === null || _a === void 0 ? void 0 : _a._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodEnum) { - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => { - var _a; - return (Object.assign(Object.assign({}, acc), { [key]: (_a = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", key] }))) !== null && _a !== void 0 ? _a : {} })); - }, {}), - additionalProperties: false, - }; - } - const schema = { - type: "object", - additionalProperties: (_b = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _b !== void 0 ? _b : {}, - }; - if (refs.target === "openApi3") { - return schema; - } - if (((_c = def.keyType) === null || _c === void 0 ? void 0 : _c._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodString && - ((_d = def.keyType._def.checks) === null || _d === void 0 ? void 0 : _d.length)) { - const keyType = Object.entries((0, string_1.parseStringDef)(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === "type" ? acc : Object.assign(Object.assign({}, acc), { [key]: value })), {}); - return Object.assign(Object.assign({}, schema), { propertyNames: keyType }); - } - else if (((_e = def.keyType) === null || _e === void 0 ? void 0 : _e._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodEnum) { - return Object.assign(Object.assign({}, schema), { propertyNames: { - enum: def.keyType._def.values, - } }); - } - return schema; -} -exports.parseRecordDef = parseRecordDef; - - -/***/ }), - -/***/ 4562: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseSetDef = void 0; -const errorMessages_1 = __nccwpck_require__(1564); -const parseDef_1 = __nccwpck_require__(2265); -function parseSetDef(def, refs) { - const items = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items"] })); - const schema = { - type: "array", - uniqueItems: true, - items, - }; - if (def.minSize) { - (0, errorMessages_1.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - (0, errorMessages_1.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} -exports.parseSetDef = parseSetDef; - - -/***/ }), - -/***/ 1876: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseStringDef = exports.emojiPattern = exports.ulidPattern = exports.cuid2Pattern = exports.cuidPattern = exports.emailPattern = void 0; -const errorMessages_1 = __nccwpck_require__(1564); -exports.emailPattern = '^(([^<>()[\\]\\\\.,;:\\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,})+))$'; -exports.cuidPattern = "^c[^\\s-]{8,}$"; -exports.cuid2Pattern = "^[a-z][a-z0-9]*$"; -exports.ulidPattern = "/[0-9A-HJKMNP-TV-Z]{26}/"; -exports.emojiPattern = "/^(p{Extended_Pictographic}|p{Emoji_Component})+$/u"; -function parseStringDef(def, refs) { - const res = { - type: "string", - }; - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case "min": - (0, errorMessages_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" - ? Math.max(res.minLength, check.value) - : check.value, check.message, refs); - break; - case "max": - (0, errorMessages_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" - ? Math.min(res.maxLength, check.value) - : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, exports.emailPattern, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex.source, check.message, refs); - break; - case "cuid": - addPattern(res, exports.cuidPattern, check.message, refs); - break; - case "cuid2": - addPattern(res, exports.cuid2Pattern, check.message, refs); - break; - case "startsWith": - addPattern(res, "^" + escapeNonAlphaNumeric(check.value), check.message, refs); - break; - case "endsWith": - addPattern(res, escapeNonAlphaNumeric(check.value) + "$", check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "length": - (0, errorMessages_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" - ? Math.max(res.minLength, check.value) - : check.value, check.message, refs); - (0, errorMessages_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" - ? Math.min(res.maxLength, check.value) - : check.value, check.message, refs); - break; - case "includes": { - addPattern(res, escapeNonAlphaNumeric(check.value), check.message, refs); - break; - } - case "ip": { - if (check.version !== "v6") { - addFormat(res, "ipv4", check.message, refs); - } - if (check.version !== "v4") { - addFormat(res, "ipv6", check.message, refs); - } - break; - } - case "emoji": - addPattern(res, exports.emojiPattern, check.message, refs); - break; - case "ulid": { - addPattern(res, exports.ulidPattern, check.message, refs); - break; - } - case "toLowerCase": - case "toUpperCase": - case "trim": - // I have no idea why these are checks in Zod 🤷 - break; - default: - ((_) => { })(check); - } - } - } - return res; -} -exports.parseStringDef = parseStringDef; -const escapeNonAlphaNumeric = (value) => Array.from(value) - .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) - .join(""); -const addFormat = (schema, value, message, refs) => { - var _a; - if (schema.format || ((_a = schema.anyOf) === null || _a === void 0 ? void 0 : _a.some((x) => x.format))) { - if (!schema.anyOf) { - schema.anyOf = []; - } - if (schema.format) { - schema.anyOf.push(Object.assign({ format: schema.format }, (schema.errorMessage && - refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format }, - }))); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.anyOf.push(Object.assign({ format: value }, (message && - refs.errorMessages && { errorMessage: { format: message } }))); - } - else { - (0, errorMessages_1.setResponseValueAndErrors)(schema, "format", value, message, refs); - } -}; -const addPattern = (schema, value, message, refs) => { - var _a; - if (schema.pattern || ((_a = schema.allOf) === null || _a === void 0 ? void 0 : _a.some((x) => x.pattern))) { - if (!schema.allOf) { - schema.allOf = []; - } - if (schema.pattern) { - schema.allOf.push(Object.assign({ pattern: schema.pattern }, (schema.errorMessage && - refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern }, - }))); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.allOf.push(Object.assign({ pattern: value }, (message && - refs.errorMessages && { errorMessage: { pattern: message } }))); - } - else { - (0, errorMessages_1.setResponseValueAndErrors)(schema, "pattern", value, message, refs); - } -}; - - -/***/ }), - -/***/ 1809: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseTupleDef = void 0; -const parseDef_1 = __nccwpck_require__(2265); -function parseTupleDef(def, refs) { - if (def.rest) { - return { - type: "array", - minItems: def.items.length, - items: def.items - .map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", `${i}`] }))) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - additionalItems: (0, parseDef_1.parseDef)(def.rest._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalItems"] })), - }; - } - else { - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items - .map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", `${i}`] }))) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - }; - } -} -exports.parseTupleDef = parseTupleDef; + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; -/***/ }), + return new Body.Promise(function (resolve, reject) { + let resTimeout; -/***/ 594: -/***/ ((__unused_webpack_module, exports) => { + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseUndefinedDef = void 0; -function parseUndefinedDef() { - return { - not: {}, - }; -} -exports.parseUndefinedDef = parseUndefinedDef; + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } -/***/ }), + accumBytes += chunk.length; + accum.push(chunk); + }); -/***/ 9878: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + body.on('end', function () { + if (abort) { + return; + } + clearTimeout(resTimeout); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseUnionDef = exports.primitiveMappings = void 0; -const parseDef_1 = __nccwpck_require__(2265); -exports.primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null", -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. - if (options.every((x) => x._def.typeName in exports.primitiveMappings && - (!x._def.checks || !x._def.checks.length))) { - // all types in union are primitive and lack checks, so might as well squash into {type: [...]} - const types = options.reduce((types, x) => { - const type = exports.primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 - return type && !types.includes(type) ? [...types, type] : types; - }, []); - return { - type: types.length > 1 ? types : types[0], - }; - } - else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - // all options literals - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": - return [...acc, type]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x._def.value === null) - return [...acc, "null"]; - case "symbol": - case "undefined": - case "function": - default: - return acc; - } - }, []); - if (types.length === options.length) { - // all the literals are primitive, as far as null can be considered primitive - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []), - }; - } - } - else if (options.every((x) => x._def.typeName === "ZodEnum")) { - return { - type: "string", - enum: options.reduce((acc, x) => [ - ...acc, - ...x._def.values.filter((x) => !acc.includes(x)), - ], []), - }; - } - return asAnyOf(def, refs); + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); } -exports.parseUnionDef = parseUnionDef; -const asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map - ? Array.from(def.options.values()) - : def.options) - .map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", `${i}`] }))) - .filter((x) => !!x && - (!refs.strictUnions || - (typeof x === "object" && Object.keys(x).length > 0))); - return anyOf.length ? { anyOf } : undefined; -}; - -/***/ }), - -/***/ 2709: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseUnknownDef = void 0; -function parseUnknownDef() { - return {}; -} -exports.parseUnknownDef = parseUnknownDef; +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; -/***/ }), + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } -/***/ 5110: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + // html5 + if (!res && str) { + res = / { - var _a; - const refs = (0, Refs_1.getRefs)(options); - const definitions = typeof options === "object" && options.definitions - ? Object.entries(options.definitions).reduce((acc, [name, schema]) => { - var _a; - return (Object.assign(Object.assign({}, acc), { [name]: (_a = (0, parseDef_1.parseDef)(schema._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), true)) !== null && _a !== void 0 ? _a : {} })); - }, {}) - : undefined; - const name = typeof options === "string" ? options : options === null || options === void 0 ? void 0 : options.name; - const main = (_a = (0, parseDef_1.parseDef)(schema._def, name === undefined - ? refs - : Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), false)) !== null && _a !== void 0 ? _a : {}; - const combined = name === undefined - ? definitions - ? Object.assign(Object.assign({}, main), { [refs.definitionPath]: definitions }) : main - : { - $ref: [ - ...(refs.$refStrategy === "relative" ? [] : refs.basePath), - refs.definitionPath, - name, - ].join("/"), - [refs.definitionPath]: Object.assign(Object.assign({}, definitions), { [name]: main }), - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (refs.target === "jsonSchema2019-09") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - } - return combined; -}; -exports.zodToJsonSchema = zodToJsonSchema; + // html4 + if (!res && str) { + res = / { + // found charset + if (res) { + charset = res.pop(); + // prevent decode issues when sites use incorrect encoding + // ref: https://hsivonen.fi/encoding-menu/ + if (charset === 'gb2312' || charset === 'gbk') { + charset = 'gb18030'; + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; -const util_1 = __nccwpck_require__(3985); -exports.ZodIssueCode = util_1.util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -exports.quotelessJson = quotelessJson; -class ZodError extends Error { - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - get errors() { - return this.issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } + // turn raw buffers into a single utf-8 buffer + return convert(buffer, 'UTF-8', charset).toString(); } -exports.ZodError = ZodError; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - - -/***/ }), - -/***/ 9566: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * Detect a URLSearchParams object + * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143 + * + * @param Object obj Object to detect by type or brand + * @return String + */ +function isURLSearchParams(obj) { + // Duck-typing as a necessary condition. + if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') { + return false; + } -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; -const en_1 = __importDefault(__nccwpck_require__(468)); -exports.defaultErrorMap = en_1.default; -let overrideErrorMap = en_1.default; -function setErrorMap(map) { - overrideErrorMap = map; + // Brand-checking and more duck-typing as optional condition. + return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; } -exports.setErrorMap = setErrorMap; -function getErrorMap() { - return overrideErrorMap; + +/** + * Check if `obj` is a W3C `Blob` object (which `File` inherits from) + * @param {*} obj + * @return {boolean} + */ +function isBlob(obj) { + return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); } -exports.getErrorMap = getErrorMap; +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @return Mixed + */ +function clone(instance) { + let p1, p2; + let body = instance.body; -/***/ }), + // don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } -/***/ 9906: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + // check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if (body instanceof Stream && typeof body.getBoundary !== 'function') { + // tee instance body + p1 = new PassThrough(); + p2 = new PassThrough(); + body.pipe(p1); + body.pipe(p2); + // set instance body to teed body and return the other teed body + instance[INTERNALS].body = p1; + body = p2; + } + return body; +} -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(9566), exports); -__exportStar(__nccwpck_require__(888), exports); -__exportStar(__nccwpck_require__(9449), exports); -__exportStar(__nccwpck_require__(3985), exports); -__exportStar(__nccwpck_require__(9335), exports); -__exportStar(__nccwpck_require__(9892), exports); +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param Mixed instance Any options.body input + */ +function extractContentType(body) { + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isBlob(body)) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream) { + // body is stream + // can't really do much about this + return null; + } else { + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; + } +} +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible + */ +function getTotalBytes(instance) { + const body = instance.body; -/***/ }), -/***/ 2513: -/***/ ((__unused_webpack_module, exports) => { + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } +} +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.errorUtil = void 0; -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil = exports.errorUtil || (exports.errorUtil = {})); + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } +} -/***/ }), +// expose Promise +Body.Promise = global.Promise; -/***/ 888: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * headers.js + * + * Headers class offers convenient helpers + */ +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; -const errors_1 = __nccwpck_require__(9566); -const en_1 = __importDefault(__nccwpck_require__(468)); -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: issueData.message || errorMessage, - }; -}; -exports.makeIssue = makeIssue; -exports.EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const issue = (0, exports.makeIssue)({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - en_1.default, - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } } -exports.addIssueToContext = addIssueToContext; -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return exports.INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - syncPairs.push({ - key: await pair.key, - value: await pair.value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return exports.INVALID; - if (value.status === "aborted") - return exports.INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } + +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } } -exports.ParseStatus = ParseStatus; -exports.INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -exports.DIRTY = DIRTY; -const OK = (value) => ({ status: "valid", value }); -exports.OK = OK; -const isAborted = (x) => x.status === "aborted"; -exports.isAborted = isAborted; -const isDirty = (x) => x.status === "dirty"; -exports.isDirty = isDirty; -const isValid = (x) => x.status === "valid"; -exports.isValid = isValid; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -exports.isAsync = isAsync; +/** + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined + */ +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; +} -/***/ }), +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; -/***/ 9449: -/***/ ((__unused_webpack_module, exports) => { + this[MAP] = Object.create(null); + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); -Object.defineProperty(exports, "__esModule", ({ value: true })); + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + return; + } -/***/ }), + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } -/***/ 3985: -/***/ ((__unused_webpack_module, exports) => { + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; -var util; -(function (util) { - util.assertEqual = (val) => val; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" - ? (obj) => Object.keys(obj) - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util = exports.util || (exports.util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, - }; - }; -})(objectUtil = exports.objectUtil || (exports.objectUtil = {})); -exports.ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return exports.ZodParsedType.undefined; - case "string": - return exports.ZodParsedType.string; - case "number": - return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; - case "boolean": - return exports.ZodParsedType.boolean; - case "function": - return exports.ZodParsedType.function; - case "bigint": - return exports.ZodParsedType.bigint; - case "symbol": - return exports.ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return exports.ZodParsedType.array; - } - if (data === null) { - return exports.ZodParsedType.null; - } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { - return exports.ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return exports.ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return exports.ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return exports.ZodParsedType.date; - } - return exports.ZodParsedType.object; - default: - return exports.ZodParsedType.unknown; - } -}; -exports.getParsedType = getParsedType; + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + return this[MAP][key].join(', '); + } -/***/ }), + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; -/***/ 3301: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.z = void 0; -const z = __importStar(__nccwpck_require__(9906)); -exports.z = z; -__exportStar(__nccwpck_require__(9906), exports); -exports["default"] = z; + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } -/***/ }), + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } -/***/ 468: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(3985); -const ZodError_1 = __nccwpck_require__(9892); -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodError_1.ZodIssueCode.invalid_type: - if (issue.received === util_1.ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodError_1.ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; - break; - case ZodError_1.ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; - break; - case ZodError_1.ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; - break; - case ZodError_1.ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodError_1.ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodError_1.ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodError_1.ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodError_1.ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util_1.util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodError_1.ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `smaller than or equal to` - : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodError_1.ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodError_1.ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util_1.util.assertNever(issue); - } - return { message }; -}; -exports["default"] = errorMap; + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; -/***/ }), +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); -/***/ 9335: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; -exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = exports.discriminatedUnion = void 0; -const errors_1 = __nccwpck_require__(9566); -const errorUtil_1 = __nccwpck_require__(2513); -const parseUtil_1 = __nccwpck_require__(888); -const util_1 = __nccwpck_require__(3985); -const ZodError_1 = __nccwpck_require__(9892); -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); } -const handleResult = (ctx, result) => { - if ((0, parseUtil_1.isValid)(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError_1.ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - if (typeof ctx.data === "undefined") { - return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; - } - return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; - }; - return { errorMap: customMap, description }; + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; } -class ZodType { - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - get description() { - return this._def.description; - } - _getType(input) { - return (0, util_1.getParsedType)(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new parseUtil_1.ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if ((0, parseUtil_1.isAsync)(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodError_1.ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this, this._def); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; } -exports.ZodType = ZodType; -exports.Schema = ZodType; -exports.ZodSchema = ZodType; -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[a-z][a-z0-9]*$/; -const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; -const 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; -const emailRegex = /^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u; -const ipv4Regex = /^(((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}))$/; -const 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})))$/; -const datetimeRegex = (args) => { - if (args.precision) { - if (args.offset) { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); - } - else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); - } - } - else if (args.precision === 0) { - if (args.offset) { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); - } - else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); - } - } - else { - if (args.offset) { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); - } - else { - return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); - } - } -}; -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } } -class ZodString extends ZodType { - constructor() { - super(...arguments); - this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { - validation, - code: ZodError_1.ZodIssueCode.invalid_string, - ...errorUtil_1.errorUtil.errToObj(message), - }); - this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message)); - this.trim = () => new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - this.toLowerCase = () => new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - this.toUpperCase = () => new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.string, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "email", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "emoji", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "uuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid2", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ulid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "regex", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ip", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); - } - datetime(options) { - var _a; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); } -exports.ZodString = ZodString; -ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; } -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.number, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util_1.util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil_1.errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil_1.errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); - } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); } -exports.ZodNumber = ZodNumber; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - input.data = BigInt(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.bigint) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.bigint, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } } -exports.ZodBigInt = ZodBigInt; -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.boolean, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); } -exports.ZodBoolean = ZodBoolean; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.date, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_date, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } } -exports.ZodDate = ZodDate; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; }; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.symbol, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; + + +/***/ }), + +/***/ 4856: +/***/ ((module, exports, __nccwpck_require__) => { + + + +var crypto = __nccwpck_require__(6113); + +/** + * Exported function + * + * Options: + * + * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5' + * - `excludeValues` {true|*false} hash object keys, values ignored + * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64' + * - `ignoreUnknown` {true|*false} ignore unknown object types + * - `replacer` optional function that replaces values before hashing + * - `respectFunctionProperties` {*true|false} consider function properties when hashing + * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing + * - `respectType` {*true|false} Respect special properties (prototype, constructor) + * when hashing to distinguish between types + * - `unorderedArrays` {true|*false} Sort all arrays before hashing + * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing + * * = default + * + * @param {object} object value to hash + * @param {object} options hashing options + * @return {string} hash value + * @api public + */ +exports = module.exports = objectHash; + +function objectHash(object, options){ + options = applyDefaults(object, options); + + return hash(object, options); } -exports.ZodSymbol = ZodSymbol; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); + +/** + * Exported sugar methods + * + * @param {object} object value to hash + * @return {string} hash value + * @api public + */ +exports.sha1 = function(object){ + return objectHash(object); }; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.undefined, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodUndefined = ZodUndefined; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); +exports.keys = function(object){ + return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'}); }; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.null, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodNull = ZodNull; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); +exports.MD5 = function(object){ + return objectHash(object, {algorithm: 'md5', encoding: 'hex'}); }; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodAny = ZodAny; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); +exports.keysMD5 = function(object){ + return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true}); }; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); + +// Internals +var hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5']; +hashes.push('passthrough'); +var encodings = ['buffer', 'hex', 'binary', 'base64']; + +function applyDefaults(object, sourceOptions){ + sourceOptions = sourceOptions || {}; + + // create a copy rather than mutating + var options = {}; + options.algorithm = sourceOptions.algorithm || 'sha1'; + options.encoding = sourceOptions.encoding || 'hex'; + options.excludeValues = sourceOptions.excludeValues ? true : false; + options.algorithm = options.algorithm.toLowerCase(); + options.encoding = options.encoding.toLowerCase(); + options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false + options.respectType = sourceOptions.respectType === false ? false : true; // default to true + options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true; + options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true; + options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false + options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false + options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true + options.replacer = sourceOptions.replacer || undefined; + options.excludeKeys = sourceOptions.excludeKeys || undefined; + + if(typeof object === 'undefined') { + throw new Error('Object argument required.'); + } + + // if there is a case-insensitive match in the hashes list, accept it + // (i.e. SHA256 for sha256) + for (var i = 0; i < hashes.length; ++i) { + if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) { + options.algorithm = hashes[i]; } + } + + if(hashes.indexOf(options.algorithm) === -1){ + throw new Error('Algorithm "' + options.algorithm + '" not supported. ' + + 'supported values: ' + hashes.join(', ')); + } + + if(encodings.indexOf(options.encoding) === -1 && + options.algorithm !== 'passthrough'){ + throw new Error('Encoding "' + options.encoding + '" not supported. ' + + 'supported values: ' + encodings.join(', ')); + } + + return options; } -exports.ZodUnknown = ZodUnknown; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.never, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } + +/** Check if the given function is a native function */ +function isNativeFunction(f) { + if ((typeof f) !== 'function') { + return false; + } + var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i; + return exp.exec(Function.prototype.toString.call(f)) != null; } -exports.ZodNever = ZodNever; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.void, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } + +function hash(object, options) { + var hashingStream; + + if (options.algorithm !== 'passthrough') { + hashingStream = crypto.createHash(options.algorithm); + } else { + hashingStream = new PassThrough(); + } + + if (typeof hashingStream.write === 'undefined') { + hashingStream.write = hashingStream.update; + hashingStream.end = hashingStream.update; + } + + var hasher = typeHasher(options, hashingStream); + hasher.dispatch(object); + if (!hashingStream.update) { + hashingStream.end(''); + } + + if (hashingStream.digest) { + return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding); + } + + var buf = hashingStream.read(); + if (options.encoding === 'buffer') { + return buf; + } + + return buf.toString(options.encoding); } -exports.ZodVoid = ZodVoid; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); + +/** + * Expose streaming API + * + * @param {object} object Value to serialize + * @param {object} options Options, as for hash() + * @param {object} stream A stream to write the serializiation to + * @api public + */ +exports.writeToStream = function(object, options, stream) { + if (typeof stream === 'undefined') { + stream = options; + options = {}; + } + + options = applyDefaults(object, options); + + return typeHasher(options, stream).dispatch(object); }; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } + +function typeHasher(options, writeTo, context){ + context = context || []; + var write = function(str) { + if (writeTo.update) { + return writeTo.update(str, 'utf8'); + } else { + return writeTo.write(str, 'utf8'); + } + }; + + return { + dispatch: function(value){ + if (options.replacer) { + value = options.replacer(value); + } + + var type = typeof value; + if (value === null) { + type = 'null'; + } + + //console.log("[DEBUG] Dispatch: ", value, "->", type, " -> ", "_" + type); + + return this['_' + type](value); + }, + _object: function(object) { + var pattern = (/\[object (.*)\]/i); + var objString = Object.prototype.toString.call(object); + var objType = pattern.exec(objString); + if (!objType) { // object type did not match [object ...] + objType = 'unknown:[' + objString + ']'; + } else { + objType = objType[1]; // take only the class name + } + + objType = objType.toLowerCase(); + + var objectNumber = null; + + if ((objectNumber = context.indexOf(object)) >= 0) { + return this.dispatch('[CIRCULAR:' + objectNumber + ']'); + } else { + context.push(object); + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) { + write('buffer:'); + return write(object); + } + + if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') { + if(this['_' + objType]) { + this['_' + objType](object); + } else if (options.ignoreUnknown) { + return write('[' + objType + ']'); + } else { + throw new Error('Unknown object type "' + objType + '"'); } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } + }else{ + var keys = Object.keys(object); + if (options.unorderedObjects) { + keys = keys.sort(); } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } + // Make sure to incorporate special properties, so + // Types with different prototypes will produce + // a different hash and objects derived from + // different functions (`new Foo`, `new Bar`) will + // produce different hashes. + // We never do this for native functions since some + // seem to break because of that. + if (options.respectType !== false && !isNativeFunction(object)) { + keys.splice(0, 0, 'prototype', '__proto__', 'constructor'); } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return parseUtil_1.ParseStatus.mergeArray(status, result); - }); + + if (options.excludeKeys) { + keys = keys.filter(function(key) { return !options.excludeKeys(key); }); } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return parseUtil_1.ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, + + write('object:' + keys.length + ':'); + var self = this; + return keys.forEach(function(key){ + self.dispatch(key); + write(':'); + if(!options.excludeValues) { + self.dispatch(object[key]); + } + write(','); }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, + } + }, + _array: function(arr, unordered){ + unordered = typeof unordered !== 'undefined' ? unordered : + options.unorderedArrays !== false; // default to options.unorderedArrays + + var self = this; + write('array:' + arr.length + ':'); + if (!unordered || arr.length <= 1) { + return arr.forEach(function(entry) { + return self.dispatch(entry); }); - } - nonempty(message) { - return this.min(1, message); - } + } + + // the unordered case is a little more complicated: + // since there is no canonical ordering on objects, + // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false, + // we first serialize each entry using a PassThrough stream + // before sorting. + // also: we can’t use the same context array for all entries + // since the order of hashing should *not* matter. instead, + // we keep track of the additions to a copy of the context array + // and add all of them to the global context array when we’re done + var contextAdditions = []; + var entries = arr.map(function(entry) { + var strm = new PassThrough(); + var localContext = context.slice(); // make copy + var hasher = typeHasher(options, strm, localContext); + hasher.dispatch(entry); + // take only what was added to localContext and append it to contextAdditions + contextAdditions = contextAdditions.concat(localContext.slice(context.length)); + return strm.read().toString(); + }); + context = context.concat(contextAdditions); + entries.sort(); + return this._array(entries, false); + }, + _date: function(date){ + return write('date:' + date.toJSON()); + }, + _symbol: function(sym){ + return write('symbol:' + sym.toString()); + }, + _error: function(err){ + return write('error:' + err.toString()); + }, + _boolean: function(bool){ + return write('bool:' + bool.toString()); + }, + _string: function(string){ + write('string:' + string.length + ':'); + write(string.toString()); + }, + _function: function(fn){ + write('fn:'); + if (isNativeFunction(fn)) { + this.dispatch('[native]'); + } else { + this.dispatch(fn.toString()); + } + + if (options.respectFunctionNames !== false) { + // Make sure we can still distinguish native functions + // by their name, otherwise String and Function will + // have the same hash + this.dispatch("function-name:" + String(fn.name)); + } + + if (options.respectFunctionProperties) { + this._object(fn); + } + }, + _number: function(number){ + return write('number:' + number.toString()); + }, + _xml: function(xml){ + return write('xml:' + xml.toString()); + }, + _null: function() { + return write('Null'); + }, + _undefined: function() { + return write('Undefined'); + }, + _regexp: function(regex){ + return write('regex:' + regex.toString()); + }, + _uint8array: function(arr){ + write('uint8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint8clampedarray: function(arr){ + write('uint8clampedarray:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int8array: function(arr){ + write('int8array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint16array: function(arr){ + write('uint16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int16array: function(arr){ + write('int16array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _uint32array: function(arr){ + write('uint32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _int32array: function(arr){ + write('int32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float32array: function(arr){ + write('float32array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _float64array: function(arr){ + write('float64array:'); + return this.dispatch(Array.prototype.slice.call(arr)); + }, + _arraybuffer: function(arr){ + write('arraybuffer:'); + return this.dispatch(new Uint8Array(arr)); + }, + _url: function(url) { + return write('url:' + url.toString(), 'utf8'); + }, + _map: function(map) { + write('map:'); + var arr = Array.from(map); + return this._array(arr, options.unorderedSets !== false); + }, + _set: function(set) { + write('set:'); + var arr = Array.from(set); + return this._array(arr, options.unorderedSets !== false); + }, + _file: function(file) { + write('file:'); + return this.dispatch([file.name, file.size, file.type, file.lastModfied]); + }, + _blob: function() { + if (options.ignoreUnknown) { + return write('[blob]'); + } + + throw Error('Hashing Blob objects is currently not supported\n' + + '(see https://github.com/puleos/object-hash/issues/26)\n' + + 'Use "options.replacer" or "options.ignoreUnknown"\n'); + }, + _domwindow: function() { return write('domwindow'); }, + _bigint: function(number){ + return write('bigint:' + number.toString()); + }, + /* Node.js standard native objects */ + _process: function() { return write('process'); }, + _timer: function() { return write('timer'); }, + _pipe: function() { return write('pipe'); }, + _tcp: function() { return write('tcp'); }, + _udp: function() { return write('udp'); }, + _tty: function() { return write('tty'); }, + _statwatcher: function() { return write('statwatcher'); }, + _securecontext: function() { return write('securecontext'); }, + _connection: function() { return write('connection'); }, + _zlib: function() { return write('zlib'); }, + _context: function() { return write('context'); }, + _nodescript: function() { return write('nodescript'); }, + _httpparser: function() { return write('httpparser'); }, + _dataview: function() { return write('dataview'); }, + _signal: function() { return write('signal'); }, + _fsevent: function() { return write('fsevent'); }, + _tlswrap: function() { return write('tlswrap'); }, + }; } -exports.ZodArray = ZodArray; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; + +// Mini-implementation of stream.PassThrough +// We are far from having need for the full implementation, and we can +// make assumptions like "many writes, then only one final read" +// and we can ignore encoding specifics +function PassThrough() { + return { + buf: '', + + write: function(b) { + this.buf += b; + }, + + end: function(b) { + this.buf += b; + }, + + read: function() { + return this.buf; } + }; } -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util_1.util.objectKeys(shape); - return (this._cached = { shape, keys }); - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") { - } - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - syncPairs.push({ - key, - value: await pair.value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); - }); + + +/***/ }), + +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(2940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} + + +/***/ }), + +/***/ 1330: +/***/ ((module) => { + + +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); + + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; + + +/***/ }), + +/***/ 8983: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const EventEmitter = __nccwpck_require__(1848); +const p_timeout_1 = __nccwpck_require__(6424); +const priority_queue_1 = __nccwpck_require__(8492); +// eslint-disable-next-line @typescript-eslint/no-empty-function +const empty = () => { }; +const timeoutError = new p_timeout_1.TimeoutError(); +/** +Promise queue with concurrency control. +*/ +class PQueue extends EventEmitter { + constructor(options) { + var _a, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); + if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil_1.errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - 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; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; } - pick(mask) { - const shape = {}; - util_1.util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; } - omit(mask) { - const shape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit('next'); } - deepPartial() { - return deepPartialify(this); + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit('idle'); + } } - partial(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = undefined; } - required(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === undefined) { + const delay = this._intervalEnd - now; + if (delay < 0) { + // Act as the interval was done + // We don't need to resume it here because it will be resumed on line 160 + this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; + // Act as the interval is pending + if (this._timeoutId === undefined) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); } - newShape[key] = newField; + return true; } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util_1.util.objectKeys(this.shape)); + } + return false; } -} -exports.ZodObject = ZodObject; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } + _tryToStartAnother() { + if (this._queue.size === 0) { + // We can clear the interval ("pause") + // Because we can redo it later ("resume") + if (this._intervalId) { + clearInterval(this._intervalId); } - const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); + this._intervalId = undefined; + this._resolvePromises(); + return false; } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); + this.emit('active'); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); } + return true; } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; } + return false; } - get options() { - return this._def.options; - } -} -exports.ZodUnion = ZodUnion; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } - else if (type instanceof ZodLiteral) { - return [type.value]; + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== undefined) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; } - else if (type instanceof ZodEnum) { - return type.options; + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = undefined; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); } - else if (type instanceof ZodNativeEnum) { - return Object.keys(type.enum); + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + // eslint-disable-next-line no-empty + while (this._tryToStartAnother()) { } } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); + get concurrency() { + return this._concurrency; } - else if (type instanceof ZodUndefined) { - return [undefined]; + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); } - else if (type instanceof ZodNull) { - return [null]; + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { + if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return undefined; + }); + resolve(await operation); + } + catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit('add'); + }); } - else { - return null; + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); } -}; -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; } + this._isPaused = false; + this._processQueue(); + return this; } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; } - get optionsMap() { - return this._def.optionsMap; + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); } - static create(discriminator, options, params) { - const optionsMap = new Map(); - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + // Instantly resolve if the queue is empty + if (this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + // Instantly resolve if none pending and if nothing else is queued + if (this._pendingCount === 0 && this._queue.size === 0) { + return; } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), + return new Promise(resolve => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; }); } -} -exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; -function mergeValues(a, b) { - const aType = (0, util_1.getParsedType)(a); - const bType = (0, util_1.getParsedType)(b); - if (a === b) { - return { valid: true, data: a }; + /** + Size of the queue. + */ + get size() { + return this._queue.size; } - else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { - const bKeys = util_1.util.objectKeys(b); - const sharedKeys = util_1.util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + return this._queue.filter(options).length; } - else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; } - else if (aType === util_1.ZodParsedType.date && - bType === util_1.ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; } - else { - return { valid: false }; + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; } } -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { - return parseUtil_1.INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_intersection_types, - }); - return parseUtil_1.INVALID; - } - if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); +exports["default"] = PQueue; + + +/***/ }), + +/***/ 2291: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound +// Used to compute insertion index to keep queue sorted after insertion +function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = (count / 2) | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); + count = step; } } + return first; } -exports.ZodIntersection = ZodIntersection; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); -}; -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (ctx.data.length < this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return parseUtil_1.INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return parseUtil_1.ParseStatus.mergeArray(status, results); - }); - } - else { - return parseUtil_1.ParseStatus.mergeArray(status, items); +exports["default"] = lowerBound; + + +/***/ }), + +/***/ 8492: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lower_bound_1 = __nccwpck_require__(2291); +class PriorityQueue { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; } + const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index, 0, element); } - get items() { - return this._def.items; + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); } -} -exports.ZodTuple = ZodTuple; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + get size() { + return this._queue.length; } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); +} +exports["default"] = PriorityQueue; + + +/***/ }), + +/***/ 2548: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +const retry = __nccwpck_require__(4347); + +const networkErrorMsgs = [ + 'Failed to fetch', // Chrome + 'NetworkError when attempting to fetch resource.', // Firefox + 'The Internet connection appears to be offline.', // Safari + 'Network request failed' // `cross-fetch` +]; + +class AbortError extends Error { + constructor(message) { + super(); + + if (message instanceof Error) { + this.originalError = message; + ({message} = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + + this.name = 'AbortError'; + this.message = message; + } +} + +const decorateErrorWithCounts = (error, attemptNumber, options) => { + // Minus 1 from attemptNumber because the first attempt does not count as a retry + const retriesLeft = options.retries - (attemptNumber - 1); + + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; }; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; + +const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); + +const pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => {}, + retries: 10, + ...options + }; + + const operation = retry.operation(options); + + operation.attempt(async attemptNumber => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + + try { + await options.onFailedAttempt(error); + } catch (error) { + reject(error); + return; + } + + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); +}); + +module.exports = pRetry; +// TODO: remove this in the next major version +module.exports["default"] = pRetry; + +module.exports.AbortError = AbortError; + + +/***/ }), + +/***/ 6424: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const pFinally = __nccwpck_require__(1330); + +class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; + } +} + +const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== 'number' || milliseconds < 0) { + throw new TypeError('Expected `milliseconds` to be a positive number'); + } + + if (milliseconds === Infinity) { + resolve(promise); + return; + } + + const timer = setTimeout(() => { + if (typeof fallback === 'function') { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } + + return; + } + + const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + + if (typeof promise.cancel === 'function') { + promise.cancel(); + } + + reject(timeoutError); + }, milliseconds); + + // TODO: Use native `finally` keyword when targeting Node.js 10 + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); +}); + +module.exports = pTimeout; +// TODO: Remove this for the next major release +module.exports["default"] = pTimeout; + +module.exports.TimeoutError = TimeoutError; + + +/***/ }), + +/***/ 3329: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +var parseUrl = (__nccwpck_require__(7310).parse); + +var DEFAULT_PORTS = { + ftp: 21, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443, +}; + +var stringEndsWith = String.prototype.endsWith || function(s) { + return s.length <= this.length && + this.indexOf(s, this.length - s.length) !== -1; +}; + +/** + * @param {string|object} url - The URL, or the result from url.parse. + * @return {string} The URL of the proxy that should handle the request to the + * given URL. If no proxy is set, this will be an empty string. + */ +function getProxyForUrl(url) { + var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; + var proto = parsedUrl.protocol; + var hostname = parsedUrl.host; + var port = parsedUrl.port; + if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { + return ''; // Don't proxy URLs without a valid scheme or host. + } + + proto = proto.split(':', 1)[0]; + // Stripping ports in this way instead of using parsedUrl.hostname to make + // sure that the brackets around IPv6 addresses are kept. + hostname = hostname.replace(/:\d*$/, ''); + port = parseInt(port) || DEFAULT_PORTS[proto] || 0; + if (!shouldProxy(hostname, port)) { + return ''; // Don't proxy URLs that match NO_PROXY. + } + + var proxy = + getEnv('npm_config_' + proto + '_proxy') || + getEnv(proto + '_proxy') || + getEnv('npm_config_proxy') || + getEnv('all_proxy'); + if (proxy && proxy.indexOf('://') === -1) { + // Missing scheme in proxy, default to the requested URL's scheme. + proxy = proto + '://' + proxy; + } + return proxy; +} + +/** + * Determines whether a given URL should be proxied. + * + * @param {string} hostname - The host name of the URL. + * @param {number} port - The effective port of the URL. + * @returns {boolean} Whether the given URL should be proxied. + * @private + */ +function shouldProxy(hostname, port) { + var NO_PROXY = + (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); + if (!NO_PROXY) { + return true; // Always proxy if NO_PROXY is not set. + } + if (NO_PROXY === '*') { + return false; // Never proxy if wildcard is set. + } + + return NO_PROXY.split(/[,\s]/).every(function(proxy) { + if (!proxy) { + return true; // Skip zero-length hosts. } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - }); - } - if (ctx.common.async) { - return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } + var parsedProxy = proxy.match(/^(.+):(\d+)$/); + var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; + var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; + if (parsedProxyPort && parsedProxyPort !== port) { + return true; // Skip if ports don't match. } - get element() { - return this._def.valueType; + + if (!/^[.*]/.test(parsedProxyHostname)) { + // No wildcards, so stop proxying if there is an exact match. + return hostname !== parsedProxyHostname; } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); + + if (parsedProxyHostname.charAt(0) === '*') { + // Remove leading wildcard. + parsedProxyHostname = parsedProxyHostname.slice(1); } + // Stop proxying if the hostname ends with the no_proxy host. + return !stringEndsWith.call(hostname, parsedProxyHostname); + }); } -exports.ZodRecord = ZodRecord; -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.map) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.map, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } + +/** + * Get the value for an environment variable. + * + * @param {string} key - The name of the environment variable. + * @return {string} The value of the environment variable. + * @private + */ +function getEnv(key) { + return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; } -exports.ZodMap = ZodMap; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); + +exports.getProxyForUrl = getProxyForUrl; + + +/***/ }), + +/***/ 4347: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(6244); + +/***/ }), + +/***/ 6244: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var RetryOperation = __nccwpck_require__(5369); + +exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); }; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.set) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.set, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return parseUtil_1.INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -exports.ZodSet = ZodSet; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); + +exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } + + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); + + return timeouts; }; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; + +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; + + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + + return timeout; +}; + +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); + } } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.function) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.function, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - function makeArgsIssue(args, error) { - return (0, parseUtil_1.makeIssue)({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return (0, parseUtil_1.makeIssue)({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return (0, parseUtil_1.OK)(async function (...args) { - const error = new ZodError_1.ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); + } + + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + + args.push(function(err) { + if (op.retry(err)) { + return; } - else { - const me = this; - return (0, parseUtil_1.OK)(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); + if (err) { + arguments[0] = op.mainError(); } + callback.apply(this, arguments); + }); + + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; + + +/***/ }), + +/***/ 5369: +/***/ ((module) => { + +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; + } + + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } +} +module.exports = RetryOperation; + +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); +} + +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + + this._timeouts = []; + this._cachedTimeouts = null; +}; + +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + + if (!err) { + return false; + } + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; + } + + this._errors.push(err); + + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); + } + + var self = this; + this._timer = setTimeout(function() { + self._attempts++; + + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); + + if (self._options.unref) { + self._timeout.unref(); + } } -} -exports.ZodFunction = ZodFunction; -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); + + self._fn(self._attempts); + }, timeout); + + if (this._options.unref) { + this._timer.unref(); + } + + return true; +}; + +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; } -} -exports.ZodLazy = ZodLazy; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); + } + + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } + + this._operationStart = new Date().getTime(); + + this._fn(this._attempts); }; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; + +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; + +RetryOperation.prototype.start = RetryOperation.prototype.try; + +RetryOperation.prototype.errors = function() { + return this._errors; +}; + +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; + +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; } -} -exports.ZodLiteral = ZodLiteral; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); + } + + return mainError; }; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); + + +/***/ }), + +/***/ 9318: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +const os = __nccwpck_require__(2037); +const tty = __nccwpck_require__(6224); +const hasFlag = __nccwpck_require__(1621); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; } -class ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (this._def.values.indexOf(input.data) === -1) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values) { - return ZodEnum.create(values); - } - exclude(values) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); - } + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } } -exports.ZodEnum = ZodEnum; -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - _parse(input) { - const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== util_1.ZodParsedType.string && - ctx.parsedType !== util_1.ZodParsedType.number) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (nativeEnumValues.indexOf(input.data) === -1) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get enum() { - return this._def.values; - } + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; } -exports.ZodNativeEnum = ZodNativeEnum; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.promise && - ctx.common.async === false) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.promise, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const promisified = ctx.parsedType === util_1.ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return (0, parseUtil_1.OK)(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; } -exports.ZodPromise = ZodPromise; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) }; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; + + +/***/ }), + +/***/ 4256: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +var punycode = __nccwpck_require__(5477); +var mappingTable = __nccwpck_require__(2020); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - (0, parseUtil_1.addIssueToContext)(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.issues.length) { - return { - status: "dirty", - value: ctx.data, - }; - } - if (ctx.common.async) { - return Promise.resolve(processed).then((processed) => { - return this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - }); - } - else { - return this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!(0, parseUtil_1.isValid)(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!(0, parseUtil_1.isValid)(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); - } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; } - util_1.util.assertNever(effect); + + processed += String.fromCodePoint(codePoint); + break; } + } + + return { + string: processed, + error: hasError + }; } -exports.ZodEffects = ZodEffects; -exports.ZodTransformer = ZodEffects; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.undefined) { - return (0, parseUtil_1.OK)(undefined); - } - return this._def.innerType._parse(input); + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; } - unwrap() { - return this._def.innerType; + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; } + } + + return { + string: labels.join("."), + error: result.error + }; } -exports.ZodOptional = ZodOptional; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.null) { - return (0, parseUtil_1.OK)(null); - } - return this._def.innerType._parse(input); + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; } - unwrap() { - return this._def.innerType; + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; } -} -exports.ZodNullable = ZodNullable; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === util_1.ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } } - removeDefault() { - return this._def.innerType; + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; + + +/***/ }), + +/***/ 4294: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(4219); + + +/***/ }), + +/***/ 4219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +var net = __nccwpck_require__(1808); +var tls = __nccwpck_require__(4404); +var http = __nccwpck_require__(3685); +var https = __nccwpck_require__(5687); +var events = __nccwpck_require__(2361); +var assert = __nccwpck_require__(9491); +var util = __nccwpck_require__(3837); + + +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + + +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } } + socket.destroy(); + self.removeSocket(socket); + }); } -exports.ZodDefault = ZodDefault; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if ((0, parseUtil_1.isAsync)(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } +util.inherits(TunnelingAgent, events.EventEmitter); + +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); + + function onFree() { + self.emit('free', socket, options); } - removeCatch() { - return this._def.innerType; + + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); } -} -exports.ZodCatch = ZodCatch; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); + }); }; -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.nan, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } + + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; } -} -exports.ZodNaN = ZodNaN; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); + + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); }); + } }; -exports.BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } + +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); } -exports.ZodBranded = ZodBranded; -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return (0, parseUtil_1.DIRTY)(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } + + +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; } + } } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } + } + return target; } -exports.ZodPipeline = ZodPipeline; -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - if ((0, parseUtil_1.isValid)(result)) { - result.value = Object.freeze(result.value); - } - return result; + + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); } + console.error.apply(console, args); + } +} else { + debug = function() {}; } -exports.ZodReadonly = ZodReadonly; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -const custom = (check, params = {}, fatal) => { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - if (!check(data)) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - const p2 = typeof p === "string" ? { message: p } : p; - ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); - } - }); - return ZodAny.create(); -}; -exports.custom = custom; -exports.late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); -class Class { - constructor(..._) { } +exports.debug = debug; // for test + + +/***/ }), + +/***/ 5030: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + + if (typeof process === "object" && "version" in process) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + + return ""; } -const instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}`, -}) => (0, exports.custom)((data) => data instanceof cls, params); -exports["instanceof"] = instanceOfType; -const stringType = ZodString.create; -exports.string = stringType; -const numberType = ZodNumber.create; -exports.number = numberType; -const nanType = ZodNaN.create; -exports.nan = nanType; -const bigIntType = ZodBigInt.create; -exports.bigint = bigIntType; -const booleanType = ZodBoolean.create; -exports.boolean = booleanType; -const dateType = ZodDate.create; -exports.date = dateType; -const symbolType = ZodSymbol.create; -exports.symbol = symbolType; -const undefinedType = ZodUndefined.create; -exports.undefined = undefinedType; -const nullType = ZodNull.create; -exports["null"] = nullType; -const anyType = ZodAny.create; -exports.any = anyType; -const unknownType = ZodUnknown.create; -exports.unknown = unknownType; -const neverType = ZodNever.create; -exports.never = neverType; -const voidType = ZodVoid.create; -exports["void"] = voidType; -const arrayType = ZodArray.create; -exports.array = arrayType; -const objectType = ZodObject.create; -exports.object = objectType; -const strictObjectType = ZodObject.strictCreate; -exports.strictObject = strictObjectType; -const unionType = ZodUnion.create; -exports.union = unionType; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -exports.discriminatedUnion = discriminatedUnionType; -const intersectionType = ZodIntersection.create; -exports.intersection = intersectionType; -const tupleType = ZodTuple.create; -exports.tuple = tupleType; -const recordType = ZodRecord.create; -exports.record = recordType; -const mapType = ZodMap.create; -exports.map = mapType; -const setType = ZodSet.create; -exports.set = setType; -const functionType = ZodFunction.create; -exports["function"] = functionType; -const lazyType = ZodLazy.create; -exports.lazy = lazyType; -const literalType = ZodLiteral.create; -exports.literal = literalType; -const enumType = ZodEnum.create; -exports["enum"] = enumType; -const nativeEnumType = ZodNativeEnum.create; -exports.nativeEnum = nativeEnumType; -const promiseType = ZodPromise.create; -exports.promise = promiseType; -const effectsType = ZodEffects.create; -exports.effect = effectsType; -exports.transformer = effectsType; -const optionalType = ZodOptional.create; -exports.optional = optionalType; -const nullableType = ZodNullable.create; -exports.nullable = nullableType; -const preprocessType = ZodEffects.createWithPreprocess; -exports.preprocess = preprocessType; -const pipelineType = ZodPipeline.create; -exports.pipeline = pipelineType; -const ostring = () => stringType().optional(); -exports.ostring = ostring; -const onumber = () => numberType().optional(); -exports.onumber = onumber; -const oboolean = () => booleanType().optional(); -exports.oboolean = oboolean; -exports.coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; -exports.NEVER = parseUtil_1.INVALID; +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 5840: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "v1", ({ + enumerable: true, + get: function () { + return _v.default; + } +})); +Object.defineProperty(exports, "v3", ({ + enumerable: true, + get: function () { + return _v2.default; + } +})); +Object.defineProperty(exports, "v4", ({ + enumerable: true, + get: function () { + return _v3.default; + } +})); +Object.defineProperty(exports, "v5", ({ + enumerable: true, + get: function () { + return _v4.default; + } +})); +Object.defineProperty(exports, "NIL", ({ + enumerable: true, + get: function () { + return _nil.default; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.default; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.default; + } +})); +Object.defineProperty(exports, "stringify", ({ + enumerable: true, + get: function () { + return _stringify.default; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parse.default; + } +})); + +var _v = _interopRequireDefault(__nccwpck_require__(8628)); + +var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); + +var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); + +var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); + +var _nil = _interopRequireDefault(__nccwpck_require__(5332)); + +var _version = _interopRequireDefault(__nccwpck_require__(1595)); + +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); + +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); + +var _parse = _interopRequireDefault(__nccwpck_require__(2746)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/***/ }), + +/***/ 4569: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports["default"] = _default; + +/***/ }), + +/***/ 5332: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports["default"] = _default; + +/***/ }), + +/***/ 2746: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ -/***/ }), + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ -/***/ 2877: -/***/ ((module) => { + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ -module.exports = eval("require")("encoding"); + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} +var _default = parse; +exports["default"] = _default; /***/ }), -/***/ 9491: -/***/ ((module) => { +/***/ 814: +/***/ ((__unused_webpack_module, exports) => { -module.exports = require("assert"); + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = /^(?:[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; +exports["default"] = _default; /***/ }), -/***/ 6113: -/***/ ((module) => { +/***/ 807: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = require("crypto"); -/***/ }), -/***/ 2361: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; -module.exports = require("events"); +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); -/***/ }), +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ 7147: -/***/ ((module) => { +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -module.exports = require("fs"); +let poolPtr = rnds8Pool.length; -/***/ }), +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); -/***/ 3685: -/***/ ((module) => { + poolPtr = 0; + } -module.exports = require("http"); + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} /***/ }), -/***/ 5687: -/***/ ((module) => { +/***/ 5274: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = require("https"); -/***/ }), -/***/ 1808: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -module.exports = require("net"); +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); -/***/ }), +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ 2037: -/***/ ((module) => { +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} -module.exports = require("os"); +var _default = sha1; +exports["default"] = _default; /***/ }), -/***/ 1017: -/***/ ((module) => { +/***/ 8950: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = require("path"); -/***/ }), -/***/ 5477: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -module.exports = require("punycode"); +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); -/***/ }), +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ 2781: -/***/ ((module) => { +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; -module.exports = require("stream"); +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} -/***/ }), +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (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]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields -/***/ 4404: -/***/ ((module) => { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} -module.exports = require("tls"); +var _default = stringify; +exports["default"] = _default; /***/ }), -/***/ 6224: -/***/ ((module) => { +/***/ 8628: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty"); -/***/ }), -/***/ 7310: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -module.exports = require("url"); +var _rng = _interopRequireDefault(__nccwpck_require__(807)); -/***/ }), +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); -/***/ 3837: -/***/ ((module) => { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = require("util"); +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; -/***/ }), +let _clockseq; // Previous uuid creation time -/***/ 1267: -/***/ ((module) => { -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.default)(b); +} + +var _default = v1; +exports["default"] = _default; /***/ }), -/***/ 9796: -/***/ ((module) => { +/***/ 6409: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(5998)); + +var _md = _interopRequireDefault(__nccwpck_require__(4569)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = require("zlib"); +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports["default"] = _default; /***/ }), -/***/ 8393: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 5998: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "F1": () => (/* binding */ calculateMaxTokens), -/* harmony export */ "_i": () => (/* binding */ getModelNameForTiktoken) -/* harmony export */ }); -/* unused harmony exports getEmbeddingContextSize, getModelContextSize */ -/* harmony import */ var _util_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(7573); -// https://www.npmjs.com/package/js-tiktoken -const getModelNameForTiktoken = (modelName) => { - if (modelName.startsWith("gpt-3.5-turbo-16k")) { - return "gpt-3.5-turbo-16k"; - } - if (modelName.startsWith("gpt-3.5-turbo-")) { - return "gpt-3.5-turbo"; - } - if (modelName.startsWith("gpt-4-32k")) { - return "gpt-4-32k"; - } - if (modelName.startsWith("gpt-4-")) { - return "gpt-4"; - } - return modelName; -}; -const getEmbeddingContextSize = (modelName) => { - switch (modelName) { - case "text-embedding-ada-002": - return 8191; - default: - return 2046; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = _default; +exports.URL = exports.DNS = void 0; + +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); + +var _parse = _interopRequireDefault(__nccwpck_require__(2746)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); } -}; -const getModelContextSize = (modelName) => { - switch (getModelNameForTiktoken(modelName)) { - case "gpt-3.5-turbo-16k": - return 16384; - case "gpt-3.5-turbo": - return 4096; - case "gpt-4-32k": - return 32768; - case "gpt-4": - return 8192; - case "text-davinci-003": - return 4097; - case "text-curie-001": - return 2048; - case "text-babbage-001": - return 2048; - case "text-ada-001": - return 2048; - case "code-davinci-002": - return 8000; - case "code-cushman-001": - return 2048; - default: - return 4097; + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); } -}; -const calculateMaxTokens = async ({ prompt, modelName, }) => { - let numTokens; - try { - numTokens = (await (0,_util_tiktoken_js__WEBPACK_IMPORTED_MODULE_0__/* .encodingForModel */ .b)(getModelNameForTiktoken(modelName))).encode(prompt).length; + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count"); - // fallback to approximate calculation if tiktoken is not available - // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# - numTokens = Math.ceil(prompt.length / 4); + + return (0, _stringify.default)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} + +/***/ }), + +/***/ 5122: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _rng = _interopRequireDefault(__nccwpck_require__(807)); + +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; } - const maxTokens = getModelContextSize(modelName); - return maxTokens - numTokens; -}; + return buf; + } + + return (0, _stringify.default)(rnds); +} + +var _default = v4; +exports["default"] = _default; + +/***/ }), + +/***/ 9120: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(5998)); + +var _sha = _interopRequireDefault(__nccwpck_require__(5274)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports["default"] = _default; + +/***/ }), + +/***/ 6900: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _regex = _interopRequireDefault(__nccwpck_require__(814)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports["default"] = _default; + +/***/ }), + +/***/ 1595: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +var _default = version; +exports["default"] = _default; /***/ }), -/***/ 7679: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 5650: +/***/ (function(__unused_webpack_module, exports) { +/** + * @license + * web-streams-polyfill v4.0.0-beta.3 + * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){ true?t(exports):0}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}function o(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=r;function a(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const i=Promise,l=Promise.prototype.then,s=Promise.resolve.bind(i),u=Promise.reject.bind(i);function c(e){return new i(e)}function d(e){return s(e)}function f(e){return u(e)}function b(e,t,r){return l.call(e,t,r)}function h(e,t,r){b(b(e,t,r),void 0,n)}function _(e,t){h(e,t)}function p(e,t){h(e,void 0,t)}function m(e,t,r){return b(e,t,r)}function y(e){b(e,void 0,n)}let g=e=>{if("function"==typeof queueMicrotask)g=queueMicrotask;else{const e=d(void 0);g=t=>b(e,t)}return g(e)};function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return d(S(e,t,r))}catch(e){return f(e)}}class v{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const R=t("[[AbortSteps]]"),T=t("[[ErrorSteps]]"),q=t("[[CancelSteps]]"),C=t("[[PullSteps]]"),P=t("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?B(e):"closed"===t._state?function(e){B(e),z(e)}(e):A(e,t._storedError)}function W(e,t){return Xt(e._ownerReadableStream,t)}function O(e){const t=e._ownerReadableStream;"readable"===t._state?j(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){A(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[P](),t._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function B(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function A(e,t){B(e),j(e,t)}function j(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function z(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const L=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},F=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function D(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function $(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function Y(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Q(e){return Number(e)}function N(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=N(o),!L(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return N(F(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return L(o)&&0!==o?o:0}function H(e){if(!o(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e){if(!o(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function U(e,t){if(!Ut(e))throw new TypeError(`${t} is not a ReadableStream.`)}function G(e,t){e._reader._readRequests.push(t)}function X(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function J(e){return e._reader._readRequests.length}function K(e){const t=e._reader;return void 0!==t&&!!Z(t)}class ReadableStreamDefaultReader{constructor(e){if(M(e,1,"ReadableStreamDefaultReader"),U(e,"First parameter"),Gt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new v}get closed(){return Z(this)?this._closedPromise:f(te("closed"))}cancel(e){return Z(this)?void 0===this._ownerReadableStream?f(k("cancel")):W(this,e):f(te("cancel"))}read(){if(!Z(this))return f(te("read"));if(void 0===this._ownerReadableStream)return f(k("read from"));let e,t;const r=c(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[C](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!Z(this))throw te("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);const t=new TypeError("Reader was released");ee(e,t)}(this)}}function Z(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function ee(e,t){const r=e._readRequests;e._readRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function te(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamDefaultReader.prototype.cancel,"cancel"),a(ReadableStreamDefaultReader.prototype.read,"read"),a(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class re{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?m(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?m(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?f(k("iterate")):b(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return f(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),m(r,(()=>({value:e,done:!0})))}return t.releaseLock(),d({value:e,done:!0})}}const oe={next(){return ne(this)?this._asyncIteratorImpl.next():f(ae("next"))},return(e){return ne(this)?this._asyncIteratorImpl.return(e):f(ae("return"))}};function ne(e){if(!o(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof re}catch(e){return!1}}function ae(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof t.asyncIterator&&Object.defineProperty(oe,t.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ie=Number.isNaN||function(e){return e!=e};function le(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function se(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return le(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ue(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ce(e,t,r){if("number"!=typeof(o=r)||ie(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function de(e){e._queue=new v,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!be(this))throw Ae("view");return this._view}respond(e){if(!be(this))throw Ae("respond");if(M(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,Ce(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!be(this))throw Ae("respondWithNewView");if(M(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,Ce(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),a(ReadableStreamBYOBRequest.prototype.respond,"respond"),a(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!fe(this))throw je("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!fe(this))throw je("desiredSize");return ke(this)}close(){if(!fe(this))throw je("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw We(e,t),t}}Ee(e),Jt(t)}(this)}enqueue(e){if(!fe(this))throw je("enqueue");if(M(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Te(e),t.buffer=t.buffer,"none"===t.readerType&&Se(e,t)}if(K(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Oe(e,t._readRequests.shift())}}(e),0===J(r))ye(e,i,n,a);else{e._pendingPullIntos.length>0&&Pe(e);X(r,new Uint8Array(i,n,a),!1)}else Fe(r)?(ye(e,i,n,a),qe(e)):ye(e,i,n,a);he(e)}(this,e)}error(e){if(!fe(this))throw je("error");We(this,e)}[q](e){_e(this),de(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[C](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Oe(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}G(t,e),he(this)}[P](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new v,this._pendingPullIntos.push(e)}}}function fe(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function be(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function he(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(K(t)&&J(t)>0)return!0;if(Fe(t)&&Le(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,he(e)),null)),(t=>(We(e,t),null)))}function _e(e){Te(e),e._pendingPullIntos=new v}function pe(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=me(t);"default"===t.readerType?X(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function me(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function ye(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ge(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw We(e,t),t}ye(e,n,0,o)}function Se(e,t){t.bytesFilled>0&&ge(e,t.buffer,t.byteOffset,t.bytesFilled),Pe(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;le(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,ve(e,o,t),l-=o}return s}function ve(e,t,r){r.bytesFilled+=t}function Re(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Jt(e._controlledReadableByteStream)):he(e)}function Te(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function qe(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Pe(e),pe(e._controlledReadableByteStream,t))}}function Ce(e,t){const r=e._pendingPullIntos.peek();Te(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Pe(e);const r=e._controlledReadableByteStream;if(Fe(r))for(;Le(r)>0;)pe(r,Pe(e))}(e,r):function(e,t,r){if(ve(0,t,r),"none"===r.readerType)return Se(e,r),void qe(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ge(e,r.buffer,t-o,o)}r.bytesFilled-=o,pe(e._controlledReadableByteStream,r),qe(e)}(e,t,r),he(e)}function Pe(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function We(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(_e(e),de(e),Ee(e),Kt(r,t))}function Oe(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Re(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Be(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>d(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>d(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,de(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new v,e._readableStreamController=t,h(d(r()),(()=>(t._started=!0,he(t),null)),(e=>(We(t,e),null)))}(e,o,n,a,i,r,l)}function Ae(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function je(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function ze(e,t){e._reader._readIntoRequests.push(t)}function Le(e){return e._reader._readIntoRequests.length}function Fe(e){const t=e._reader;return void 0!==t&&!!De(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableByteStreamController.prototype.close,"close"),a(ReadableByteStreamController.prototype.enqueue,"enqueue"),a(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if(M(e,1,"ReadableStreamBYOBReader"),U(e,"First parameter"),Gt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!fe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new v}get closed(){return De(this)?this._closedPromise:f($e("closed"))}cancel(e){return De(this)?void 0===this._ownerReadableStream?f(k("cancel")):W(this,e):f($e("cancel"))}read(e){if(!De(this))return f($e("read"));if(!ArrayBuffer.isView(e))return f(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return f(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return f(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return f(k("read from"));let t,r;const o=c(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void ze(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=me(l);return Re(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return We(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),ze(o,r),he(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!De(this))throw $e("releaseLock");void 0!==this._ownerReadableStream&&function(e){O(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function De(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function $e(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function Me(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Ye(e){const{size:t}=e;return t||(()=>1)}function Qe(e,t){D(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Q(r),size:void 0===o?void 0:Ne(o,`${t} has member 'size' that`)}}function Ne(e,t){return I(e,t),t=>Q(e(t))}function xe(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function Ve(e,t,r){return I(e,r),r=>S(e,t,[r])}function Ue(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamBYOBReader.prototype.cancel,"cancel"),a(ReadableStreamBYOBReader.prototype.read,"read"),a(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ge="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:$(e,"First parameter");const r=Qe(t,"Second parameter"),o=function(e,t){D(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:xe(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:Ve(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ue(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new v,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Ye(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>d(void 0);l=void 0!==t.close?()=>t.close():()=>d(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>d(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,de(t),t._abortReason=void 0,t._abortController=function(){if(Ge)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=ht(t);at(e,s);const u=r();h(d(u),(()=>(t._started=!0,ft(t),null)),(r=>(t._started=!0,et(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,Me(r,1),a)}get locked(){if(!Xe(this))throw pt("locked");return Je(this)}abort(e){return Xe(this)?Je(this)?f(new TypeError("Cannot abort a stream that already has a writer")):Ke(this,e):f(pt("abort"))}close(){return Xe(this)?Je(this)?f(new TypeError("Cannot close a stream that already has a writer")):ot(this)?f(new TypeError("Cannot close an already-closing stream")):Ze(this):f(pt("close"))}getWriter(){if(!Xe(this))throw pt("getWriter");return new WritableStreamDefaultWriter(this)}}function Xe(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Je(e){return void 0!==e._writer}function Ke(e,t){var r;if("closed"===e._state||"errored"===e._state)return d(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return d(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=c(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||tt(e,t),a}function Ze(e){const t=e._state;if("closed"===t||"errored"===t)return f(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=c(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ce(n=e._writableStreamController,st,0),ft(n),r}function et(e,t){"writable"!==e._state?rt(e):tt(e,t)}function tt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&<(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&rt(e)}function rt(e){e._state="errored",e._writableStreamController[T]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new v,void 0===e._pendingAbortRequest)return void nt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void nt(e);h(e._writableStreamController[R](r._reason),(()=>(r._resolve(),nt(e),null)),(t=>(r._reject(t),nt(e),null)))}function ot(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function nt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&vt(t,e._storedError)}function at(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Tt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),a(WritableStream.prototype.abort,"abort"),a(WritableStream.prototype.close,"close"),a(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if(M(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Xe(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Je(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!ot(e)&&e._backpressure?Tt(this):Ct(this),St(this);else if("erroring"===t)qt(this,e._storedError),St(this);else if("closed"===t)Ct(this),St(r=this),Rt(r);else{const t=e._storedError;qt(this,t),wt(this,t)}var r}get closed(){return it(this)?this._closedPromise:f(yt("closed"))}get desiredSize(){if(!it(this))throw yt("desiredSize");if(void 0===this._ownerWritableStream)throw gt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return dt(t._writableStreamController)}(this)}get ready(){return it(this)?this._readyPromise:f(yt("ready"))}abort(e){return it(this)?void 0===this._ownerWritableStream?f(gt("abort")):function(e,t){return Ke(e._ownerWritableStream,t)}(this,e):f(yt("abort"))}close(){if(!it(this))return f(yt("close"));const e=this._ownerWritableStream;return void 0===e?f(gt("close")):ot(e)?f(new TypeError("Cannot close an already-closing stream")):Ze(this._ownerWritableStream)}releaseLock(){if(!it(this))throw yt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");lt(e,r),function(e,t){"pending"===e._closedPromiseState?vt(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return it(this)?void 0===this._ownerWritableStream?f(gt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return bt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return f(gt("write to"));const a=r._state;if("errored"===a)return f(r._storedError);if(ot(r)||"closed"===a)return f(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return f(r._storedError);const i=function(e){return c(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ce(e,t,r)}catch(t){return void bt(e,t)}const o=e._controlledWritableStream;if(!ot(o)&&"writable"===o._state){at(o,ht(e))}ft(e)}(o,t,n),i}(this,e):f(yt("write"))}}function it(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function lt(e,t){"pending"===e._readyPromiseState?Pt(e,t):function(e,t){qt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),a(WritableStreamDefaultWriter.prototype.abort,"abort"),a(WritableStreamDefaultWriter.prototype.close,"close"),a(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),a(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const st={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!ut(this))throw mt("abortReason");return this._abortReason}get signal(){if(!ut(this))throw mt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!ut(this))throw mt("error");"writable"===this._controlledWritableStream._state&&_t(this,e)}[R](e){const t=this._abortAlgorithm(e);return ct(this),t}[T](){de(this)}}function ut(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ct(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function dt(e){return e._strategyHWM-e._queueTotalSize}function ft(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void rt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===st?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ue(e);const r=e._closeAlgorithm();ct(e),h(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Rt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),et(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);h(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ue(e),!ot(r)&&"writable"===t){const t=ht(e);at(r,t)}return ft(e),null}),(t=>("writable"===r._state&&ct(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,et(e,t)}(r,t),null)))}(e,r)}function bt(e,t){"writable"===e._controlledWritableStream._state&&_t(e,t)}function ht(e){return dt(e)<=0}function _t(e,t){const r=e._controlledWritableStream;ct(e),tt(r,t)}function pt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function mt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function yt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function gt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function St(e){e._closedPromise=c(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function wt(e,t){St(e),vt(e,t)}function vt(e,t){void 0!==e._closedPromise_reject&&(y(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Rt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Tt(e){e._readyPromise=c(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function qt(e,t){Tt(e),Pt(e,t)}function Ct(e){Tt(e),Et(e)}function Pt(e,t){void 0!==e._readyPromise_reject&&(y(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Wt="undefined"!=typeof DOMException?DOMException:void 0;const Ot=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Wt)?Wt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Ut(e)&&(e._disturbed=!0);let s,u,p,S=!1,w=!1,v="readable",R="writable",T=!1,q=!1;const C=c((e=>{p=e}));let P=Promise.resolve(void 0);return c(((E,W)=>{let O;function k(){if(S)return;const e=c(((e,t)=>{!function r(o){o?e():b(function(){if(S)return d(!0);return b(l.ready,(()=>b(i.read(),(e=>!!e.done||(P=l.write(e.value),y(P),!1)))))}(),r,t)}(!1)}));y(e)}function B(){return v="closed",r?L():z((()=>(Xe(t)&&(T=ot(t),R=t._state),T||"closed"===R?d(void 0):"erroring"===R||"errored"===R?f(u):(T=!0,l.close()))),!1,void 0),null}function A(e){return S||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return w||(R="errored",u=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(O=()=>{const e=void 0!==a.reason?a.reason:new Ot("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):d(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):d(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?O():a.addEventListener("abort",O)),Ut(e)&&(v=e._state,s=e._storedError),Xe(t)&&(R=t._state,u=t._storedError,T=ot(t)),Ut(e)&&Xe(t)&&(q=!0,p()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(u);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():_(function(){let e;return d(function t(){if(e!==P)return e=P,m(P,t,t)}())}(),n),null}function n(){return e?h(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}S||(S=!0,q?o():_(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return w=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",O),e?W(t):E(void 0),null}S||(h(i.closed,B,A),h(l.closed,(function(){return w||(R="closed"),null}),j)),q?k():g((()=>{q=!0,p(),k()}))}))}function Bt(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,u=!1,f=!1,b=!1,_=!1;const m=c((e=>{a=e}));function y(e){p(e.closed,(t=>(e!==i||(o.error(t),n.error(t),b&&_||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),h(i.read(),(e=>{var t,r;if(u=!1,f=!1,e.done)return b||o.close(),_||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),b&&_||a(void 0),null;const l=e.value,c=l;let d=l;if(!b&&!_)try{d=se(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return b||o.enqueue(c),_||n.enqueue(d),s=!1,u?w():f&&v(),null}),(()=>(s=!1,null)))}function S(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const c=r?n:o,d=r?o:n;h(i.read(t),(e=>{var t;u=!1,f=!1;const o=r?_:b,n=r?b:_;if(e.done){o||c.close(),n||d.close();const r=e.value;return void 0!==r&&(o||c.byobRequest.respondWithNewView(r),n||null===(t=d.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||c.byobRequest.respondWithNewView(l);else{let e;try{e=se(l)}catch(e){return c.error(e),d.error(e),a(i.cancel(e)),null}o||c.byobRequest.respondWithNewView(l),d.enqueue(e)}return s=!1,u?w():f&&v(),null}),(()=>(s=!1,null)))}function w(){if(s)return u=!0,d(void 0);s=!0;const e=o.byobRequest;return null===e?g():S(e.view,!1),d(void 0)}function v(){if(s)return f=!0,d(void 0);s=!0;const e=n.byobRequest;return null===e?g():S(e.view,!0),d(void 0)}function R(e){if(b=!0,t=e,_){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(_=!0,r=e,b){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:w,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,u=!1,f=!1,b=!1;const _=c((e=>{l=e}));function m(){return s?(u=!0,d(void 0)):(s=!0,h(r.read(),(e=>{if(u=!1,e.done)return f||a.close(),b||i.close(),f&&b||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),b||i.enqueue(o),s=!1,u&&m(),null}),(()=>(s=!1,null))),d(void 0))}function y(e){if(f=!0,o=e,b){const e=[o,n],t=r.cancel(e);l(t)}return _}function g(e){if(b=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return _}const S=new ReadableStream({start(e){a=e},pull:m,cancel:y}),w=new ReadableStream({start(e){i=e},pull:m,cancel:g});return p(r.closed,(e=>(a.error(e),i.error(e),f&&b||l(void 0),null))),[S,w]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!At(this))throw $t("desiredSize");return Ft(this)}close(){if(!At(this))throw $t("close");if(!Dt(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Dt(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(zt(e),Jt(t))}(this)}enqueue(e){if(!At(this))throw $t("enqueue");if(!Dt(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Dt(e))return;const r=e._controlledReadableStream;if(Gt(r)&&J(r)>0)X(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Lt(e,t),t}try{ce(e,t,r)}catch(t){throw Lt(e,t),t}}jt(e)}(this,e)}error(e){if(!At(this))throw $t("error");Lt(this,e)}[q](e){de(this);const t=this._cancelAlgorithm(e);return zt(this),t}[C](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ue(this);this._closeRequested&&0===this._queue.length?(zt(this),Jt(t)):jt(this),e._chunkSteps(r)}else G(t,e),jt(this)}[P](){}}function At(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function jt(e){const t=function(e){const t=e._controlledReadableStream;if(!Dt(e))return!1;if(!e._started)return!1;if(Gt(t)&&J(t)>0)return!0;if(Ft(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;h(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,jt(e)),null)),(t=>(Lt(e,t),null)))}function zt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Lt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(de(e),zt(e),Kt(r,t))}function Ft(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Dt(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>d(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>d(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,de(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,h(d(r()),(()=>(t._started=!0,jt(t),null)),(e=>(Lt(t,e),null)))}(e,n,a,i,l,r,o)}function $t(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Qt(e,t,r){return I(e,r),r=>S(e,t,[r])}function Nt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function xt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){D(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function Vt(e,t){D(e,t);const r=null==e?void 0:e.readable;Y(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return Y(o,"writable","ReadableWritablePair"),function(e,t){if(!V(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableStreamDefaultController.prototype.close,"close"),a(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),a(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:$(e,"First parameter");const r=Qe(t,"Second parameter"),o=function(e,t){D(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:Mt(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Yt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Qt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Nt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Be(this,o,Me(r,0))}else{const e=Ye(r);It(this,o,Me(r,1),e)}}get locked(){if(!Ut(this))throw Zt("locked");return Gt(this)}cancel(e){return Ut(this)?Gt(this)?f(new TypeError("Cannot cancel a stream that already has a reader")):Xt(this,e):f(Zt("cancel"))}getReader(e){if(!Ut(this))throw Zt("getReader");return void 0===function(e,t){D(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:xt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Zt("pipeThrough");M(e,1,"pipeThrough");const r=Vt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return y(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return f(Zt("pipeTo"));if(void 0===e)return f("Parameter 1 is required in 'pipeTo'.");if(!V(e))return f(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return f(e)}return this.locked?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?f(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Zt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Bt(this)}values(e){if(!H(this))throw Zt("values");return function(e,t){const r=e.getReader(),o=new re(r,t),n=Object.create(oe);return n._asyncIteratorImpl=o,n}(this,function(e,t){D(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Ut(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Gt(e){return void 0!==e._reader}function Xt(e,t){if(e._disturbed=!0,"closed"===e._state)return d(void 0);if("errored"===e._state)return f(e._storedError);Jt(e);const o=e._reader;if(void 0!==o&&De(o)){const e=o._readIntoRequests;o._readIntoRequests=new v,e.forEach((e=>{e._closeSteps(void 0)}))}return m(e._readableStreamController[q](t),r)}function Jt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(z(t),Z(t))){const e=t._readRequests;t._readRequests=new v,e.forEach((e=>{e._closeSteps()}))}}function Kt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(j(r,t),Z(r)?ee(r,t):Ie(r,t))}function Zt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function er(e,t){D(e,t);const r=null==e?void 0:e.highWaterMark;return Y(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Q(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),a(ReadableStream.prototype.cancel,"cancel"),a(ReadableStream.prototype.getReader,"getReader"),a(ReadableStream.prototype.pipeThrough,"pipeThrough"),a(ReadableStream.prototype.pipeTo,"pipeTo"),a(ReadableStream.prototype.tee,"tee"),a(ReadableStream.prototype.values,"values"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const tr=e=>e.byteLength;a(tr,"size");class ByteLengthQueuingStrategy{constructor(e){M(e,1,"ByteLengthQueuingStrategy"),e=er(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!or(this))throw rr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!or(this))throw rr("size");return tr}}function rr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function or(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const nr=()=>1;a(nr,"size");class CountQueuingStrategy{constructor(e){M(e,1,"CountQueuingStrategy"),e=er(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ir(this))throw ar("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ir(this))throw ar("size");return nr}}function ar(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ir(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function lr(e,t,r){return I(e,r),r=>w(e,t,[r])}function sr(e,t,r){return I(e,r),r=>S(e,t,[r])}function ur(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Qe(t,"Second parameter"),n=Qe(r,"Third parameter"),a=function(e,t){D(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:lr(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:sr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:ur(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=Me(n,0),l=Ye(n),s=Me(o,1),u=Ye(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return m(e._backpressureChangePromise,(()=>{if("erroring"===(Xe(e._writable)?e._writable._state:e._writableState))throw Xe(e._writable)?e._writable._storedError:e._writableStoredError;return mr(r,t)}))}return mr(r,t)}(e,t)}function s(t){return function(e,t){return dr(e,t),d(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return _r(t),m(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;Sr(e)&&wr(e)}),(t=>{throw dr(e,t),e._readableStoredError}))}(e)}function c(){return function(e){return br(e,!1),e._backpressureChangePromise}(e)}function f(t){return fr(e,t),d(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return m(t(),(()=>(e._writableStarted=!0,Pr(e),null)),(t=>{throw e._writableStarted=!0,Tr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),m(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Pr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Tr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),m(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Tr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{vr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{vr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,c,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,br(e,!0),e._transformStreamController=void 0}(this,c((e=>{b=e})),s,u,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return pr(r,e),d(void 0)}catch(e){return f(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>d(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!cr(this))throw gr("readable");return this._readable}get writable(){if(!cr(this))throw gr("writable");return this._writable}}function cr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function dr(e,t){vr(e,t),fr(e,t)}function fr(e,t){_r(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&qr(e,t)}(e,t),e._backpressure&&br(e,!1)}function br(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=c((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!hr(this))throw yr("desiredSize");return Rr(this._controlledTransformStream)}enqueue(e){if(!hr(this))throw yr("enqueue");pr(this,e)}error(e){if(!hr(this))throw yr("error");var t;t=e,dr(this._controlledTransformStream,t)}terminate(){if(!hr(this))throw yr("terminate");!function(e){const t=e._controlledTransformStream;Sr(t)&&wr(t);const r=new TypeError("TransformStream terminated");fr(t,r)}(this)}}function hr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function _r(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function pr(e,t){const r=e._controlledTransformStream;if(!Sr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw vr(e,t),t}}(r,t)}catch(e){throw fr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!Sr(e))return!1;if(e._readablePulling)return!0;if(Rr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&br(r,!0)}function mr(e,t){return m(e._transformAlgorithm(t),void 0,(t=>{throw dr(e._controlledTransformStream,t),t}))}function yr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function gr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function Sr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function vr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function Rr(e){return e._readableController.desiredSize}function Tr(e,t){"writable"!==e._writableState?Cr(e):qr(e,t)}function qr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&Cr(e)}function Cr(e){e._writableState="errored"}function Pr(e){"erroring"===e._writableState&&Cr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),a(TransformStreamDefaultController.prototype.enqueue,"enqueue"),a(TransformStreamDefaultController.prototype.error,"error"),a(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}),e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter,Object.defineProperty(e,"__esModule",{value:!0})})); -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "BD": () => (/* binding */ BaseLangChain), - "qV": () => (/* binding */ BaseLanguageModel) -}); -// UNUSED EXPORTS: calculateMaxTokens, getModelContextSize +/***/ }), -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js -var schema = __nccwpck_require__(8102); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/async_caller.js -var async_caller = __nccwpck_require__(2723); -// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/count_tokens.js -var count_tokens = __nccwpck_require__(8393); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/tiktoken.js + 3 modules -var tiktoken = __nccwpck_require__(7573); -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules -var runnable = __nccwpck_require__(1972); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js -var base = __nccwpck_require__(5411); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/chat.js -var chat = __nccwpck_require__(6704); -// EXTERNAL MODULE: ./node_modules/object-hash/index.js -var object_hash = __nccwpck_require__(4856); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/cache/base.js +/***/ 4886: +/***/ ((module) => { -/** - * This cache key should be consistent across all versions of langchain. - * It is currently NOT consistent across versions of langchain. - * - * A huge benefit of having a remote cache (like redis) is that you can - * access the cache from different processes/machines. The allows you to - * seperate concerns and scale horizontally. - * - * TODO: Make cache key consistent across versions of langchain. - */ -const getCacheKey = (...strings) => object_hash(strings.join("_")); -function deserializeStoredGeneration(storedGeneration) { - if (storedGeneration.message !== undefined) { - return { - text: storedGeneration.text, - message: mapStoredMessageToChatMessage(storedGeneration.message), - }; - } - else { - return { text: storedGeneration.text }; - } -} -function serializeGeneration(generation) { - const serializedValue = { - text: generation.text, - }; - if (generation.message !== undefined) { - serializedValue.message = generation.message.toDict(); - } - return serializedValue; -} -;// CONCATENATED MODULE: ./node_modules/langchain/dist/cache/index.js +var conversions = {}; +module.exports = conversions; +function sign(x) { + return x < 0 ? -1 : 1; +} -const GLOBAL_MAP = new Map(); -/** - * A cache for storing LLM generations that stores data in memory. - */ -class InMemoryCache extends schema/* BaseCache */.H2 { - constructor(map) { - super(); - Object.defineProperty(this, "cache", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.cache = map ?? new Map(); - } - /** - * Retrieves data from the cache using a prompt and an LLM key. If the - * data is not found, it returns null. - * @param prompt The prompt used to find the data. - * @param llmKey The LLM key used to find the data. - * @returns The data corresponding to the prompt and LLM key, or null if not found. - */ - lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); - } - /** - * Updates the cache with new data using a prompt and an LLM key. - * @param prompt The prompt used to store the data. - * @param llmKey The LLM key used to store the data. - * @param value The data to be stored. - */ - async update(prompt, llmKey, value) { - this.cache.set(getCacheKey(prompt, llmKey), value); - } - /** - * Returns a global instance of InMemoryCache using a predefined global - * map as the initial cache. - * @returns A global instance of InMemoryCache. - */ - static global() { - return new InMemoryCache(GLOBAL_MAP); +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); } } -;// CONCATENATED MODULE: ./node_modules/langchain/dist/base_language/index.js +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + return function(V, opts) { + if (!opts) opts = {}; + let x = +V; + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + return x; + } + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); -const getVerbosity = () => false; -/** - * Base class for language models, chains, tools. - */ -class BaseLangChain extends runnable/* Runnable */.eq { - get lc_attributes() { - return { - callbacks: undefined, - verbose: undefined, - }; - } - constructor(params) { - super(params); - /** - * Whether to print out response text. - */ - Object.defineProperty(this, "verbose", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "callbacks", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.verbose = params.verbose ?? getVerbosity(); - this.callbacks = params.callbacks; - this.tags = params.tags ?? []; - this.metadata = params.metadata ?? {}; - } -} -/** - * Base class for language models. - */ -class BaseLanguageModel extends BaseLangChain { - /** - * Keys that the language model accepts as call options. - */ - get callKeys() { - return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; - } - constructor({ callbacks, callbackManager, ...params }) { - super({ - callbacks: callbacks ?? callbackManager, - ...params, - }); - /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. - */ - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cache", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_encoding", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - if (typeof params.cache === "object") { - this.cache = params.cache; - } - else if (params.cache) { - this.cache = InMemoryCache.global(); + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; } - else { - this.cache = undefined; + + if (!Number.isFinite(x) || x === 0) { + return 0; } - this.caller = new async_caller/* AsyncCaller */.L(params ?? {}); - } - async getNumTokens(text) { - // fallback to approximate calculation if tiktoken is not available - let numTokens = Math.ceil(text.length / 4); - if (!this._encoding) { - try { - this._encoding = await (0,tiktoken/* encodingForModel */.b)("modelName" in this - ? (0,count_tokens/* getModelNameForTiktoken */._i)(this.modelName) - : "gpt2"); - } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; } } - if (this._encoding) { - numTokens = this._encoding.encode(text).length; - } - return numTokens; - } - static _convertInputToPromptValue(input) { - if (typeof input === "string") { - return new base/* StringPromptValue */.nw(input); - } - else if (Array.isArray(input)) { - return new chat/* ChatPromptValue */.GU(input.map(schema/* coerceMessageLikeToMessage */.E1)); - } - else { - return input; - } - } - /** - * Get the identifying parameters of the LLM. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _identifyingParams() { - return {}; - } - /** - * Create a unique cache key for a specific call to a specific language model. - * @param callOptions Call options for the model - * @returns A unique cache key. - */ - _getSerializedCacheKeyParametersForCall(callOptions) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const params = { - ...this._identifyingParams(), - ...callOptions, - _type: this._llmType(), - _model: this._modelType(), - }; - const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); - const serializedEntries = filteredEntries - .map(([key, value]) => `${key}:${JSON.stringify(value)}`) - .sort() - .join(","); - return serializedEntries; - } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType(), - }; - } - /** - * @deprecated - * Load an LLM from a json-like object describing it. - */ - static async deserialize(data) { - const { _type, _model, ...rest } = data; - if (_model && _model !== "base_chat_model") { - throw new Error(`Cannot load LLM with model ${_model}`); - } - const Cls = { - openai: (await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 27))).ChatOpenAI, - }[_type]; - if (Cls === undefined) { - throw new Error(`Cannot load LLM with type ${_type}`); - } - return new Cls(rest); + + return x; } } -/* - * Export utility functions for token calculations: - * - calculateMaxTokens: Calculate max tokens for a given model and prompt (the model context size - tokens in prompt). - * - getModelContextSize: Get the context size for a specific model. - */ +conversions["void"] = function () { + return undefined; +}; +conversions["boolean"] = function (val) { + return !!val; +}; -/***/ }), +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); -/***/ 8882: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "E": () => (/* binding */ BaseCallbackHandler) -/* harmony export */ }); -/* harmony import */ var uuid__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(1273); -/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(4432); +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); -/** - * Abstract class that provides a set of optional methods that can be - * overridden in derived classes to handle various events during the - * execution of a LangChain application. - */ -class BaseCallbackHandlerMethodsClass { -} -/** - * Abstract base class for creating callback handlers in the LangChain - * framework. It provides a set of optional methods that can be overridden - * in derived classes to handle various events during the execution of a - * LangChain application. - */ -class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { - get lc_namespace() { - return ["langchain", "callbacks", this.name]; - } - get lc_secrets() { - return undefined; - } - get lc_attributes() { - return undefined; - } - get lc_aliases() { - return undefined; +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); } - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - (0,_load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .get_lc_unique_name */ .j)(this.constructor), - ]; + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; } - constructor(input) { - super(); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "ignoreLLM", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreChain", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreAgent", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "ignoreRetriever", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "awaitHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.LANGCHAIN_CALLBACKS_BACKGROUND !== "true" - : true - }); - this.lc_kwargs = input || {}; - if (input) { - this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; - this.ignoreChain = input.ignoreChain ?? this.ignoreChain; - this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; - this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); } } - copy() { - return new this.constructor(this); - } - toJSON() { - return _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable.prototype.toJSON.call */ .i.prototype.toJSON.call(this); - } - toJSONNotImplemented() { - return _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable.prototype.toJSONNotImplemented.call */ .i.prototype.toJSONNotImplemented.call(this); - } - static fromMethods(methods) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: uuid__WEBPACK_IMPORTED_MODULE_1__.v4() - }); - Object.assign(this, methods); + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } } } - return new Handler(); } -} + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; /***/ }), -/***/ 8763: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 7537: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "Z": () => (/* binding */ BaseTracer) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(8882); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" - ? value - : { [defaultKey]: value }; -} -class BaseTracer extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseCallbackHandler */ .E { - constructor(_fields) { - super(...arguments); - Object.defineProperty(this, "runMap", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - } - copy() { - return this; - } - _addChildRun(parentRun, childRun) { - parentRun.child_runs.push(childRun); +const usm = __nccwpck_require__(2158); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } } - async _startTrace(run) { - if (run.parent_run_id !== undefined) { - const parentRun = this.runMap.get(run.parent_run_id); - if (parentRun) { - this._addChildRun(parentRun, run); - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); - } - } - this.runMap.set(run.id, run); - await this.onRunCreate?.(run); + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); } - async _endTrace(run) { - const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); - if (parentRun) { - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); - } - else { - await this.persistRun(run); - } - this.runMap.delete(run.id); - await this.onRunUpdate?.(run); + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); } - _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); - // If a run has no parent then execution order is 1 - if (!parentRun) { - return 1; - } - return parentRun.child_execution_order + 1; + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; } - async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata - ? { ...extraParams, metadata } - : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { prompts }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [], - }; - await this._startTrace(run); - await this.onLLMStart?.(run); - return run; + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; } - async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata - ? { ...extraParams, metadata } - : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { messages }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [], - }; - await this._startTrace(run); - await this.onLLMStart?.(run); - return run; + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; } - async handleLLMEnd(output, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); - } - run.end_time = Date.now(); - run.outputs = output; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onLLMEnd?.(run); - await this._endTrace(run); - return run; + + if (url.port === null) { + return usm.serializeHost(url.host); } - async handleLLMError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); - } - run.end_time = Date.now(); - run.error = error.message; - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - await this.onLLMError?.(run); - await this._endTrace(run); - return run; + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; } - async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? chain.id[chain.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: chain, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs, - execution_order, - child_execution_order: execution_order, - run_type: runType ?? "chain", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - await this._startTrace(run); - await this.onChainStart?.(run); - return run; + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; } - async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); - } - run.end_time = Date.now(); - run.outputs = _coerceToDict(outputs, "output"); - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - if (kwargs?.inputs !== undefined) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); - } - await this.onChainEnd?.(run); - await this._endTrace(run); - return run; + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; } - async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); - } - run.end_time = Date.now(); - run.error = error.message; - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - if (kwargs?.inputs !== undefined) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); - } - await this.onChainError?.(run); - await this._endTrace(run); - return run; + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; } - async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? tool.id[tool.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: tool, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { input }, - execution_order, - child_execution_order: execution_order, - run_type: "tool", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - await this._startTrace(run); - await this.onToolStart?.(run); - return run; + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; } - async handleToolEnd(output, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); - } - run.end_time = Date.now(); - run.outputs = { output }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onToolEnd?.(run); - await this._endTrace(run); - return run; + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); } - async handleToolError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); - } - run.end_time = Date.now(); - run.error = error.message; - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - await this.onToolError?.(run); - await this._endTrace(run); - return run; + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; } - async handleAgentAction(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - const agentRun = run; - agentRun.actions = agentRun.actions || []; - agentRun.actions.push(action); - agentRun.events.push({ - name: "agent_action", - time: new Date().toISOString(), - kwargs: { action }, - }); - await this.onAgentAction?.(run); + + if (this._url.path.length === 0) { + return ""; } - async handleAgentEnd(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - run.events.push({ - name: "agent_end", - time: new Date().toISOString(), - kwargs: { action }, - }); - await this.onAgentEnd?.(run); + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; } - async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? retriever.id[retriever.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: retriever, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { query }, - execution_order, - child_execution_order: execution_order, - run_type: "retriever", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - await this._startTrace(run); - await this.onRetrieverStart?.(run); - return run; + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; } - async handleRetrieverEnd(documents, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); - } - run.end_time = Date.now(); - run.outputs = { documents }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onRetrieverEnd?.(run); - await this._endTrace(run); - return run; + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; } - async handleRetrieverError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); - } - run.end_time = Date.now(); - run.error = error.message; - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - await this.onRetrieverError?.(run); - await this._endTrace(run); - return run; + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; } - async handleText(text, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - run.events.push({ - name: "text", - time: new Date().toISOString(), - kwargs: { text }, - }); - await this.onText?.(run); + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; + + +/***/ }), + +/***/ 3394: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const conversions = __nccwpck_require__(4886); +const utils = __nccwpck_require__(3185); +const Impl = __nccwpck_require__(7537); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + + + +/***/ }), + +/***/ 8665: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +exports.URL = __nccwpck_require__(3394)["interface"]; +exports.serializeURL = __nccwpck_require__(2158).serializeURL; +exports.serializeURLOrigin = __nccwpck_require__(2158).serializeURLOrigin; +exports.basicURLParse = __nccwpck_require__(2158).basicURLParse; +exports.setTheUsername = __nccwpck_require__(2158).setTheUsername; +exports.setThePassword = __nccwpck_require__(2158).setThePassword; +exports.serializeHost = __nccwpck_require__(2158).serializeHost; +exports.serializeInteger = __nccwpck_require__(2158).serializeInteger; +exports.parseURL = __nccwpck_require__(2158).parseURL; + + +/***/ }), + +/***/ 2158: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +const punycode = __nccwpck_require__(5477); +const tr46 = __nccwpck_require__(4256); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; + + +/***/ }), + +/***/ 3185: +/***/ ((module) => { + + + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + + + +/***/ }), + +/***/ 2940: +/***/ ((module) => { + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] } - async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); - } - run.events.push({ - name: "new_token", - time: new Date().toISOString(), - kwargs: { token, idx, chunk: fields?.chunk }, - }); - await this.onLLMNewToken?.(run, token); - return run; + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) } + return ret + } } /***/ }), -/***/ 6009: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 8707: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "Ye": () => (/* binding */ CallbackManager), - "QH": () => (/* binding */ parseCallbackConfigArg) -}); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.zodToJsonSchema = void 0; +const zodToJsonSchema_1 = __nccwpck_require__(5110); +Object.defineProperty(exports, "zodToJsonSchema", ({ enumerable: true, get: function () { return zodToJsonSchema_1.zodToJsonSchema; } })); +exports["default"] = zodToJsonSchema_1.zodToJsonSchema; -// UNUSED EXPORTS: BaseCallbackManager, CallbackManagerForChainRun, CallbackManagerForLLMRun, CallbackManagerForRetrieverRun, CallbackManagerForToolRun, TraceGroup, traceAsGroup -// EXTERNAL MODULE: ./node_modules/langchain/node_modules/uuid/wrapper.mjs -var wrapper = __nccwpck_require__(1273); -// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/base.js -var base = __nccwpck_require__(8882); -// EXTERNAL MODULE: ./node_modules/langchain/node_modules/ansi-styles/index.js -var ansi_styles = __nccwpck_require__(8964); -// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer.js -var tracer = __nccwpck_require__(8763); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/console.js +/***/ }), +/***/ 977: +/***/ ((__unused_webpack_module, exports) => { -function wrap(style, text) { - return `${style.open}${text}${style.close}`; -} -function tryJsonStringify(obj, fallback) { - try { - return JSON.stringify(obj, null, 2); - } - catch (err) { - return fallback; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDefaultOptions = exports.defaultOptions = void 0; +exports.defaultOptions = { + name: undefined, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "string", + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + emailStrategy: "format:email", +}; +const getDefaultOptions = (options) => (typeof options === "string" + ? Object.assign(Object.assign({}, exports.defaultOptions), { name: options }) : Object.assign(Object.assign({}, exports.defaultOptions), options)); +exports.getDefaultOptions = getDefaultOptions; + + +/***/ }), + +/***/ 9345: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRefs = void 0; +const Options_1 = __nccwpck_require__(977); +const getRefs = (options) => { + const _options = (0, Options_1.getDefaultOptions)(options); + const currentPath = _options.name !== undefined + ? [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return Object.assign(Object.assign({}, _options), { currentPath: currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])) }); +}; +exports.getRefs = getRefs; + + +/***/ }), + +/***/ 1564: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setResponseValueAndErrors = exports.addErrorMessage = void 0; +function addErrorMessage(res, key, errorMessage, refs) { + if (!(refs === null || refs === void 0 ? void 0 : refs.errorMessages)) + return; + if (errorMessage) { + res.errorMessage = Object.assign(Object.assign({}, res.errorMessage), { [key]: errorMessage }); } } -function elapsed(run) { - if (!run.end_time) - return ""; - const elapsed = run.end_time - run.start_time; - if (elapsed < 1000) { - return `${elapsed}ms`; - } - return `${(elapsed / 1000).toFixed(2)}s`; +exports.addErrorMessage = addErrorMessage; +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); } -const { color } = ansi_styles; -/** - * A tracer that logs all events to the console. It extends from the - * `BaseTracer` class and overrides its methods to provide custom logging - * functionality. - */ -class ConsoleCallbackHandler extends tracer/* BaseTracer */.Z { - constructor() { - super(...arguments); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "console_callback_handler" - }); +exports.setResponseValueAndErrors = setResponseValueAndErrors; + + +/***/ }), + +/***/ 2265: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseDef = void 0; +const zod_1 = __nccwpck_require__(3301); +const any_1 = __nccwpck_require__(4742); +const array_1 = __nccwpck_require__(9719); +const bigint_1 = __nccwpck_require__(9552); +const boolean_1 = __nccwpck_require__(4037); +const branded_1 = __nccwpck_require__(8944); +const catch_1 = __nccwpck_require__(6651); +const date_1 = __nccwpck_require__(8221); +const default_1 = __nccwpck_require__(6681); +const effects_1 = __nccwpck_require__(2015); +const enum_1 = __nccwpck_require__(9144); +const intersection_1 = __nccwpck_require__(8358); +const literal_1 = __nccwpck_require__(2071); +const map_1 = __nccwpck_require__(291); +const nativeEnum_1 = __nccwpck_require__(6969); +const never_1 = __nccwpck_require__(4668); +const null_1 = __nccwpck_require__(8739); +const nullable_1 = __nccwpck_require__(5879); +const number_1 = __nccwpck_require__(4265); +const object_1 = __nccwpck_require__(2887); +const optional_1 = __nccwpck_require__(8817); +const pipeline_1 = __nccwpck_require__(1097); +const promise_1 = __nccwpck_require__(2354); +const record_1 = __nccwpck_require__(6414); +const set_1 = __nccwpck_require__(4562); +const string_1 = __nccwpck_require__(1876); +const tuple_1 = __nccwpck_require__(1809); +const undefined_1 = __nccwpck_require__(594); +const union_1 = __nccwpck_require__(9878); +const unknown_1 = __nccwpck_require__(2709); +function parseDef(def, refs, forceResolution = false // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61. +) { + const seenItem = refs.seen.get(def); + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + return seenSchema; + } } - /** - * Method used to persist the run. In this case, it simply returns a - * resolved promise as there's no persistence logic. - * @param _run The run to persist. - * @returns A resolved promise. - */ - persistRun(_run) { - return Promise.resolve(); + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchema = selectParser(def, def.typeName, refs); + if (jsonSchema) { + addMeta(def, refs, jsonSchema); } - // utility methods - /** - * Method used to get all the parent runs of a given run. - * @param run The run whose parents are to be retrieved. - * @returns An array of parent runs. - */ - getParents(run) { - const parents = []; - let currentRun = run; - while (currentRun.parent_run_id) { - const parent = this.runMap.get(currentRun.parent_run_id); - if (parent) { - parents.push(parent); - currentRun = parent; + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +exports.parseDef = parseDef; +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { + $ref: item.path.length === 0 + ? "" + : item.path.length === 1 + ? `${item.path[0]}/` + : item.path.join("/"), + }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return {}; + } + return undefined; + } + case "seen": { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return {}; } else { - break; + return item.jsonSchema; } } - return parents; - } - /** - * Method used to get a string representation of the run's lineage, which - * is used in logging. - * @param run The run whose lineage is to be retrieved. - * @returns A string representation of the run's lineage. - */ - getBreadcrumbs(run) { - const parents = this.getParents(run).reverse(); - const string = [...parents, run] - .map((parent, i, arr) => { - const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; - return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; - }) - .join(" > "); - return wrap(color.grey, string); - } - // logging methods - /** - * Method used to log the start of a chain run. - * @param run The chain run that has started. - * @returns void - */ - onChainStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a chain run. - * @param run The chain run that has ended. - * @returns void - */ - onChainEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a chain run. - * @param run The chain run that has errored. - * @returns void - */ - onChainError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of an LLM run. - * @param run The LLM run that has started. - * @returns void - */ - onLLMStart(run) { - const crumbs = this.getBreadcrumbs(run); - const inputs = "prompts" in run.inputs - ? { prompts: run.inputs.prompts.map((p) => p.trim()) } - : run.inputs; - console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); - } - /** - * Method used to log the end of an LLM run. - * @param run The LLM run that has ended. - * @returns void - */ - onLLMEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); - } - /** - * Method used to log any errors of an LLM run. - * @param run The LLM run that has errored. - * @returns void - */ - onLLMError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } - /** - * Method used to log the start of a tool run. - * @param run The tool run that has started. - * @returns void - */ - onToolStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${run.inputs.input?.trim()}"`); +}; +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; } - /** - * Method used to log the end of a tool run. - * @param run The tool run that has ended. - * @returns void - */ - onToolEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${run.outputs?.output?.trim()}"`); + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; +const selectParser = (def, typeName, refs) => { + switch (typeName) { + case zod_1.ZodFirstPartyTypeKind.ZodString: + return (0, string_1.parseStringDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodNumber: + return (0, number_1.parseNumberDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodObject: + return (0, object_1.parseObjectDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodBigInt: + return (0, bigint_1.parseBigintDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodBoolean: + return (0, boolean_1.parseBooleanDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodDate: + return (0, date_1.parseDateDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodUndefined: + return (0, undefined_1.parseUndefinedDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodNull: + return (0, null_1.parseNullDef)(refs); + case zod_1.ZodFirstPartyTypeKind.ZodArray: + return (0, array_1.parseArrayDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodUnion: + case zod_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return (0, union_1.parseUnionDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodIntersection: + return (0, intersection_1.parseIntersectionDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodTuple: + return (0, tuple_1.parseTupleDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodRecord: + return (0, record_1.parseRecordDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodLiteral: + return (0, literal_1.parseLiteralDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodEnum: + return (0, enum_1.parseEnumDef)(def); + case zod_1.ZodFirstPartyTypeKind.ZodNativeEnum: + return (0, nativeEnum_1.parseNativeEnumDef)(def); + case zod_1.ZodFirstPartyTypeKind.ZodNullable: + return (0, nullable_1.parseNullableDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodOptional: + return (0, optional_1.parseOptionalDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodMap: + return (0, map_1.parseMapDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodSet: + return (0, set_1.parseSetDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodLazy: + return parseDef(def.getter()._def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodPromise: + return (0, promise_1.parsePromiseDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodNaN: + case zod_1.ZodFirstPartyTypeKind.ZodNever: + return (0, never_1.parseNeverDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodEffects: + return (0, effects_1.parseEffectsDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodAny: + return (0, any_1.parseAnyDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodUnknown: + return (0, unknown_1.parseUnknownDef)(); + case zod_1.ZodFirstPartyTypeKind.ZodDefault: + return (0, default_1.parseDefaultDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodBranded: + return (0, branded_1.parseBrandedDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodCatch: + return (0, catch_1.parseCatchDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodPipeline: + return (0, pipeline_1.parsePipelineDef)(def, refs); + case zod_1.ZodFirstPartyTypeKind.ZodFunction: + case zod_1.ZodFirstPartyTypeKind.ZodVoid: + case zod_1.ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_) => undefined)(typeName); } - /** - * Method used to log any errors of a tool run. - * @param run The tool run that has errored. - * @returns void - */ - onToolError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } } - /** - * Method used to log the start of a retriever run. - * @param run The retriever run that has started. - * @returns void - */ - onRetrieverStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + return jsonSchema; +}; + + +/***/ }), + +/***/ 4742: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseAnyDef = void 0; +function parseAnyDef() { + return {}; +} +exports.parseAnyDef = parseAnyDef; + + +/***/ }), + +/***/ 9719: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseArrayDef = void 0; +const zod_1 = __nccwpck_require__(3301); +const errorMessages_1 = __nccwpck_require__(1564); +const parseDef_1 = __nccwpck_require__(2265); +function parseArrayDef(def, refs) { + var _a, _b; + const res = { + type: "array", + }; + if (((_b = (_a = def.type) === null || _a === void 0 ? void 0 : _a._def) === null || _b === void 0 ? void 0 : _b.typeName) !== zod_1.ZodFirstPartyTypeKind.ZodAny) { + res.items = (0, parseDef_1.parseDef)(def.type._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items"] })); } - /** - * Method used to log the end of a retriever run. - * @param run The retriever run that has ended. - * @returns void - */ - onRetrieverEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + if (def.minLength) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs); } - /** - * Method used to log any errors of a retriever run. - * @param run The retriever run that has errored. - * @returns void - */ - onRetrieverError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + if (def.maxLength) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } - /** - * Method used to log the action selected by the agent. - * @param run The run in which the agent action occurred. - * @returns void - */ - onAgentAction(run) { - const agentRun = run; - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + if (def.exactLength) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + (0, errorMessages_1.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } + return res; } +exports.parseArrayDef = parseArrayDef; -// EXTERNAL MODULE: ./node_modules/langsmith/node_modules/uuid/dist/index.js -var dist = __nccwpck_require__(9097); -;// CONCATENATED MODULE: ./node_modules/langsmith/node_modules/uuid/wrapper.mjs -const v1 = dist.v1; -const v3 = dist.v3; -const v4 = dist.v4; -const v5 = dist.v5; -const NIL = dist/* NIL */.zR; -const version = dist/* version */.i8; -const validate = dist/* validate */.Gu; -const stringify = dist/* stringify */.Pz; -const parse = dist/* parse */.Qc; +/***/ }), -// EXTERNAL MODULE: ./node_modules/p-retry/index.js -var p_retry = __nccwpck_require__(2548); -// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js -var p_queue_dist = __nccwpck_require__(8983); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js +/***/ 9552: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const STATUS_NO_RETRY = [ - 400, - 401, - 403, - 404, - 405, - 406, - 407, - 408, - 409, // Conflict -]; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; - } - else { - throw new Error(error); - } - }), { - onFailedAttempt(error) { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.message.startsWith("AbortError")) { - throw error; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseBigintDef = void 0; +const errorMessages_1 = __nccwpck_require__(1564); +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const status = error?.response?.status; - if (status && STATUS_NO_RETRY.includes(+status)) { - throw error; + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } } - }, - retries: this.maxRetries, - randomize: true, - // If needed we can change some of the defaults here, - // but they're quite sensible. - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); } + return res; } +exports.parseBigintDef = parseBigintDef; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage(message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content }, + +/***/ }), + +/***/ 4037: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseBooleanDef = void 0; +function parseBooleanDef() { + return { + type: "boolean", }; - // Check for presence of keys in additional_kwargs - if (message?.additional_kwargs && - Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; - } - return converted; } +exports.parseBooleanDef = parseBooleanDef; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && - (navigator.userAgent.includes("Node.js") || - navigator.userAgent.includes("jsdom"))); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !isDeno(); -const getEnv = () => { - let env; - if (isBrowser()) { - env = "browser"; - } - else if (isNode()) { - env = "node"; - } - else if (isWebWorker()) { - env = "webworker"; - } - else if (isJsDom()) { - env = "jsdom"; - } - else if (isDeno()) { - env = "deno"; + +/***/ }), + +/***/ 8944: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseBrandedDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parseBrandedDef(_def, refs) { + return (0, parseDef_1.parseDef)(_def.type._def, refs); +} +exports.parseBrandedDef = parseBrandedDef; + + +/***/ }), + +/***/ 6651: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseCatchDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +const parseCatchDef = (def, refs) => { + return (0, parseDef_1.parseDef)(def.innerType._def, refs); +}; +exports.parseCatchDef = parseCatchDef; + + +/***/ }), + +/***/ 8221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseDateDef = void 0; +const errorMessages_1 = __nccwpck_require__(1564); +function parseDateDef(def, refs) { + if (refs.dateStrategy == "integer") { + return integerDateParser(def, refs); } else { - env = "other"; - } - return env; -}; -let runtimeEnvironment; -async function env_getRuntimeEnvironment() { - if (runtimeEnvironment === undefined) { - const env = getEnv(); - const releaseEnv = getShas(); - runtimeEnvironment = { - library: "langsmith", - runtime: env, - ...releaseEnv, + return { + type: "string", + format: "date-time", }; } - return runtimeEnvironment; -} -/** - * Retrieves the LangChain-specific environment variables from the current runtime environment. - * Sensitive keys (containing the word "key") have their values redacted for security. - * - * @returns {Record} - * - A record of LangChain-specific environment variables. - */ -function getLangChainEnvVars() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - for (const [key, value] of Object.entries(allEnvVars)) { - if (key.startsWith("LANGCHAIN_") && typeof value === "string") { - envVars[key] = value; - } - } - for (const key in envVars) { - if (key.toLowerCase().includes("key") && typeof envVars[key] === "string") { - const value = envVars[key]; - envVars[key] = - value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); - } - } - return envVars; } -/** - * Retrieves the environment variables from the current runtime environment. - * - * This function is designed to operate in a variety of JS environments, - * including Node.js, Deno, browsers, etc. - * - * @returns {Record | undefined} - * - A record of environment variables if available. - * - `undefined` if the environment does not support or allows access to environment variables. - */ -function getEnvironmentVariables() { - try { - // Check for Node.js environment - // eslint-disable-next-line no-process-env - if (typeof process !== "undefined" && process.env) { - // eslint-disable-next-line no-process-env - Object.entries(process.env).reduce((acc, [key, value]) => { - acc[key] = String(value); - return acc; - }, {}); +exports.parseDateDef = parseDateDef; +const integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time", + }; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, // This is in milliseconds + check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, // This is in milliseconds + check.message, refs); + } + break; } - // For browsers and other environments, we may not have direct access to env variables - // Return undefined or any other fallback as required. - return undefined; - } - catch (e) { - // Catch any errors that might occur while trying to access environment variables - return undefined; } + return res; +}; + + +/***/ }), + +/***/ 6681: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseDefaultDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parseDefaultDef(_def, refs) { + return Object.assign(Object.assign({}, (0, parseDef_1.parseDef)(_def.innerType._def, refs)), { default: _def.defaultValue() }); } -function env_getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; - } - catch (e) { - return undefined; - } +exports.parseDefaultDef = parseDefaultDef; + + +/***/ }), + +/***/ 2015: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseEffectsDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" + ? (0, parseDef_1.parseDef)(_def.schema._def, refs) + : {}; } -function setEnvironmentVariable(name, value) { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - process.env[name] = value; - } +exports.parseEffectsDef = parseEffectsDef; + + +/***/ }), + +/***/ 9144: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseEnumDef = void 0; +function parseEnumDef(def) { + return { + type: "string", + enum: def.values, + }; } -let cachedCommitSHAs; -/** - * Get the Git commit SHA from common environment variables - * used by different CI/CD platforms. - * @returns {string | undefined} The Git commit SHA or undefined if not found. - */ -function getShas() { - if (cachedCommitSHAs !== undefined) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT", - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = env_getEnvironmentVariable(env); - if (envVar !== undefined) { - shas[env] = envVar; +exports.parseEnumDef = parseEnumDef; + + +/***/ }), + +/***/ 8358: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseIntersectionDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +const isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [ + (0, parseDef_1.parseDef)(def.left._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })), + (0, parseDef_1.parseDef)(def.right._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "1"] })), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" + ? { unevaluatedProperties: false } + : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } } - } - cachedCommitSHAs = shas; - return shas; + else { + let nestedSchema = schema; + if ("additionalProperties" in schema && + schema.additionalProperties === false) { + const { additionalProperties } = schema, rest = __rest(schema, ["additionalProperties"]); + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length + ? Object.assign({ allOf: mergedAllOf }, unevaluatedProperties) : undefined; } +exports.parseIntersectionDef = parseIntersectionDef; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js +/***/ }), +/***/ 2071: +/***/ ((__unused_webpack_module, exports) => { -// utility functions -const isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); -}; -const raiseForStatus = async (response, operation) => { - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - const body = await response.text(); - if (!response.ok) { - throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseLiteralDef = void 0; +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && + parsedType !== "number" && + parsedType !== "boolean" && + parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object", + }; } -}; -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value], + }; } - return result; + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value, + }; } -function trimQuotes(str) { - if (str === undefined) { - return undefined; - } - return str - .trim() - .replace(/^"(.*)"$/, "$1") - .replace(/^'(.*)'$/, "$1"); +exports.parseLiteralDef = parseLiteralDef; + + +/***/ }), + +/***/ 291: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseMapDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parseMapDef(def, refs) { + const keys = (0, parseDef_1.parseDef)(def.keyType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", "items", "0"] })) || {}; + const values = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", "items", "1"] })) || {}; + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; } -function hideInputs(inputs) { - if (env_getEnvironmentVariable("LANGCHAIN_HIDE_INPUTS") === "true") { - return {}; - } - return inputs; +exports.parseMapDef = parseMapDef; + + +/***/ }), + +/***/ 6969: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseNativeEnumDef = void 0; +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 + ? parsedTypes[0] === "string" + ? "string" + : "number" + : ["string", "number"], + enum: actualValues, + }; } -function hideOutputs(outputs) { - if (env_getEnvironmentVariable("LANGCHAIN_HIDE_OUTPUTS") === "true") { - return {}; - } - return outputs; +exports.parseNativeEnumDef = parseNativeEnumDef; + + +/***/ }), + +/***/ 4668: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseNeverDef = void 0; +function parseNeverDef() { + return { + not: {}, + }; } -class client_Client { - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - const defaultConfig = client_Client.getDefaultClientConfig(); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - this.validateApiKeyIfHosted(); - this.timeout_ms = config.timeout_ms ?? 4000; - this.caller = new AsyncCaller(config.callerOptions ?? {}); - } - static getDefaultClientConfig() { - const apiKey = env_getEnvironmentVariable("LANGCHAIN_API_KEY"); - const apiUrl = env_getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? - (apiKey ? "https://api.smith.langchain.com" : "http://localhost:1984"); - return { - apiUrl: apiUrl, - apiKey: apiKey, - webUrl: undefined, - }; - } - validateApiKeyIfHosted() { - const isLocal = isLocalhost(this.apiUrl); - if (!isLocal && !this.apiKey) { - throw new Error("API key must be provided when using hosted LangSmith API"); - } - } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; - } - else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost"; - return "http://localhost"; - } - else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return "https://dev.smith.langchain.com"; - } - else { - this.webUrl = "https://smith.langchain.com"; - return "https://smith.langchain.com"; +exports.parseNeverDef = parseNeverDef; + + +/***/ }), + +/***/ 8739: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseNullDef = void 0; +function parseNullDef(refs) { + return refs.target === "openApi3" + ? { + enum: ["null"], + nullable: true, } - } - get headers() { - const headers = {}; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; + : { + type: "null", + }; +} +exports.parseNullDef = parseNullDef; + + +/***/ }), + +/***/ 5879: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseNullableDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +const union_1 = __nccwpck_require__(9878); +function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: union_1.primitiveMappings[def.innerType._def.typeName], + nullable: true, + }; } - return headers; + return { + type: [ + union_1.primitiveMappings[def.innerType._def.typeName], + "null", + ], + }; } - async _get(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; - const response = await this.caller.call(fetch, url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`); - } - return response.json(); + if (refs.target === "openApi3") { + const base = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath] })); + return base && Object.assign(Object.assign({}, base), { nullable: true }); } - async *_getPaginated(path, queryParams = new URLSearchParams()) { - let offset = Number(queryParams.get("offset")) || 0; - const limit = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset)); - queryParams.set("limit", String(limit)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(fetch, url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to fetch ${path}: ${response.status} ${response.statusText}`); - } - const items = await response.json(); - if (items.length === 0) { + const base = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", "0"] })); + return base && { anyOf: [base, { type: "null" }] }; +} +exports.parseNullableDef = parseNullableDef; + + +/***/ }), + +/***/ 4265: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseNumberDef = void 0; +const errorMessages_1 = __nccwpck_require__(1564); +function parseNumberDef(def, refs) { + const res = { + type: "number", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + (0, errorMessages_1.addErrorMessage)(res, "type", check.message, refs); break; - } - yield items; - if (items.length < limit) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + else { + (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); break; - } - offset += items.length; - } - } - async createRun(run) { - const headers = { ...this.headers, "Content-Type": "application/json" }; - const extra = run.extra ?? {}; - const runtimeEnv = await env_getRuntimeEnvironment(); - const session_name = run.project_name; - delete run.project_name; - const runCreate = { - session_name, - ...run, - extra: { - ...run.extra, - runtime: { - ...runtimeEnv, - ...extra.runtime, - }, - }, - }; - runCreate.inputs = hideInputs(runCreate.inputs); - if (runCreate.outputs) { - runCreate.outputs = hideOutputs(runCreate.outputs); - } - const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, { - method: "POST", - headers, - body: JSON.stringify(runCreate), - signal: AbortSignal.timeout(this.timeout_ms), - }); - await raiseForStatus(response, "create run"); - } - async updateRun(runId, run) { - if (run.inputs) { - run.inputs = hideInputs(run.inputs); - } - if (run.outputs) { - run.outputs = hideOutputs(run.outputs); - } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - body: JSON.stringify(run), - signal: AbortSignal.timeout(this.timeout_ms), - }); - await raiseForStatus(response, "update run"); - } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns && run.child_run_ids) { - run = await this._loadChildRuns(run); - } - return run; - } - async getRunUrl({ runId, run, projectOpts, }) { - if (run !== undefined) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; - } - else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; - } - else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; - } - else { - const project = await this.readProject({ - projectName: env_getEnvironmentVariable("LANGCHAIN_PROJECT") || "default", - }); - sessionId = project.id; - } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; - } - else if (runId !== undefined) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); - } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; - } - else { - throw new Error("Must provide either runId or run"); - } - } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ id: run.child_run_ids })); - const treemap = {}; - const runs = {}; - // TODO: make dotted order required when the migration finishes - childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || - childRun.parent_run_id === undefined) { - throw new Error(`Child run ${childRun.id} has no parent`); - } - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; - } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; - } - } - return run; - } - async *listRuns({ projectId, projectName, parentRunId, referenceExampleId, startTime, executionOrder, runType, error, id, limit, offset, query, filter, }) { - const queryParams = new URLSearchParams(); - let projectId_ = projectId; - if (projectName) { - if (projectId) { - throw new Error("Only one of projectId or projectName may be given"); - } - projectId_ = (await this.readProject({ projectName })).id; - } - if (projectId_) { - queryParams.append("session", projectId_); - } - if (parentRunId) { - queryParams.append("parent_run", parentRunId); - } - if (referenceExampleId) { - queryParams.append("reference_example", referenceExampleId); - } - if (startTime) { - queryParams.append("start_time", startTime.toISOString()); - } - if (executionOrder) { - queryParams.append("execution_order", executionOrder.toString()); - } - if (runType) { - queryParams.append("run_type", runType); - } - if (error !== undefined) { - queryParams.append("error", error.toString()); - } - if (id !== undefined) { - for (const id_ of id) { - queryParams.append("id", id_); - } - } - if (limit !== undefined) { - queryParams.append("limit", limit.toString()); - } - if (offset !== undefined) { - queryParams.append("offset", offset.toString()); - } - if (query !== undefined) { - queryParams.append("query", query); } - if (filter !== undefined) { - queryParams.append("filter", filter); + } + return res; +} +exports.parseNumberDef = parseNumberDef; + + +/***/ }), + +/***/ 2887: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseObjectDef = exports.parseObjectDefX = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parseObjectDefX(def, refs) { + var _a, _b; + Object.keys(def.shape()).reduce((schema, key) => { + let prop = def.shape()[key]; + const isOptional = prop.isOptional(); + if (!isOptional) { + prop = Object.assign({}, prop._def.innerSchema); } - for await (const runs of this._getPaginated("/runs", queryParams)) { - yield* runs; + const propSchema = (0, parseDef_1.parseDef)(prop._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", key], propertyPath: [...refs.currentPath, "properties", key] })); + if (propSchema !== undefined) { + schema.properties[key] = propSchema; + if (!isOptional) { + if (!schema.required) { + schema.required = []; + } + schema.required.push(key); + } } - } - async shareRun(runId, { shareId } = {}) { - const data = { - run_id: runId, - share_token: shareId || v4(), + return schema; + }, { + type: "object", + properties: {}, + additionalProperties: def.catchall._def.typeName === "ZodNever" + ? def.unknownKeys === "passthrough" + : (_a = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _a !== void 0 ? _a : true, + }); + const result = Object.assign(Object.assign({ type: "object" }, Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { + if (propDef === undefined || propDef._def === undefined) + return acc; + const parsedDef = (0, parseDef_1.parseDef)(propDef._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] })); + if (parsedDef === undefined) + return acc; + return { + properties: Object.assign(Object.assign({}, acc.properties), { [propName]: parsedDef }), + required: propDef.isOptional() + ? acc.required + : [...acc.required, propName], }; - const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async unshareRun(runId) { - const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - await raiseForStatus(response, "unshare run"); + }, { properties: {}, required: [] })), { additionalProperties: def.catchall._def.typeName === "ZodNever" + ? def.unknownKeys === "passthrough" + : (_b = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _b !== void 0 ? _b : true }); + if (!result.required.length) + delete result.required; + return result; +} +exports.parseObjectDefX = parseObjectDefX; +function parseObjectDef(def, refs) { + var _a; + const result = Object.assign(Object.assign({ type: "object" }, Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { + if (propDef === undefined || propDef._def === undefined) + return acc; + const parsedDef = (0, parseDef_1.parseDef)(propDef._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] })); + if (parsedDef === undefined) + return acc; + return { + properties: Object.assign(Object.assign({}, acc.properties), { [propName]: parsedDef }), + required: propDef.isOptional() + ? acc.required + : [...acc.required, propName], + }; + }, { properties: {}, required: [] })), { additionalProperties: def.catchall._def.typeName === "ZodNever" + ? def.unknownKeys === "passthrough" + : (_a = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _a !== void 0 ? _a : true }); + if (!result.required.length) + delete result.required; + return result; +} +exports.parseObjectDef = parseObjectDef; + + +/***/ }), + +/***/ 8817: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseOptionalDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +const parseOptionalDef = (def, refs) => { + var _a; + if (refs.currentPath.toString() === ((_a = refs.propertyPath) === null || _a === void 0 ? void 0 : _a.toString())) { + return (0, parseDef_1.parseDef)(def.innerType._def, refs); } - async readRunSharedLink(runId) { - const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return undefined; + const innerSchema = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", "1"] })); + return innerSchema + ? { + anyOf: [ + { + not: {}, + }, + innerSchema, + ], } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + : {}; +}; +exports.parseOptionalDef = parseOptionalDef; + + +/***/ }), + +/***/ 1097: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parsePipelineDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return (0, parseDef_1.parseDef)(def.in._def, refs); } - async createProject({ projectName, projectExtra, upsert, referenceDatasetId, }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const body = { - name: projectName, + const a = (0, parseDef_1.parseDef)(def.in._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })); + const b = (0, parseDef_1.parseDef)(def.out._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] })); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; +exports.parsePipelineDef = parsePipelineDef; + + +/***/ }), + +/***/ 2354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parsePromiseDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parsePromiseDef(def, refs) { + return (0, parseDef_1.parseDef)(def.type._def, refs); +} +exports.parsePromiseDef = parsePromiseDef; + + +/***/ }), + +/***/ 6414: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseRecordDef = void 0; +const zod_1 = __nccwpck_require__(3301); +const parseDef_1 = __nccwpck_require__(2265); +const string_1 = __nccwpck_require__(1876); +function parseRecordDef(def, refs) { + var _a, _b, _c, _d, _e; + if (refs.target === "openApi3" && + ((_a = def.keyType) === null || _a === void 0 ? void 0 : _a._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => { + var _a; + return (Object.assign(Object.assign({}, acc), { [key]: (_a = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", key] }))) !== null && _a !== void 0 ? _a : {} })); + }, {}), + additionalProperties: false, }; - if (projectExtra !== undefined) { - body["extra"] = projectExtra; - } - if (referenceDatasetId !== undefined) { - body["reference_dataset_id"] = referenceDatasetId; - } - const response = await this.caller.call(fetch, endpoint, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - }); - const result = await response.json(); - if (!response.ok) { - throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`); - } - return result; } - async readProject({ projectId, projectName, }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); - } - result = response[0]; - } - else { - result = response; - } - return result; + const schema = { + type: "object", + additionalProperties: (_b = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _b !== void 0 ? _b : {}, + }; + if (refs.target === "openApi3") { + return schema; } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; - } - throw new Error("No projects found to resolve tenant."); + if (((_c = def.keyType) === null || _c === void 0 ? void 0 : _c._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodString && + ((_d = def.keyType._def.checks) === null || _d === void 0 ? void 0 : _d.length)) { + const keyType = Object.entries((0, string_1.parseStringDef)(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === "type" ? acc : Object.assign(Object.assign({}, acc), { [key]: value })), {}); + return Object.assign(Object.assign({}, schema), { propertyNames: keyType }); } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, } = {}) { - const params = new URLSearchParams(); - if (projectIds !== undefined) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== undefined) { - params.append("name", name); - } - if (nameContains !== undefined) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== undefined) { - params.append("reference_dataset", referenceDatasetId); - } - else if (referenceDatasetName !== undefined) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName, - }); - params.append("reference_dataset", dataset.id); - } - if (referenceFree !== undefined) { - params.append("reference_free", referenceFree.toString()); - } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; - } + else if (((_e = def.keyType) === null || _e === void 0 ? void 0 : _e._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodEnum) { + return Object.assign(Object.assign({}, schema), { propertyNames: { + enum: def.keyType._def.values, + } }); } - async deleteProject({ projectId, projectName, }) { - let projectId_; - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide projectName or projectId"); - } - else if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId === undefined) { - projectId_ = (await this.readProject({ projectName })).id; - } - else { - projectId_ = projectId; - } - const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - await raiseForStatus(response, `delete session ${projectId_} (${projectName})`); + return schema; +} +exports.parseRecordDef = parseRecordDef; + + +/***/ }), + +/***/ 4562: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseSetDef = void 0; +const errorMessages_1 = __nccwpck_require__(1564); +const parseDef_1 = __nccwpck_require__(2265); +function parseSetDef(def, refs) { + const items = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items"] })); + const schema = { + type: "array", + uniqueItems: true, + items, + }; + if (def.minSize) { + (0, errorMessages_1.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs); } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); - }); - if (description) { - formData.append("description", description); - } - if (dataType) { - formData.append("data_type", dataType); - } - if (name) { - formData.append("name", name); - } - const response = await this.caller.call(fetch, url, { - method: "POST", - headers: this.headers, - body: formData, - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - const result = await response.json(); - if (result.detail && result.detail.includes("already exists")) { - throw new Error(`Dataset ${fileName} already exists`); - } - throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`); - } - const result = await response.json(); - return result; + if (def.maxSize) { + (0, errorMessages_1.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); } - async createDataset(name, { description, dataType, } = {}) { - const body = { - name, - description, - }; - if (dataType) { - body.data_type = dataType; - } - const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - const result = await response.json(); - if (result.detail && result.detail.includes("already exists")) { - throw new Error(`Dataset ${name} already exists`); + return schema; +} +exports.parseSetDef = parseSetDef; + + +/***/ }), + +/***/ 1876: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseStringDef = exports.emojiPattern = exports.ulidPattern = exports.cuid2Pattern = exports.cuidPattern = exports.emailPattern = void 0; +const errorMessages_1 = __nccwpck_require__(1564); +exports.emailPattern = '^(([^<>()[\\]\\\\.,;:\\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,})+))$'; +exports.cuidPattern = "^c[^\\s-]{8,}$"; +exports.cuid2Pattern = "^[a-z][a-z0-9]*$"; +exports.ulidPattern = "/[0-9A-HJKMNP-TV-Z]{26}/"; +exports.emojiPattern = "/^(p{Extended_Pictographic}|p{Emoji_Component})+$/u"; +function parseStringDef(def, refs) { + const res = { + type: "string", + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + break; + case "max": + (0, errorMessages_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, exports.emailPattern, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex.source, check.message, refs); + break; + case "cuid": + addPattern(res, exports.cuidPattern, check.message, refs); + break; + case "cuid2": + addPattern(res, exports.cuid2Pattern, check.message, refs); + break; + case "startsWith": + addPattern(res, "^" + escapeNonAlphaNumeric(check.value), check.message, refs); + break; + case "endsWith": + addPattern(res, escapeNonAlphaNumeric(check.value) + "$", check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "length": + (0, errorMessages_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + (0, errorMessages_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "includes": { + addPattern(res, escapeNonAlphaNumeric(check.value), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat(res, "ipv6", check.message, refs); + } + break; + } + case "emoji": + addPattern(res, exports.emojiPattern, check.message, refs); + break; + case "ulid": { + addPattern(res, exports.ulidPattern, check.message, refs); + break; + } + case "toLowerCase": + case "toUpperCase": + case "trim": + // I have no idea why these are checks in Zod 🤷 + break; + default: + ((_) => { })(check); } - throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`); } - const result = await response.json(); - return result; } - async readDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - // limit to 1 result - const params = new URLSearchParams({ limit: "1" }); - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - path += `/${datasetId}`; - } - else if (datasetName !== undefined) { - params.append("name", datasetName); - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); - } - result = response[0]; - } - else { - result = response; + return res; +} +exports.parseStringDef = parseStringDef; +const escapeNonAlphaNumeric = (value) => Array.from(value) + .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) + .join(""); +const addFormat = (schema, value, message, refs) => { + var _a; + if (schema.format || ((_a = schema.anyOf) === null || _a === void 0 ? void 0 : _a.some((x) => x.format))) { + if (!schema.anyOf) { + schema.anyOf = []; } - return result; - } - async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit.toString(), - offset: offset.toString(), - }); - if (datasetIds !== undefined) { - for (const id_ of datasetIds) { - params.append("id", id_); + if (schema.format) { + schema.anyOf.push(Object.assign({ format: schema.format }, (schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }))); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } } } - if (datasetName !== undefined) { - params.append("name", datasetName); - } - if (datasetNameContains !== undefined) { - params.append("name_contains", datasetNameContains); - } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; - } - } - async deleteDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - if (datasetId_ !== undefined) { - path += `/${datasetId_}`; - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this.caller.call(fetch, this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); - } - await response.json(); - } - async createExample(inputs, outputs, { datasetId, datasetName, createdAt, exampleId }) { - let datasetId_ = datasetId; - if (datasetId_ === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - const createdAt_ = createdAt || new Date(); - const data = { - dataset_id: datasetId_, - inputs, - outputs, - created_at: createdAt_.toISOString(), - id: exampleId, - }; - const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to create example: ${response.status} ${response.statusText}`); - } - const result = await response.json(); - return result; - } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); - } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); - } - return message; - }); - const finalOutput = isLangChainMessage(generations) - ? convertLangChainMessageToExample(generations) - : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); + schema.anyOf.push(Object.assign({ format: value }, (message && + refs.errorMessages && { errorMessage: { format: message } }))); } - async readExample(exampleId) { - const path = `/examples/${exampleId}`; - return await this._get(path); + else { + (0, errorMessages_1.setResponseValueAndErrors)(schema, "format", value, message, refs); } - async *listExamples({ datasetId, datasetName, exampleIds, } = {}) { - let datasetId_; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - datasetId_ = datasetId; - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - throw new Error("Must provide a datasetName or datasetId"); +}; +const addPattern = (schema, value, message, refs) => { + var _a; + if (schema.pattern || ((_a = schema.allOf) === null || _a === void 0 ? void 0 : _a.some((x) => x.pattern))) { + if (!schema.allOf) { + schema.allOf = []; } - const params = new URLSearchParams({ dataset: datasetId_ }); - if (exampleIds !== undefined) { - for (const id_ of exampleIds) { - params.append("id", id_); + if (schema.pattern) { + schema.allOf.push(Object.assign({ pattern: schema.pattern }, (schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }))); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } } } - for await (const examples of this._getPaginated("/examples", params)) { - yield* examples; - } - } - async deleteExample(exampleId) { - const path = `/examples/${exampleId}`; - const response = await this.caller.call(fetch, this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); - } - await response.json(); - } - async updateExample(exampleId, update) { - const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update), - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`); - } - const result = await response.json(); - return result; + schema.allOf.push(Object.assign({ pattern: value }, (message && + refs.errorMessages && { errorMessage: { pattern: message } }))); } - async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, } = { loadChildRuns: false }) { - let run_; - if (typeof run === "string") { - run_ = await this.readRun(run, { loadChildRuns }); - } - else if (typeof run === "object" && "id" in run) { - run_ = run; - } - else { - throw new Error(`Invalid run type: ${typeof run}`); - } - let referenceExample = undefined; - if (run_.reference_example_id !== null && - run_.reference_example_id !== undefined) { - referenceExample = await this.readExample(run_.reference_example_id); - } - const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); - let sourceInfo_ = sourceInfo ?? {}; - if (feedbackResult.evaluatorInfo) { - sourceInfo_ = { ...sourceInfo_, ...feedbackResult.evaluatorInfo }; - } - return await this.createFeedback(run_.id, feedbackResult.key, { - score: feedbackResult.score, - value: feedbackResult.value, - comment: feedbackResult.comment, - correction: feedbackResult.correction, - sourceInfo: sourceInfo_, - feedbackSourceType: "model", - }); + else { + (0, errorMessages_1.setResponseValueAndErrors)(schema, "pattern", value, message, refs); } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, }) { - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {}, - }; - if (sourceRunId !== undefined && - feedback_source?.metadata !== undefined && - !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; - } - const feedback = { - id: feedbackId ?? v4(), - run_id: runId, - key, - score, - value, - correction, - comment, - feedback_source: feedback_source, +}; + + +/***/ }), + +/***/ 1809: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseTupleDef = void 0; +const parseDef_1 = __nccwpck_require__(2265); +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items + .map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", `${i}`] }))) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: (0, parseDef_1.parseDef)(def.rest._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalItems"] })), }; - const response = await this.caller.call(fetch, `${this.apiUrl}/feedback`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedback), - signal: AbortSignal.timeout(this.timeout_ms), - }); - await raiseForStatus(response, "create feedback"); - return feedback; - } - async updateFeedback(feedbackId, { score, value, correction, comment, }) { - const feedbackUpdate = {}; - if (score !== undefined && score !== null) { - feedbackUpdate["score"] = score; - } - if (value !== undefined && value !== null) { - feedbackUpdate["value"] = value; - } - if (correction !== undefined && correction !== null) { - feedbackUpdate["correction"] = correction; - } - if (comment !== undefined && comment !== null) { - feedbackUpdate["comment"] = comment; - } - const response = await this.caller.call(fetch, `${this.apiUrl}/feedback/${feedbackId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedbackUpdate), - signal: AbortSignal.timeout(this.timeout_ms), - }); - await raiseForStatus(response, "update feedback"); } - async readFeedback(feedbackId) { - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; - } - async deleteFeedback(feedbackId) { - const path = `/feedback/${feedbackId}`; - const response = await this.caller.call(fetch, this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - }); - if (!response.ok) { - throw new Error(`Failed to delete ${path}: ${response.status} ${response.statusText}`); - } - await response.json(); - } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - queryParams.append("run", runIds.join(",")); - } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); - } - } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); - } - } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; - } + else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", `${i}`] }))) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; } } +exports.parseTupleDef = parseTupleDef; + -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js +/***/ }), +/***/ 594: +/***/ ((__unused_webpack_module, exports) => { -const warnedMessages = {}; -function warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseUndefinedDef = void 0; +function parseUndefinedDef() { + return { + not: {}, + }; } -class RunTree { - constructor(config) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "end_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "extra", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "serialized", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "reference_example_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "events", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - const defaultConfig = RunTree.getDefaultConfig(); - Object.assign(this, { ...defaultConfig, ...config }); - } - static getDefaultConfig() { +exports.parseUndefinedDef = parseUndefinedDef; + + +/***/ }), + +/***/ 9878: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseUnionDef = exports.primitiveMappings = void 0; +const parseDef_1 = __nccwpck_require__(2265); +exports.primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null", +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in exports.primitiveMappings && + (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = exports.primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); return { - id: uuid.v4(), - project_name: getEnvironmentVariable("LANGCHAIN_PROJECT") ?? - getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default", - child_runs: [], - execution_order: 1, - child_execution_order: 1, - api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time: Date.now(), - serialized: {}, - inputs: {}, - extra: {}, - client: new Client({}), - }; - } - async createChild(config) { - const child = new RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - client: this.client, - execution_order: this.child_execution_order + 1, - child_execution_order: this.child_execution_order + 1, - }); - this.child_runs.push(child); - return child; - } - async end(outputs, error, endTime = Date.now()) { - this.outputs = outputs; - this.error = error; - this.end_time = endTime; - if (this.parent_run) { - this.parent_run.child_execution_order = Math.max(this.parent_run.child_execution_order, this.child_execution_order); - } - } - async _convertToCreate(run, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - if (!runExtra.runtime) { - runExtra.runtime = {}; - } - const runtimeEnv = await getRuntimeEnvironment(); - for (const [k, v] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k]) { - runExtra.runtime[k] = v; - } - } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = await Promise.all(run.child_runs.map((child_run) => this._convertToCreate(child_run, excludeChildRuns))); - parent_run_id = undefined; - } - else { - parent_run_id = run.parent_run?.id; - child_runs = []; - } - const persistedRun = { - id: run.id, - name: run.name, - start_time: run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - execution_order: run.execution_order, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs: child_runs, - parent_run_id: parent_run_id, + type: types.length > 1 ? types : types[0], }; - return persistedRun; } - async postRun(excludeChildRuns = true) { - const runCreate = await this._convertToCreate(this, true); - await this.client.createRun(runCreate); - if (!excludeChildRuns) { - warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); + else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; } } - async patchRun() { - const runUpdate = { - end_time: this.end_time, - error: this.error, - outputs: this.outputs, - parent_run_id: this.parent_run?.id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, + else if (options.every((x) => x._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x) => [ + ...acc, + ...x._def.values.filter((x) => !acc.includes(x)), + ], []), }; - await this.client.updateRun(this.id, runUpdate); } + return asAnyOf(def, refs); } +exports.parseUnionDef = parseUnionDef; +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map + ? Array.from(def.options.values()) + : def.options) + .map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", `${i}`] }))) + .filter((x) => !!x && + (!refs.strictUnions || + (typeof x === "object" && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js +/***/ }), +/***/ 2709: +/***/ ((__unused_webpack_module, exports) => { -;// CONCATENATED MODULE: ./node_modules/langsmith/index.js -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/env.js -var env = __nccwpck_require__(5785); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer_langchain.js +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.parseUnknownDef = void 0; +function parseUnknownDef() { + return {}; +} +exports.parseUnknownDef = parseUnknownDef; +/***/ }), -class tracer_langchain_LangChainTracer extends tracer/* BaseTracer */.Z { - constructor(fields = {}) { - super(fields); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "langchain_tracer" - }); - Object.defineProperty(this, "projectName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "exampleId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - const { exampleId, projectName, client } = fields; - this.projectName = - projectName ?? - (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_PROJECT") ?? - (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_SESSION"); - this.exampleId = exampleId; - this.client = client ?? new client_Client({}); +/***/ 5110: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.zodToJsonSchema = void 0; +const parseDef_1 = __nccwpck_require__(2265); +const Refs_1 = __nccwpck_require__(9345); +const zodToJsonSchema = (schema, options) => { + var _a; + const refs = (0, Refs_1.getRefs)(options); + const definitions = typeof options === "object" && options.definitions + ? Object.entries(options.definitions).reduce((acc, [name, schema]) => { + var _a; + return (Object.assign(Object.assign({}, acc), { [name]: (_a = (0, parseDef_1.parseDef)(schema._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), true)) !== null && _a !== void 0 ? _a : {} })); + }, {}) + : undefined; + const name = typeof options === "string" ? options : options === null || options === void 0 ? void 0 : options.name; + const main = (_a = (0, parseDef_1.parseDef)(schema._def, name === undefined + ? refs + : Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), false)) !== null && _a !== void 0 ? _a : {}; + const combined = name === undefined + ? definitions + ? Object.assign(Object.assign({}, main), { [refs.definitionPath]: definitions }) : main + : { + $ref: [ + ...(refs.$refStrategy === "relative" ? [] : refs.basePath), + refs.definitionPath, + name, + ].join("/"), + [refs.definitionPath]: Object.assign(Object.assign({}, definitions), { [name]: main }), + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; } - async _convertToCreate(run, example_id = undefined) { - return { - ...run, - extra: { - ...run.extra, - runtime: await (0,env/* getRuntimeEnvironment */.sA)(), - }, - child_runs: undefined, - session_name: this.projectName, - reference_example_id: run.parent_run_id ? undefined : example_id, + else if (refs.target === "jsonSchema2019-09") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + return combined; +}; +exports.zodToJsonSchema = zodToJsonSchema; + + +/***/ }), + +/***/ 6869: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; +const util_1 = __nccwpck_require__(3985); +exports.ZodIssueCode = util_1.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +exports.quotelessJson = quotelessJson; +class ZodError extends Error { + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; } - async persistRun(_run) { } - async _persistRunSingle(run) { - const persistedRun = await this._convertToCreate(run, this.exampleId); - await this.client.createRun(persistedRun); + get errors() { + return this.issues; } - async _updateRunSingle(run) { - const runUpdate = { - end_time: run.end_time, - error: run.error, - outputs: run.outputs, - events: run.events, - inputs: run.inputs, + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } }; - await this.client.updateRun(run.id, runUpdate); + processError(this); + return fieldErrors; } - async onRetrieverStart(run) { - await this._persistRunSingle(run); + toString() { + return this.message; } - async onRetrieverEnd(run) { - await this._updateRunSingle(run); + get message() { + return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); } - async onRetrieverError(run) { - await this._updateRunSingle(run); + get isEmpty() { + return this.issues.length === 0; } - async onLLMStart(run) { - await this._persistRunSingle(run); + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; } - async onLLMEnd(run) { - await this._updateRunSingle(run); + get formErrors() { + return this.flatten(); } - async onLLMError(run) { - await this._updateRunSingle(run); +} +exports.ZodError = ZodError; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; + + +/***/ }), + +/***/ 9566: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; +const en_1 = __importDefault(__nccwpck_require__(468)); +exports.defaultErrorMap = en_1.default; +let overrideErrorMap = en_1.default; +function setErrorMap(map) { + overrideErrorMap = map; +} +exports.setErrorMap = setErrorMap; +function getErrorMap() { + return overrideErrorMap; +} +exports.getErrorMap = getErrorMap; + + +/***/ }), + +/***/ 9906: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(9566), exports); +__exportStar(__nccwpck_require__(888), exports); +__exportStar(__nccwpck_require__(9449), exports); +__exportStar(__nccwpck_require__(3985), exports); +__exportStar(__nccwpck_require__(9335), exports); +__exportStar(__nccwpck_require__(6869), exports); + + +/***/ }), + +/***/ 2513: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.errorUtil = void 0; +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; +})(errorUtil = exports.errorUtil || (exports.errorUtil = {})); + + +/***/ }), + +/***/ 888: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; +const errors_1 = __nccwpck_require__(9566); +const en_1 = __importDefault(__nccwpck_require__(468)); +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; } - async onChainStart(run) { - await this._persistRunSingle(run); + return { + ...issueData, + path: fullPath, + message: issueData.message || errorMessage, + }; +}; +exports.makeIssue = makeIssue; +exports.EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const issue = (0, exports.makeIssue)({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + (0, errors_1.getErrorMap)(), + en_1.default, + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +exports.addIssueToContext = addIssueToContext; +class ParseStatus { + constructor() { + this.value = "valid"; } - async onChainEnd(run) { - await this._updateRunSingle(run); + dirty() { + if (this.value === "valid") + this.value = "dirty"; } - async onChainError(run) { - await this._updateRunSingle(run); + abort() { + if (this.value !== "aborted") + this.value = "aborted"; } - async onToolStart(run) { - await this._persistRunSingle(run); + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return exports.INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; } - async onToolEnd(run) { - await this._updateRunSingle(run); + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + syncPairs.push({ + key: await pair.key, + value: await pair.value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); } - async onToolError(run) { - await this._updateRunSingle(run); + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return exports.INVALID; + if (value.status === "aborted") + return exports.INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && + (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; } } +exports.ParseStatus = ParseStatus; +exports.INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +exports.DIRTY = DIRTY; +const OK = (value) => ({ status: "valid", value }); +exports.OK = OK; +const isAborted = (x) => x.status === "aborted"; +exports.isAborted = isAborted; +const isDirty = (x) => x.status === "dirty"; +exports.isDirty = isDirty; +const isValid = (x) => x.status === "valid"; +exports.isValid = isValid; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +exports.isAsync = isAsync; -// EXTERNAL MODULE: ./node_modules/langchain/dist/memory/base.js -var memory_base = __nccwpck_require__(790); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer_langchain_v1.js +/***/ }), +/***/ 9449: +/***/ ((__unused_webpack_module, exports) => { -class LangChainTracerV1 extends tracer/* BaseTracer */.Z { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "langchain_tracer" - }); - Object.defineProperty(this, "endpoint", { - enumerable: true, - configurable: true, - writable: true, - value: (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_ENDPOINT") || "http://localhost:1984" - }); - Object.defineProperty(this, "headers", { - enumerable: true, - configurable: true, - writable: true, - value: { - "Content-Type": "application/json", - } - }); - Object.defineProperty(this, "session", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - const apiKey = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_API_KEY"); - if (apiKey) { - this.headers["x-api-key"] = apiKey; - } - } - async newSession(sessionName) { - const sessionCreate = { - start_time: Date.now(), - name: sessionName, - }; - const session = await this.persistSession(sessionCreate); - this.session = session; - return session; - } - async loadSession(sessionName) { - const endpoint = `${this.endpoint}/sessions?name=${sessionName}`; - return this._handleSessionResponse(endpoint); - } - async loadDefaultSession() { - const endpoint = `${this.endpoint}/sessions?name=default`; - return this._handleSessionResponse(endpoint); - } - async convertV2RunToRun(run) { - const session = this.session ?? (await this.loadDefaultSession()); - const serialized = run.serialized; - let runResult; - if (run.run_type === "llm") { - const prompts = run.inputs.prompts - ? run.inputs.prompts - : run.inputs.messages.map((x) => (0,memory_base/* getBufferString */.zs)(x)); - const llmRun = { - uuid: run.id, - start_time: run.start_time, - end_time: run.end_time, - execution_order: run.execution_order, - child_execution_order: run.child_execution_order, - serialized, - type: run.run_type, - session_id: session.id, - prompts, - response: run.outputs, - }; - runResult = llmRun; - } - else if (run.run_type === "chain") { - const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); - const chainRun = { - uuid: run.id, - start_time: run.start_time, - end_time: run.end_time, - execution_order: run.execution_order, - child_execution_order: run.child_execution_order, - serialized, - type: run.run_type, - session_id: session.id, - inputs: run.inputs, - outputs: run.outputs, - child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), - child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), - child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"), - }; - runResult = chainRun; - } - else if (run.run_type === "tool") { - const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); - const toolRun = { - uuid: run.id, - start_time: run.start_time, - end_time: run.end_time, - execution_order: run.execution_order, - child_execution_order: run.child_execution_order, - serialized, - type: run.run_type, - session_id: session.id, - tool_input: run.inputs.input, - output: run.outputs?.output, - action: JSON.stringify(serialized), - child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), - child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), - child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"), - }; - runResult = toolRun; - } - else { - throw new Error(`Unknown run type: ${run.run_type}`); - } - return runResult; + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + +/***/ }), + +/***/ 3985: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; +var util; +(function (util) { + util.assertEqual = (val) => val; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); } - async persistRun(run) { - let endpoint; - let v1Run; - if (run.run_type !== undefined) { - v1Run = await this.convertV2RunToRun(run); - } - else { - v1Run = run; - } - if (v1Run.type === "llm") { - endpoint = `${this.endpoint}/llm-runs`; - } - else if (v1Run.type === "chain") { - endpoint = `${this.endpoint}/chain-runs`; + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; } - else { - endpoint = `${this.endpoint}/tool-runs`; + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; } - const response = await fetch(endpoint, { - method: "POST", - headers: this.headers, - body: JSON.stringify(v1Run), + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; }); - if (!response.ok) { - console.error(`Failed to persist run: ${response.status} ${response.statusText}`); + }; + util.objectKeys = typeof Object.keys === "function" + ? (obj) => Object.keys(obj) + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) + : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array + .map((val) => (typeof val === "string" ? `'${val}'` : val)) + .join(separator); } - async persistSession(sessionCreate) { - const endpoint = `${this.endpoint}/sessions`; - const response = await fetch(endpoint, { - method: "POST", - headers: this.headers, - body: JSON.stringify(sessionCreate), - }); - if (!response.ok) { - console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`); - return { - id: 1, - ...sessionCreate, - }; + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); } + return value; + }; +})(util = exports.util || (exports.util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { return { - id: (await response.json()).id, - ...sessionCreate, + ...first, + ...second, }; + }; +})(objectUtil = exports.objectUtil || (exports.objectUtil = {})); +exports.ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return exports.ZodParsedType.undefined; + case "string": + return exports.ZodParsedType.string; + case "number": + return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; + case "boolean": + return exports.ZodParsedType.boolean; + case "function": + return exports.ZodParsedType.function; + case "bigint": + return exports.ZodParsedType.bigint; + case "symbol": + return exports.ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return exports.ZodParsedType.array; + } + if (data === null) { + return exports.ZodParsedType.null; + } + if (data.then && + typeof data.then === "function" && + data.catch && + typeof data.catch === "function") { + return exports.ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return exports.ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return exports.ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return exports.ZodParsedType.date; + } + return exports.ZodParsedType.object; + default: + return exports.ZodParsedType.unknown; } - async _handleSessionResponse(endpoint) { - const response = await fetch(endpoint, { - method: "GET", - headers: this.headers, - }); - let tracerSession; - if (!response.ok) { - console.error(`Failed to load session: ${response.status} ${response.statusText}`); - tracerSession = { - id: 1, - start_time: Date.now(), - }; - this.session = tracerSession; - return tracerSession; - } - const resp = (await response.json()); - if (resp.length === 0) { - tracerSession = { - id: 1, - start_time: Date.now(), - }; - this.session = tracerSession; - return tracerSession; - } - [tracerSession] = resp; - this.session = tracerSession; - return tracerSession; +}; +exports.getParsedType = getParsedType; + + +/***/ }), + +/***/ 3301: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.z = void 0; +const z = __importStar(__nccwpck_require__(9906)); +exports.z = z; +__exportStar(__nccwpck_require__(9906), exports); +exports["default"] = z; + + +/***/ }), + +/***/ 468: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __nccwpck_require__(3985); +const ZodError_1 = __nccwpck_require__(6869); +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodError_1.ZodIssueCode.invalid_type: + if (issue.received === util_1.ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodError_1.ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; + break; + case ZodError_1.ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_1.ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodError_1.ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; + break; + case ZodError_1.ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_1.ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodError_1.ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodError_1.ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodError_1.ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util_1.util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodError_1.ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly equal to ` + : issue.inclusive + ? `greater than or equal to ` + : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodError_1.ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `less than or equal to` + : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact + ? `exactly` + : issue.inclusive + ? `smaller than or equal to` + : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodError_1.ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodError_1.ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodError_1.ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_1.ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_1.util.assertNever(issue); } -} + return { message }; +}; +exports["default"] = errorMap; -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/initialize.js +/***/ }), -/** - * Function that returns an instance of `LangChainTracerV1`. If a session - * is provided, it loads that session into the tracer; otherwise, it loads - * a default session. - * @param session Optional session to load into the tracer. - * @returns An instance of `LangChainTracerV1`. - */ -async function getTracingCallbackHandler(session) { - const tracer = new LangChainTracerV1(); - if (session) { - await tracer.loadSession(session); - } - else { - await tracer.loadDefaultSession(); - } - return tracer; -} -/** - * Function that returns an instance of `LangChainTracer`. It does not - * load any session data. - * @returns An instance of `LangChainTracer`. - */ -async function getTracingV2CallbackHandler() { - return new tracer_langchain_LangChainTracer(); -} +/***/ 9335: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/promises.js -let queue; -/** - * Creates a queue using the p-queue library. The queue is configured to - * auto-start and has a concurrency of 1, meaning it will process tasks - * one at a time. - */ -function createQueue() { - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - return new PQueue({ - autoStart: true, - concurrency: 1, - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; +exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = exports.discriminatedUnion = void 0; +const errors_1 = __nccwpck_require__(9566); +const errorUtil_1 = __nccwpck_require__(2513); +const parseUtil_1 = __nccwpck_require__(888); +const util_1 = __nccwpck_require__(3985); +const ZodError_1 = __nccwpck_require__(6869); +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (this._key instanceof Array) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } } -/** - * Consume a promise, either adding it to the queue or waiting for it to resolve - * @param promise Promise to consume - * @param wait Whether to wait for the promise to resolve or resolve immediately - */ -async function consumeCallback(promiseFn, wait) { - if (wait === true) { - await promiseFn(); +const handleResult = (ctx, result) => { + if ((0, parseUtil_1.isValid)(result)) { + return { success: true, data: result.value }; } else { - if (typeof queue === "undefined") { - queue = createQueue(); + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); } - void queue.add(promiseFn); + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError_1.ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; } -} -/** - * Waits for all promises in the queue to resolve. If the queue is - * undefined, it immediately resolves a promise. - */ -function awaitAllCallbacks() { - return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/manager.js - - - - - - - - -function parseCallbackConfigArg(arg) { - if (!arg) { +}; +function processCreateParams(params) { + if (!params) return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } - else if (Array.isArray(arg) || "name" in arg) { - return { callbacks: arg }; + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + if (typeof ctx.data === "undefined") { + return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; + } + return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); } - else { - return arg; + get description() { + return this._def.description; } -} -/** - * Manage callbacks from different components of LangChain. - */ -class BaseCallbackManager { - setHandler(handler) { - return this.setHandlers([handler]); + _getType(input) { + return (0, util_1.getParsedType)(input.data); } -} -/** - * Base class for run manager in LangChain. - */ -class BaseRunManager { - constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { - Object.defineProperty(this, "runId", { - enumerable: true, - configurable: true, - writable: true, - value: runId - }); - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: handlers - }); - Object.defineProperty(this, "inheritableHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableHandlers - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: tags - }); - Object.defineProperty(this, "inheritableTags", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableTags - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: metadata - }); - Object.defineProperty(this, "inheritableMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: inheritableMetadata - }); - Object.defineProperty(this, "_parentRunId", { - enumerable: true, - configurable: true, - writable: true, - value: _parentRunId + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: (0, util_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, }); } - async handleText(text) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleText: ${err}`); - } - }, handler.awaitHandlers))); + _processInputParams(input) { + return { + status: new parseUtil_1.ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: (0, util_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; } -} -/** - * Manages callbacks for retriever runs. - */ -class CallbackManagerForRetrieverRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); + _parseSync(input) { + const result = this._parse(input); + if ((0, parseUtil_1.isAsync)(result)) { + throw new Error("Synchronous parse encountered promise."); } - return manager; + return result; } - async handleRetrieverEnd(documents) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleRetriever`); - } - } - }, handler.awaitHandlers))); + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); } - async handleRetrieverError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); - } - catch (error) { - console.error(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); - } - } - }, handler.awaitHandlers))); + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; } -} -class CallbackManagerForLLMRun extends BaseRunManager { - async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); - } - } - }, handler.awaitHandlers))); + safeParse(data, params) { + var _a; + const ctx = { + common: { + issues: [], + async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_1.getParsedType)(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); } - async handleLLMError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); - } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: true, + }, + path: (params === null || params === void 0 ? void 0 : params.path) || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_1.getParsedType)(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) + ? maybeAsyncResult + : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; } - }, handler.awaitHandlers))); + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodError_1.ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); } - async handleLLMEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); - } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" + ? refinementData(val, ctx) + : refinementData); + return false; } - }, handler.awaitHandlers))); + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this, this._def); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); } -} -class CallbackManagerForChainRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); } - async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); - } - } - }, handler.awaitHandlers))); + pipe(target) { + return ZodPipeline.create(this, target); } - async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); - } - } - }, handler.awaitHandlers))); + readonly() { + return ZodReadonly.create(this); } - async handleAgentAction(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); - } - } - }, handler.awaitHandlers))); + isOptional() { + return this.safeParse(undefined).success; } - async handleAgentEnd(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); - } - } - }, handler.awaitHandlers))); + isNullable() { + return this.safeParse(null).success; } } -class CallbackManagerForToolRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); +exports.ZodType = ZodType; +exports.Schema = ZodType; +exports.ZodSchema = ZodType; +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[a-z][a-z0-9]*$/; +const ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; +const 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; +const emailRegex = /^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +const emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u; +const ipv4Regex = /^(((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}))$/; +const 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})))$/; +const datetimeRegex = (args) => { + if (args.precision) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); } - return manager; } - async handleToolError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); - } - } - }, handler.awaitHandlers))); + else if (args.precision === 0) { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); + } } - async handleToolEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); - } - } - }, handler.awaitHandlers))); + else { + if (args.offset) { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); + } + else { + return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); + } + } +}; +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; } + return false; } -class CallbackManager extends BaseCallbackManager { - constructor(parentRunId) { - super(); - Object.defineProperty(this, "handlers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inheritableHandlers", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "inheritableTags", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: {} +class ZodString extends ZodType { + constructor() { + super(...arguments); + this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { + validation, + code: ZodError_1.ZodIssueCode.invalid_string, + ...errorUtil_1.errorUtil.errToObj(message), }); - Object.defineProperty(this, "inheritableMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: {} + this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message)); + this.trim = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "callback_manager" + this.toLowerCase = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], }); - Object.defineProperty(this, "_parentRunId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + this.toUpperCase = () => new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], }); - this.handlers = []; - this.inheritableHandlers = []; - this._parentRunId = parentRunId; } - async handleLLMStart(llm, prompts, _runId = undefined, _parentRunId = undefined, extraParams = undefined) { - return Promise.all(prompts.map(async (prompt) => { - const runId = (0,wrapper.v4)(); - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMStart?.(llm, [prompt], runId, this._parentRunId, extraParams, this.tags, this.metadata); - } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - } + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.string, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const status = new parseUtil_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); } - }, handler.awaitHandlers))); - return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChatModelStart(llm, messages, _runId = undefined, _parentRunId = undefined, extraParams = undefined) { - return Promise.all(messages.map(async (messageGroup) => { - const runId = (0,wrapper.v4)(); - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - if (handler.handleChatModelStart) - await handler.handleChatModelStart?.(llm, [messageGroup], runId, this._parentRunId, extraParams, this.tags, this.metadata); - else if (handler.handleLLMStart) { - const messageString = (0,memory_base/* getBufferString */.zs)(messageGroup); - await handler.handleLLMStart?.(llm, [messageString], runId, this._parentRunId, extraParams, this.tags, this.metadata); - } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + else if (tooSmall) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); } + status.dirty(); } - }, handler.awaitHandlers))); - return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChainStart(chain, inputs, runId = (0,wrapper.v4)(), runType = undefined) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType); + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "email", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + } + else if (check.kind === "emoji") { + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "emoji", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } } - }, handler.awaitHandlers))); - return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleToolStart(tool, input, runId = (0,wrapper.v4)()) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata); + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "uuid", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "cuid", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } } - }, handler.awaitHandlers))); - return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleRetrieverStart(retriever, query, runId = (0,wrapper.v4)(), _parentRunId = undefined) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "cuid2", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "ulid", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { try { - await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata); + new URL(input.data); } - catch (err) { - console.error(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + catch (_a) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "url", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } } - }, handler.awaitHandlers))); - return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - addHandler(handler, inherit = true) { - this.handlers.push(handler); - if (inherit) { - this.inheritableHandlers.push(handler); - } - } - removeHandler(handler) { - this.handlers = this.handlers.filter((_handler) => _handler !== handler); - this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); - } - setHandlers(handlers, inherit = true) { - this.handlers = []; - this.inheritableHandlers = []; - for (const handler of handlers) { - this.addHandler(handler, inherit); - } - } - addTags(tags, inherit = true) { - this.removeTags(tags); // Remove duplicates - this.tags.push(...tags); - if (inherit) { - this.inheritableTags.push(...tags); - } - } - removeTags(tags) { - this.tags = this.tags.filter((tag) => !tags.includes(tag)); - this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); - } - addMetadata(metadata, inherit = true) { - this.metadata = { ...this.metadata, ...metadata }; - if (inherit) { - this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; - } - } - removeMetadata(metadata) { - for (const key of Object.keys(metadata)) { - delete this.metadata[key]; - delete this.inheritableMetadata[key]; - } - } - copy(additionalHandlers = [], inherit = true) { - const manager = new CallbackManager(this._parentRunId); - for (const handler of this.handlers) { - const inheritable = this.inheritableHandlers.includes(handler); - manager.addHandler(handler, inheritable); - } - for (const tag of this.tags) { - const inheritable = this.inheritableTags.includes(tag); - manager.addTags([tag], inheritable); - } - for (const key of Object.keys(this.metadata)) { - const inheritable = Object.keys(this.inheritableMetadata).includes(key); - manager.addMetadata({ [key]: this.metadata[key] }, inheritable); - } - for (const handler of additionalHandlers) { - if ( - // Prevent multiple copies of console_callback_handler - manager.handlers - .filter((h) => h.name === "console_callback_handler") - .some((h) => h.name === handler.name)) { - continue; + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "regex", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - manager.addHandler(handler, inherit); - } - return manager; - } - static fromHandlers(handlers) { - class Handler extends base/* BaseCallbackHandler */.E { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: (0,wrapper.v4)() - }); - Object.assign(this, handlers); + else if (check.kind === "trim") { + input.data = input.data.trim(); } - } - const manager = new this(); - manager.addHandler(new Handler()); - return manager; - } - static async configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - let callbackManager; - if (inheritableHandlers || localHandlers) { - if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { - callbackManager = new CallbackManager(); - callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } } - else { - callbackManager = inheritableHandlers; + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); } - callbackManager = callbackManager.copy(Array.isArray(localHandlers) - ? localHandlers.map(ensureHandler) - : localHandlers?.handlers, false); - } - const verboseEnabled = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_VERBOSE") || options?.verbose; - const tracingV2Enabled = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_TRACING_V2") === "true"; - const tracingEnabled = tracingV2Enabled || - ((0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_TRACING") ?? false); - if (verboseEnabled || tracingEnabled) { - if (!callbackManager) { - callbackManager = new CallbackManager(); + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); } - if (verboseEnabled && - !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { - const consoleHandler = new ConsoleCallbackHandler(); - callbackManager.addHandler(consoleHandler, true); + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } } - if (tracingEnabled && - !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { - if (tracingV2Enabled) { - callbackManager.addHandler(await getTracingV2CallbackHandler(), true); + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); } - else { - const session = (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_PROJECT") && - (0,env/* getEnvironmentVariable */.lS)("LANGCHAIN_SESSION"); - callbackManager.addHandler(await getTracingCallbackHandler(session), true); + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); } } - } - if (inheritableTags || localTags) { - if (callbackManager) { - callbackManager.addTags(inheritableTags ?? []); - callbackManager.addTags(localTags ?? [], false); + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + validation: "ip", + code: ZodError_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } } - } - if (inheritableMetadata || localMetadata) { - if (callbackManager) { - callbackManager.addMetadata(inheritableMetadata ?? {}); - callbackManager.addMetadata(localMetadata ?? {}, false); + else { + util_1.util.assertNever(check); } } - return callbackManager; - } -} -function ensureHandler(handler) { - if ("name" in handler) { - return handler; + return { status: status.value, value: input.data }; } - return base/* BaseCallbackHandler.fromMethods */.E.fromMethods(handler); -} -class TraceGroup { - constructor(groupName, options) { - Object.defineProperty(this, "groupName", { - enumerable: true, - configurable: true, - writable: true, - value: groupName - }); - Object.defineProperty(this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - Object.defineProperty(this, "runManager", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], }); } - async getTraceGroupCallbackManager(group_name, inputs, options) { - const cb = new LangChainTracer(options); - const cm = await CallbackManager.configure([cb]); - const runManager = await cm?.handleChainStart({ - lc: 1, - type: "not_implemented", - id: ["langchain", "callbacks", "groups", group_name], - }, inputs ?? {}); - if (!runManager) { - throw new Error("Failed to create run group callback manager."); - } - return runManager; + email(message) { + return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); } - async start(inputs) { - if (!this.runManager) { - this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); - } - return this.runManager.getChild(); + url(message) { + return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); } - async error(err) { - if (this.runManager) { - await this.runManager.handleChainError(err); - this.runManager = undefined; - } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); } - async end(output) { - if (this.runManager) { - await this.runManager.handleChainEnd(output ?? {}); - this.runManager = undefined; - } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); } -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" - ? value - : { [defaultKey]: value }; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -async function traceAsGroup(groupOptions, enclosedCode, ...args) { - const traceGroup = new TraceGroup(groupOptions.name, groupOptions); - const callbackManager = await traceGroup.start({ ...args }); - try { - const result = await enclosedCode(callbackManager, ...args); - await traceGroup.end(_coerceToDict(result, "output")); - return result; + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); } - catch (err) { - await traceGroup.error(err); - throw err; + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); } -} - - -/***/ }), - -/***/ 6159: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "APIChain": () => (/* binding */ APIChain) -}); - -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js -var base = __nccwpck_require__(3197); -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 1 modules -var llm_chain = __nccwpck_require__(7287); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js -var prompts_prompt = __nccwpck_require__(3379); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/api/prompts.js -/* eslint-disable spaced-comment */ - -const API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation: -{api_docs} -Using this documentation, generate the full API url to call for answering the user question. -You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call. - -Question:{question} -API url:`; -const API_URL_PROMPT_TEMPLATE = /* #__PURE__ */ new prompts_prompt.PromptTemplate({ - inputVariables: ["api_docs", "question"], - template: API_URL_RAW_PROMPT_TEMPLATE, -}); -const API_RESPONSE_RAW_PROMPT_TEMPLATE = `${API_URL_RAW_PROMPT_TEMPLATE} {api_url} - -Here is the response from the API: - -{api_response} - -Summarize this response to answer the original question. - -Summary:`; -const API_RESPONSE_PROMPT_TEMPLATE = /* #__PURE__ */ new prompts_prompt.PromptTemplate({ - inputVariables: ["api_docs", "question", "api_url", "api_response"], - template: API_RESPONSE_RAW_PROMPT_TEMPLATE, -}); - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/api/api_chain.js - - - -/** - * Class that extends BaseChain and represents a chain specifically - * designed for making API requests and processing API responses. - */ -class APIChain extends base/* BaseChain */.l { - get inputKeys() { - return [this.inputKey]; + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); } - get outputKeys() { - return [this.outputKey]; + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); } - constructor(fields) { - super(fields); - Object.defineProperty(this, "apiAnswerChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + datetime(options) { + var _a; + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, + offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, + ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); - Object.defineProperty(this, "apiRequestChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil_1.errorUtil.errToObj(message), }); - Object.defineProperty(this, "apiDocs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options === null || options === void 0 ? void 0 : options.position, + ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); - Object.defineProperty(this, "headers", { - enumerable: true, - configurable: true, - writable: true, - value: {} + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil_1.errorUtil.errToObj(message), }); - Object.defineProperty(this, "inputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "question" + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil_1.errorUtil.errToObj(message), }); - Object.defineProperty(this, "outputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "output" + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_1.errorUtil.errToObj(message), }); - this.apiRequestChain = fields.apiRequestChain; - this.apiAnswerChain = fields.apiAnswerChain; - this.apiDocs = fields.apiDocs; - this.inputKey = fields.inputKey ?? this.inputKey; - this.outputKey = fields.outputKey ?? this.outputKey; - this.headers = fields.headers ?? this.headers; } - /** @ignore */ - async _call(values, runManager) { - const question = values[this.inputKey]; - const api_url = await this.apiRequestChain.predict({ question, api_docs: this.apiDocs }, runManager?.getChild("request")); - const res = await fetch(api_url, { headers: this.headers }); - const api_response = await res.text(); - const answer = await this.apiAnswerChain.predict({ question, api_docs: this.apiDocs, api_url, api_response }, runManager?.getChild("response")); - return { [this.outputKey]: answer }; + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_1.errorUtil.errToObj(message), + }); } - _chainType() { - return "api_chain"; + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_1.errorUtil.errToObj(message), + }); } - static async deserialize(data) { - const { api_request_chain, api_answer_chain, api_docs } = data; - if (!api_request_chain) { - throw new Error("LLMChain must have api_request_chain"); + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } } - if (!api_answer_chain) { - throw new Error("LLMChain must have api_answer_chain"); + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - if (!api_docs) { - throw new Error("LLMChain must have api_docs"); + return max; + } +} +exports.ZodString = ZodString; +ZodString.create = (params) => { + var _a; + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / Math.pow(10, decCount); +} +class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); } - return new APIChain({ - apiAnswerChain: await llm_chain.LLMChain.deserialize(api_answer_chain), - apiRequestChain: await llm_chain.LLMChain.deserialize(api_request_chain), - apiDocs: api_docs, + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.number, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + let ctx = undefined; + const status = new parseUtil_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_1.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_1.errorUtil.toString(message), + }, + ], }); } - serialize() { - return { - _type: this._chainType(), - api_answer_chain: this.apiAnswerChain.serialize(), - api_request_chain: this.apiRequestChain.serialize(), - api_docs: this.apiDocs, - }; + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); } - /** - * Static method to create a new APIChain from a BaseLanguageModel and API - * documentation. - * @param llm BaseLanguageModel instance. - * @param apiDocs API documentation. - * @param options Optional configuration options for the APIChain. - * @returns New APIChain instance. - */ - static fromLLMAndAPIDocs(llm, apiDocs, options = {}) { - const { apiUrlPrompt = API_URL_PROMPT_TEMPLATE, apiResponsePrompt = API_RESPONSE_PROMPT_TEMPLATE, } = options; - const apiRequestChain = new llm_chain.LLMChain({ prompt: apiUrlPrompt, llm }); - const apiAnswerChain = new llm_chain.LLMChain({ prompt: apiResponsePrompt, llm }); - return new this({ - apiAnswerChain, - apiRequestChain, - apiDocs, - ...options, + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_1.errorUtil.toString(message), }); } -} - - -/***/ }), - -/***/ 3197: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "l": () => (/* binding */ BaseChain) -/* harmony export */ }); -/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(8102); -/* harmony import */ var _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(6009); -/* harmony import */ var _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(7679); - - - -/** - * Base interface that all chains must implement. - */ -class BaseChain extends _base_language_index_js__WEBPACK_IMPORTED_MODULE_2__/* .BaseLangChain */ .BD { - get lc_namespace() { - return ["langchain", "chains", this._chainType()]; + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); } - constructor(fields, - /** @deprecated */ - verbose, - /** @deprecated */ - callbacks) { - if (arguments.length === 1 && - typeof fields === "object" && - !("saveContext" in fields)) { - // fields is not a BaseMemory - const { memory, callbackManager, ...rest } = fields; - super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); - this.memory = memory; - } - else { - // fields is a BaseMemory - super({ verbose, callbacks }); - this.memory = fields; - } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); } - /** @ignore */ - _selectMemoryInputs(values) { - const valuesForMemory = { ...values }; - if ("signal" in valuesForMemory) { - delete valuesForMemory.signal; - } - if ("timeout" in valuesForMemory) { - delete valuesForMemory.timeout; - } - return valuesForMemory; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); } - /** - * Invoke the chain with the provided input and returns the output. - * @param input Input values for the chain run. - * @param config Optional configuration for the Runnable. - * @returns Promise that resolves with the output of the chain run. - */ - async invoke(input, config) { - return this.call(input, config); + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); } - /** - * Return a json-like object representing this chain. - */ - serialize() { - throw new Error("Method not implemented."); + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil_1.errorUtil.toString(message), + }); } - async run( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - input, config) { - const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); - const isKeylessInput = inputKeys.length <= 1; - if (!isKeylessInput) { - throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; - const returnValues = await this.call(values, config); - const keys = Object.keys(returnValues); - if (keys.length === 1) { - return returnValues[keys[0]]; - } - throw new Error("return values have multiple keys, `run` only supported when one key currently"); + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_1.errorUtil.toString(message), + }); } - async _formatValues(values) { - const fullValues = { ...values }; - if (fullValues.timeout && !fullValues.signal) { - fullValues.signal = AbortSignal.timeout(fullValues.timeout); - delete fullValues.timeout; - } - if (!(this.memory == null)) { - const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); - for (const [key, value] of Object.entries(newValues)) { - fullValues[key] = value; + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_1.errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_1.errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } } - return fullValues; + return min; } - /** - * Run the core logic of this chain and add to output if desired. - * - * Wraps _call and handles memory. - */ - async call(values, config, - /** @deprecated */ - tags) { - const fullValues = await this._formatValues(values); - const parsedConfig = (0,_callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .parseCallbackConfigArg */ .QH)(config); - const callbackManager_ = await _callbacks_manager_js__WEBPACK_IMPORTED_MODULE_1__/* .CallbackManager.configure */ .Ye.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); - let outputValues; - try { - outputValues = await (values.signal - ? Promise.race([ - this._call(fullValues, runManager), - new Promise((_, reject) => { - values.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]) - : this._call(fullValues, runManager)); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - if (!(this.memory == null)) { - await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - await runManager?.handleChainEnd(outputValues); - // add the runManager's currentRunId to the outputValues - Object.defineProperty(outputValues, _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .RUN_KEY */ .WH, { - value: runManager ? { runId: runManager?.runId } : undefined, - configurable: true, - }); - return outputValues; + return max; } - /** - * Call the chain on all inputs in the list - */ - async apply(inputs, config) { - return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || + (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); } - /** - * Load a chain from a json-like object describing it. - */ - static async deserialize(data, values = {}) { - switch (data._type) { - case "llm_chain": { - const { LLMChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 7287)); - return LLMChain.deserialize(data); - } - case "sequential_chain": { - const { SequentialChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 7210)); - return SequentialChain.deserialize(data); + get isFinite() { + let max = null, min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || + ch.kind === "int" || + ch.kind === "multipleOf") { + return true; } - case "simple_sequential_chain": { - const { SimpleSequentialChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 7210)); - return SimpleSequentialChain.deserialize(data); + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - case "stuff_documents_chain": { - const { StuffDocumentsChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 3608)); - return StuffDocumentsChain.deserialize(data); + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - case "map_reduce_documents_chain": { - const { MapReduceDocumentsChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 3608)); - return MapReduceDocumentsChain.deserialize(data); + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +exports.ZodNumber = ZodNumber; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); +}; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + input.data = BigInt(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.bigint) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.bigint, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + let ctx = undefined; + const status = new parseUtil_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive + ? input.data < check.value + : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } } - case "refine_documents_chain": { - const { RefineDocumentsChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 3608)); - return RefineDocumentsChain.deserialize(data); + else if (check.kind === "max") { + const tooBig = check.inclusive + ? input.data > check.value + : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } } - case "vector_db_qa": { - const { VectorDBQAChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 9518)); - return VectorDBQAChain.deserialize(data, values); + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } } - case "api_chain": { - const { APIChain } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 6159)); - return APIChain.deserialize(data); + else { + util_1.util.assertNever(check); } - default: - throw new Error(`Invalid prompt type in config: ${data._type}`); } + return { status: status.value, value: input.data }; } -} - - -/***/ }), - -/***/ 3608: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -__nccwpck_require__.r(__webpack_exports__); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "MapReduceDocumentsChain": () => (/* binding */ MapReduceDocumentsChain), -/* harmony export */ "RefineDocumentsChain": () => (/* binding */ RefineDocumentsChain), -/* harmony export */ "StuffDocumentsChain": () => (/* binding */ StuffDocumentsChain) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(3197); -/* harmony import */ var _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(7287); -/* harmony import */ var _prompts_prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(3379); - - - -/** - * Chain that combines documents by stuffing into context. - * @augments BaseChain - * @augments StuffDocumentsChainInput - */ -class StuffDocumentsChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { - static lc_name() { - return "StuffDocumentsChain"; + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); } - get inputKeys() { - return [this.inputKey, ...this.llmChain.inputKeys].filter((key) => key !== this.documentVariableName); + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); } - get outputKeys() { - return this.llmChain.outputKeys; + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); } - constructor(fields) { - super(fields); - Object.defineProperty(this, "llmChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_1.errorUtil.toString(message), + }, + ], }); - Object.defineProperty(this, "inputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "input_documents" + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], }); - Object.defineProperty(this, "documentVariableName", { - enumerable: true, - configurable: true, - writable: true, - value: "context" + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), }); - this.llmChain = fields.llmChain; - this.documentVariableName = - fields.documentVariableName ?? this.documentVariableName; - this.inputKey = fields.inputKey ?? this.inputKey; } - /** @ignore */ - _prepInputs(values) { - if (!(this.inputKey in values)) { - throw new Error(`Document key ${this.inputKey} not found.`); + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_1.errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_1.errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_1.errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +exports.ZodBigInt = ZodBigInt; +ZodBigInt.create = (params) => { + var _a; + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + ...processCreateParams(params), + }); +}; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.boolean, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodBoolean = ZodBoolean; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.date, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + if (isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_date, + }); + return parseUtil_1.INVALID; } - const { [this.inputKey]: docs, ...rest } = values; - const texts = docs.map(({ pageContent }) => pageContent); - const text = texts.join("\n\n"); - return { - ...rest, - [this.documentVariableName]: text, - }; - } - /** @ignore */ - async _call(values, runManager) { - const result = await this.llmChain.call(this._prepInputs(values), runManager?.getChild("combine_documents")); - return result; - } - _chainType() { - return "stuff_documents_chain"; - } - static async deserialize(data) { - if (!data.llm_chain) { - throw new Error("Missing llm_chain"); + const status = new parseUtil_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util_1.util.assertNever(check); + } } - return new StuffDocumentsChain({ - llmChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(data.llm_chain), - }); - } - serialize() { return { - _type: this._chainType(), - llm_chain: this.llmChain.serialize(), + status: status.value, + value: new Date(input.data.getTime()), }; } -} -/** - * Combine documents by mapping a chain over them, then combining results. - * @augments BaseChain - * @augments StuffDocumentsChainInput - */ -class MapReduceDocumentsChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { - static lc_name() { - return "MapReduceDocumentsChain"; - } - get inputKeys() { - return [this.inputKey, ...this.combineDocumentChain.inputKeys]; - } - get outputKeys() { - return this.combineDocumentChain.outputKeys; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "llmChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "input_documents" - }); - Object.defineProperty(this, "documentVariableName", { - enumerable: true, - configurable: true, - writable: true, - value: "context" - }); - Object.defineProperty(this, "returnIntermediateSteps", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "maxTokens", { - enumerable: true, - configurable: true, - writable: true, - value: 3000 - }); - Object.defineProperty(this, "maxIterations", { - enumerable: true, - configurable: true, - writable: true, - value: 10 + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], }); - Object.defineProperty(this, "ensureMapStep", { - enumerable: true, - configurable: true, - writable: true, - value: false + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_1.errorUtil.toString(message), }); - Object.defineProperty(this, "combineDocumentChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_1.errorUtil.toString(message), }); - this.llmChain = fields.llmChain; - this.combineDocumentChain = fields.combineDocumentChain; - this.documentVariableName = - fields.documentVariableName ?? this.documentVariableName; - this.ensureMapStep = fields.ensureMapStep ?? this.ensureMapStep; - this.inputKey = fields.inputKey ?? this.inputKey; - this.maxTokens = fields.maxTokens ?? this.maxTokens; - this.maxIterations = fields.maxIterations ?? this.maxIterations; - this.returnIntermediateSteps = fields.returnIntermediateSteps ?? false; } - /** @ignore */ - async _call(values, runManager) { - if (!(this.inputKey in values)) { - throw new Error(`Document key ${this.inputKey} not found.`); - } - const { [this.inputKey]: docs, ...rest } = values; - let currentDocs = docs; - let intermediateSteps = []; - // For each iteration, we'll use the `llmChain` to get a new result - for (let i = 0; i < this.maxIterations; i += 1) { - const inputs = currentDocs.map((d) => ({ - [this.documentVariableName]: d.pageContent, - ...rest, - })); - const canSkipMapStep = i !== 0 || !this.ensureMapStep; - if (canSkipMapStep) { - // Calculate the total tokens required in the input - const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({ - [this.combineDocumentChain.inputKey]: currentDocs, - ...rest, - })); - const length = await this.combineDocumentChain.llmChain.llm.getNumTokens(formatted); - const withinTokenLimit = length < this.maxTokens; - // If we can skip the map step, and we're within the token limit, we don't - // need to run the map step, so just break out of the loop. - if (withinTokenLimit) { - break; - } - } - const results = await this.llmChain.apply(inputs, - // If we have a runManager, then we need to create a child for each input - // so that we can track the progress of each input. - runManager - ? Array.from({ length: inputs.length }, (_, i) => runManager.getChild(`map_${i + 1}`)) - : undefined); - const { outputKey } = this.llmChain; - // If the flag is set, then concat that to the intermediate steps - if (this.returnIntermediateSteps) { - intermediateSteps = intermediateSteps.concat(results.map((r) => r[outputKey])); + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - currentDocs = results.map((r) => ({ - pageContent: r[outputKey], - metadata: {}, - })); - } - // Now, with the final result of all the inputs from the `llmChain`, we can - // run the `combineDocumentChain` over them. - const newInputs = { - [this.combineDocumentChain.inputKey]: currentDocs, - ...rest, - }; - const result = await this.combineDocumentChain.call(newInputs, runManager?.getChild("combine_documents")); - // Return the intermediate steps results if the flag is set - if (this.returnIntermediateSteps) { - return { ...result, intermediateSteps }; } - return result; + return min != null ? new Date(min) : null; } - _chainType() { - return "map_reduce_documents_chain"; + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; } - static async deserialize(data) { - if (!data.llm_chain) { - throw new Error("Missing llm_chain"); +} +exports.ZodDate = ZodDate; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.symbol, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; } - if (!data.combine_document_chain) { - throw new Error("Missing combine_document_chain"); + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodSymbol = ZodSymbol; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.undefined, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; } - return new MapReduceDocumentsChain({ - llmChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(data.llm_chain), - combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain), - }); + return (0, parseUtil_1.OK)(input.data); } - serialize() { - return { - _type: this._chainType(), - llm_chain: this.llmChain.serialize(), - combine_document_chain: this.combineDocumentChain.serialize(), - }; +} +exports.ZodUndefined = ZodUndefined; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.null, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); } } -/** - * Combine documents by doing a first pass and then refining on more documents. - * @augments BaseChain - * @augments RefineDocumentsChainInput - */ -class RefineDocumentsChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { - static lc_name() { - return "RefineDocumentsChain"; +exports.ZodNull = ZodNull; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + this._any = true; } - get defaultDocumentPrompt() { - return new _prompts_prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate({ - inputVariables: ["page_content"], - template: "{page_content}", - }); + _parse(input) { + return (0, parseUtil_1.OK)(input.data); } - get inputKeys() { - return [ - ...new Set([ - this.inputKey, - ...this.llmChain.inputKeys, - ...this.refineLLMChain.inputKeys, - ]), - ].filter((key) => key !== this.documentVariableName && key !== this.initialResponseName); +} +exports.ZodAny = ZodAny; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; } - get outputKeys() { - return [this.outputKey]; + _parse(input) { + return (0, parseUtil_1.OK)(input.data); } - constructor(fields) { - super(fields); - Object.defineProperty(this, "llmChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "input_documents" - }); - Object.defineProperty(this, "outputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "output_text" - }); - Object.defineProperty(this, "documentVariableName", { - enumerable: true, - configurable: true, - writable: true, - value: "context" - }); - Object.defineProperty(this, "initialResponseName", { - enumerable: true, - configurable: true, - writable: true, - value: "existing_answer" - }); - Object.defineProperty(this, "refineLLMChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "documentPrompt", { - enumerable: true, - configurable: true, - writable: true, - value: this.defaultDocumentPrompt +} +exports.ZodUnknown = ZodUnknown; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.never, + received: ctx.parsedType, }); - this.llmChain = fields.llmChain; - this.refineLLMChain = fields.refineLLMChain; - this.documentVariableName = - fields.documentVariableName ?? this.documentVariableName; - this.inputKey = fields.inputKey ?? this.inputKey; - this.outputKey = fields.outputKey ?? this.outputKey; - this.documentPrompt = fields.documentPrompt ?? this.documentPrompt; - this.initialResponseName = - fields.initialResponseName ?? this.initialResponseName; + return parseUtil_1.INVALID; } - /** @ignore */ - async _constructInitialInputs(doc, rest) { - const baseInfo = { - page_content: doc.pageContent, - ...doc.metadata, - }; - const documentInfo = {}; - this.documentPrompt.inputVariables.forEach((value) => { - documentInfo[value] = baseInfo[value]; +} +exports.ZodNever = ZodNever; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.void, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + return (0, parseUtil_1.OK)(input.data); + } +} +exports.ZodVoid = ZodVoid; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== util_1.ZodParsedType.array) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return parseUtil_1.ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); - const baseInputs = { - [this.documentVariableName]: await this.documentPrompt.format({ - ...documentInfo, - }), - }; - const inputs = { ...baseInputs, ...rest }; - return inputs; + return parseUtil_1.ParseStatus.mergeArray(status, result); } - /** @ignore */ - async _constructRefineInputs(doc, res) { - const baseInfo = { - page_content: doc.pageContent, - ...doc.metadata, - }; - const documentInfo = {}; - this.documentPrompt.inputVariables.forEach((value) => { - documentInfo[value] = baseInfo[value]; - }); - const baseInputs = { - [this.documentVariableName]: await this.documentPrompt.format({ - ...documentInfo, - }), - }; - const inputs = { [this.initialResponseName]: res, ...baseInputs }; - return inputs; + get element() { + return this._def.type; } - /** @ignore */ - async _call(values, runManager) { - if (!(this.inputKey in values)) { - throw new Error(`Document key ${this.inputKey} not found.`); - } - const { [this.inputKey]: docs, ...rest } = values; - const currentDocs = docs; - const initialInputs = await this._constructInitialInputs(currentDocs[0], rest); - let res = await this.llmChain.predict({ ...initialInputs }, runManager?.getChild("answer")); - const refineSteps = [res]; - for (let i = 1; i < currentDocs.length; i += 1) { - const refineInputs = await this._constructRefineInputs(currentDocs[i], res); - const inputs = { ...refineInputs, ...rest }; - res = await this.refineLLMChain.predict({ ...inputs }, runManager?.getChild("refine")); - refineSteps.push(res); - } - return { [this.outputKey]: res }; + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, + }); } - _chainType() { - return "refine_documents_chain"; + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, + }); } - static async deserialize(data) { - const SerializedLLMChain = data.llm_chain; - if (!SerializedLLMChain) { - throw new Error("Missing llm_chain"); - } - const SerializedRefineDocumentChain = data.refine_llm_chain; - if (!SerializedRefineDocumentChain) { - throw new Error("Missing refine_llm_chain"); - } - return new RefineDocumentsChain({ - llmChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(SerializedLLMChain), - refineLLMChain: await _llm_chain_js__WEBPACK_IMPORTED_MODULE_1__.LLMChain.deserialize(SerializedRefineDocumentChain), + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, }); } - serialize() { - return { - _type: this._chainType(), - llm_chain: this.llmChain.serialize(), - refine_llm_chain: this.refineLLMChain.serialize(), - }; + nonempty(message) { + return this.min(1, message); } } - - -/***/ }), - -/***/ 7287: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "LLMChain": () => (/* binding */ LLMChain) -}); - -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js -var base = __nccwpck_require__(3197); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js -var prompts_base = __nccwpck_require__(5411); -// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules -var base_language = __nccwpck_require__(7679); -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/output_parser.js -var output_parser = __nccwpck_require__(3175); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/output_parsers/noop.js - -/** - * The NoOpOutputParser class is a type of output parser that does not - * perform any operations on the output. It extends the BaseOutputParser - * class and is part of the LangChain's output parsers module. This class - * is useful in scenarios where the raw output of the Large Language - * Models (LLMs) is required. - */ -class NoOpOutputParser extends output_parser/* BaseOutputParser */.bI { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "output_parsers", "default"] +exports.ZodArray = ZodArray; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), }); } - static lc_name() { - return "NoOpOutputParser"; + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); } - /** - * This method takes a string as input and returns the same string as - * output. It does not perform any operations on the input string. - * @param text The input string to be parsed. - * @returns The same input string without any operations performed on it. - */ - parse(text) { - return Promise.resolve(text); + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); } - /** - * This method returns an empty string. It does not provide any formatting - * instructions. - * @returns An empty string, indicating no formatting instructions. - */ - getFormatInstructions() { - return ""; + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); } -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/llm_chain.js - - - - -/** - * Chain to run queries against LLMs. - * - * @example - * ```ts - * import { LLMChain } from "langchain/chains"; - * import { OpenAI } from "langchain/llms/openai"; - * import { PromptTemplate } from "langchain/prompts"; - * - * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); - * const llm = new LLMChain({ llm: new OpenAI(), prompt }); - * ``` - */ -class LLMChain extends base/* BaseChain */.l { - static lc_name() { - return "LLMChain"; + else { + return schema; } - get inputKeys() { - return this.prompt.inputVariables; +} +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; } - get outputKeys() { - return [this.outputKey]; + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util_1.util.objectKeys(shape); + return (this._cached = { shape, keys }); } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "prompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "llm", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "llmKwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "text" - }); - Object.defineProperty(this, "outputParser", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.prompt = fields.prompt; - this.llm = fields.llm; - this.llmKwargs = fields.llmKwargs; - this.outputKey = fields.outputKey ?? this.outputKey; - this.outputParser = - fields.outputParser ?? new NoOpOutputParser(); - if (this.prompt.outputParser) { - if (fields.outputParser) { - throw new Error("Cannot set both outputParser and prompt.outputParser"); + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && + this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } } - this.outputParser = this.prompt.outputParser; } - } - /** @ignore */ - _selectMemoryInputs(values) { - const valuesForMemory = super._selectMemoryInputs(values); - for (const key of this.llm.callKeys) { - if (key in values) { - delete valuesForMemory[key]; + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } - return valuesForMemory; - } - /** @ignore */ - async _getFinalOutput(generations, promptValue, runManager) { - let finalCompletion; - if (this.outputParser) { - finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + syncPairs.push({ + key, + value: await pair.value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); + }); } else { - finalCompletion = generations[0].text; + return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); } - return finalCompletion; } - /** - * Run the core logic of this chain and add to output if desired. - * - * Wraps _call and handles memory. - */ - call(values, config) { - return super.call(values, config); + get shape() { + return this._def.shape(); } - /** @ignore */ - async _call(values, runManager) { - const valuesForPrompt = { ...values }; - const valuesForLLM = { - ...this.llmKwargs, - }; - for (const key of this.llm.callKeys) { - if (key in values) { - valuesForLLM[key] = values[key]; - delete valuesForPrompt[key]; - } - } - const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); - const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); - return { - [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), - }; + strict(message) { + errorUtil_1.errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + var _a, _b, _c, _d; + 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; + if (issue.code === "unrecognized_keys") + return { + message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); } - /** - * Format prompt with values and pass to LLM - * - * @param values - keys to pass to prompt template - * @param callbackManager - CallbackManager to use - * @returns Completion from LLM. - * - * @example - * ```ts - * llm.predict({ adjective: "funny" }) - * ``` - */ - async predict(values, callbackManager) { - const output = await this.call(values, callbackManager); - return output[this.outputKey]; + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); } - _chainType() { - return "llm"; + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); } - static async deserialize(data) { - const { llm, prompt } = data; - if (!llm) { - throw new Error("LLMChain must have llm"); - } - if (!prompt) { - throw new Error("LLMChain must have prompt"); - } - return new LLMChain({ - llm: await base_language/* BaseLanguageModel.deserialize */.qV.deserialize(llm), - prompt: await prompts_base/* BasePromptTemplate.deserialize */.dy.deserialize(prompt), + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), }); } - /** @deprecated */ - serialize() { - return { - _type: `${this._chainType()}_chain`, - llm: this.llm.serialize(), - prompt: this.prompt.serialize(), - }; + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; } -} - - -/***/ }), - -/***/ 3504: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "cf": () => (/* binding */ loadQAStuffChain) -}); - -// UNUSED EXPORTS: loadQAChain, loadQAMapReduceChain, loadQARefineChain - -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 1 modules -var llm_chain = __nccwpck_require__(7287); -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/combine_docs_chain.js -var combine_docs_chain = __nccwpck_require__(3608); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js -var prompts_prompt = __nccwpck_require__(3379); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/chat.js -var chat = __nccwpck_require__(6704); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/conditional.js -/** - * Abstract class that defines the interface for selecting a prompt for a - * given language model. - */ -class BasePromptSelector { - /** - * Asynchronous version of `getPrompt` that also accepts an options object - * for partial variables. - * @param llm The language model for which to get a prompt. - * @param options Optional object for partial variables. - * @returns A Promise that resolves to a prompt template. - */ - async getPromptAsync(llm, options) { - const prompt = this.getPrompt(llm); - return prompt.partial(options?.partialVariables ?? {}); + setKey(key, schema) { + return this.augment({ [key]: schema }); } -} -/** - * Concrete implementation of `BasePromptSelector` that selects a prompt - * based on a set of conditions. It has a default prompt that it returns - * if none of the conditions are met. - */ -class ConditionalPromptSelector extends BasePromptSelector { - constructor(default_prompt, conditionals = []) { - super(); - Object.defineProperty(this, "defaultPrompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, }); - Object.defineProperty(this, "conditionals", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + pick(mask) { + const shape = {}; + util_1.util.objectKeys(mask).forEach((key) => { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + }); + return new ZodObject({ + ...this._def, + shape: () => shape, }); - this.defaultPrompt = default_prompt; - this.conditionals = conditionals; } - /** - * Method that selects a prompt based on a set of conditions. If none of - * the conditions are met, it returns the default prompt. - * @param llm The language model for which to get a prompt. - * @returns A prompt template. - */ - getPrompt(llm) { - for (const [condition, prompt] of this.conditionals) { - if (condition(llm)) { - return prompt; + omit(mask) { + const shape = {}; + util_1.util.objectKeys(this.shape).forEach((key) => { + if (!mask[key]) { + shape[key] = this.shape[key]; } - } - return this.defaultPrompt; + }); + return new ZodObject({ + ...this._def, + shape: () => shape, + }); } -} -/** - * Type guard function that checks if a given language model is of type - * `BaseLLM`. - */ -function isLLM(llm) { - return llm._modelType() === "base_llm"; -} -/** - * Type guard function that checks if a given language model is of type - * `BaseChatModel`. - */ -function isChatModel(llm) { - return llm._modelType() === "base_chat_model"; -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/stuff_prompts.js -/* eslint-disable spaced-comment */ - - - -const DEFAULT_QA_PROMPT = /*#__PURE__*/ new prompts_prompt.PromptTemplate({ - template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", - inputVariables: ["context", "question"], -}); -const system_template = `Use the following pieces of context to answer the users question. -If you don't know the answer, just say that you don't know, don't try to make up an answer. ----------------- -{context}`; -const messages = [ - /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(system_template), - /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), -]; -const CHAT_PROMPT = /*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(messages); -const QA_PROMPT_SELECTOR = /*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_QA_PROMPT, [[isChatModel, CHAT_PROMPT]]); - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js -/* eslint-disable spaced-comment */ - - - -const qa_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. -Return any relevant text verbatim. -{context} -Question: {question} -Relevant text, if any:`; -const DEFAULT_COMBINE_QA_PROMPT = -/*#__PURE__*/ -prompts_prompt.PromptTemplate.fromTemplate(qa_template); -const map_reduce_prompts_system_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. -Return any relevant text verbatim. ----------------- -{context}`; -const map_reduce_prompts_messages = [ - /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(map_reduce_prompts_system_template), - /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), -]; -const CHAT_QA_PROMPT = /*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(map_reduce_prompts_messages); -const map_reduce_prompts_COMBINE_QA_PROMPT_SELECTOR = -/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_COMBINE_QA_PROMPT, [ - [isChatModel, CHAT_QA_PROMPT], -]); -const combine_prompt = `Given the following extracted parts of a long document and a question, create a final answer. -If you don't know the answer, just say that you don't know. Don't try to make up an answer. - -QUESTION: Which state/country's law governs the interpretation of the contract? -========= -Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. - -Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties.\n\n11.9 No Third-Party Beneficiaries. - -Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, -========= -FINAL ANSWER: This Agreement is governed by English law. - -QUESTION: What did the president say about Michael Jackson? -========= -Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. - -Content: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. - -Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay. - -Content: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation. -========= -FINAL ANSWER: The president did not mention Michael Jackson. - -QUESTION: {question} -========= -{summaries} -========= -FINAL ANSWER:`; -const COMBINE_PROMPT = -/*#__PURE__*/ prompts_prompt.PromptTemplate.fromTemplate(combine_prompt); -const system_combine_template = `Given the following extracted parts of a long document and a question, create a final answer. -If you don't know the answer, just say that you don't know. Don't try to make up an answer. ----------------- -{summaries}`; -const combine_messages = [ - /*#__PURE__*/ chat/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(system_combine_template), - /*#__PURE__*/ chat/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), -]; -const CHAT_COMBINE_PROMPT = -/*#__PURE__*/ chat/* ChatPromptTemplate.fromMessages */.ks.fromMessages(combine_messages); -const map_reduce_prompts_COMBINE_PROMPT_SELECTOR = -/*#__PURE__*/ new ConditionalPromptSelector(COMBINE_PROMPT, [ - [isChatModel, CHAT_COMBINE_PROMPT], -]); - -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/index.js + 3 modules -var prompts = __nccwpck_require__(4910); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/refine_prompts.js -/* eslint-disable spaced-comment */ - - -const DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question} -We have provided an existing answer: {existing_answer} -We have the opportunity to refine the existing answer -(only if needed) with some more context below. ------------- -{context} ------------- -Given the new context, refine the original answer to better answer the question. -If the context isn't useful, return the original answer.`; -const DEFAULT_REFINE_PROMPT = /*#__PURE__*/ new prompts/* PromptTemplate */.Pf({ - inputVariables: ["question", "existing_answer", "context"], - template: DEFAULT_REFINE_PROMPT_TMPL, -}); -const refineTemplate = `The original question is as follows: {question} -We have provided an existing answer: {existing_answer} -We have the opportunity to refine the existing answer -(only if needed) with some more context below. ------------- -{context} ------------- -Given the new context, refine the original answer to better answer the question. -If the context isn't useful, return the original answer.`; -const refine_prompts_messages = [ - /*#__PURE__*/ prompts/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), - /*#__PURE__*/ prompts/* AIMessagePromptTemplate.fromTemplate */.gc.fromTemplate("{existing_answer}"), - /*#__PURE__*/ prompts/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate(refineTemplate), -]; -const CHAT_REFINE_PROMPT = -/*#__PURE__*/ prompts/* ChatPromptTemplate.fromMessages */.ks.fromMessages(refine_prompts_messages); -const refine_prompts_REFINE_PROMPT_SELECTOR = -/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_REFINE_PROMPT, [ - [isChatModel, CHAT_REFINE_PROMPT], -]); -const DEFAULT_TEXT_QA_PROMPT_TMPL = `Context information is below. ---------------------- -{context} ---------------------- -Given the context information and no prior knowledge, answer the question: {question}`; -const DEFAULT_TEXT_QA_PROMPT = /*#__PURE__*/ new prompts/* PromptTemplate */.Pf({ - inputVariables: ["context", "question"], - template: DEFAULT_TEXT_QA_PROMPT_TMPL, -}); -const chat_qa_prompt_template = `Context information is below. ---------------------- -{context} ---------------------- -Given the context information and no prior knowledge, answer any questions`; -const chat_messages = [ - /*#__PURE__*/ prompts/* SystemMessagePromptTemplate.fromTemplate */.ov.fromTemplate(chat_qa_prompt_template), - /*#__PURE__*/ prompts/* HumanMessagePromptTemplate.fromTemplate */.kq.fromTemplate("{question}"), -]; -const CHAT_QUESTION_PROMPT = -/*#__PURE__*/ prompts/* ChatPromptTemplate.fromMessages */.ks.fromMessages(chat_messages); -const refine_prompts_QUESTION_PROMPT_SELECTOR = -/*#__PURE__*/ new ConditionalPromptSelector(DEFAULT_TEXT_QA_PROMPT, [ - [isChatModel, CHAT_QUESTION_PROMPT], -]); - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/question_answering/load.js - - - - - -const loadQAChain = (llm, params = { type: "stuff" }) => { - const { type } = params; - if (type === "stuff") { - return loadQAStuffChain(llm, params); + deepPartial() { + return deepPartialify(this); } - if (type === "map_reduce") { - return loadQAMapReduceChain(llm, params); + partial(mask) { + const newShape = {}; + util_1.util.objectKeys(this.shape).forEach((key) => { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); } - if (type === "refine") { - return loadQARefineChain(llm, params); + required(mask) { + const newShape = {}; + util_1.util.objectKeys(this.shape).forEach((key) => { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + }); + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util_1.util.objectKeys(this.shape)); } - throw new Error(`Invalid _type: ${type}`); -}; -/** - * Loads a StuffQAChain based on the provided parameters. It takes an LLM - * instance and StuffQAChainParams as parameters. - * @param llm An instance of BaseLanguageModel. - * @param params Parameters for creating a StuffQAChain. - * @returns A StuffQAChain instance. - */ -function loadQAStuffChain(llm, params = {}) { - const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; - const llmChain = new llm_chain.LLMChain({ prompt, llm, verbose }); - const chain = new combine_docs_chain.StuffDocumentsChain({ llmChain, verbose }); - return chain; } -/** - * Loads a MapReduceQAChain based on the provided parameters. It takes an - * LLM instance and MapReduceQAChainParams as parameters. - * @param llm An instance of BaseLanguageModel. - * @param params Parameters for creating a MapReduceQAChain. - * @returns A MapReduceQAChain instance. - */ -function loadQAMapReduceChain(llm, params = {}) { - const { combineMapPrompt = COMBINE_QA_PROMPT_SELECTOR.getPrompt(llm), combinePrompt = COMBINE_PROMPT_SELECTOR.getPrompt(llm), verbose, combineLLM, returnIntermediateSteps, } = params; - const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose }); - const combineLLMChain = new LLMChain({ - prompt: combinePrompt, - llm: combineLLM ?? llm, - verbose, - }); - const combineDocumentChain = new StuffDocumentsChain({ - llmChain: combineLLMChain, - documentVariableName: "summaries", - verbose, - }); - const chain = new MapReduceDocumentsChain({ - llmChain, - combineDocumentChain, - returnIntermediateSteps, - verbose, +exports.ZodObject = ZodObject; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), }); - return chain; -} -/** - * Loads a RefineQAChain based on the provided parameters. It takes an LLM - * instance and RefineQAChainParams as parameters. - * @param llm An instance of BaseLanguageModel. - * @param params Parameters for creating a RefineQAChain. - * @returns A RefineQAChain instance. - */ -function loadQARefineChain(llm, params = {}) { - const { questionPrompt = QUESTION_PROMPT_SELECTOR.getPrompt(llm), refinePrompt = REFINE_PROMPT_SELECTOR.getPrompt(llm), refineLLM, verbose, } = params; - const llmChain = new LLMChain({ prompt: questionPrompt, llm, verbose }); - const refineLLMChain = new LLMChain({ - prompt: refinePrompt, - llm: refineLLM ?? llm, - verbose, +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), }); - const chain = new RefineDocumentsChain({ - llmChain, - refineLLMChain, - verbose, +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), }); - return chain; -} - - -/***/ }), - -/***/ 7210: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "SequentialChain": () => (/* binding */ SequentialChain), - "SimpleSequentialChain": () => (/* binding */ SimpleSequentialChain) -}); - -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js -var base = __nccwpck_require__(3197); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/set.js -/** - * Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#implementing_basic_set_operations - */ -/** - * returns intersection of two sets - */ -function intersection(setA, setB) { - const _intersection = new Set(); - for (const elem of setB) { - if (setA.has(elem)) { - _intersection.add(elem); +}; +class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_1.INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_1.INVALID; } } - return _intersection; -} -/** - * returns union of two sets - */ -function union(setA, setB) { - const _union = new Set(setA); - for (const elem of setB) { - _union.add(elem); + get options() { + return this._def.options; } - return _union; } -/** - * returns difference of two sets - */ -function difference(setA, setB) { - const _difference = new Set(setA); - for (const elem of setB) { - _difference.delete(elem); +exports.ZodUnion = ZodUnion; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); } - return _difference; -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/sequential_chain.js - - -function formatSet(input) { - return Array.from(input) - .map((i) => `"${i}"`) - .join(", "); -} -/** - * Chain where the outputs of one chain feed directly into next. - */ -class SequentialChain extends base/* BaseChain */.l { - static lc_name() { - return "SequentialChain"; + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); } - get inputKeys() { - return this.inputVariables; + else if (type instanceof ZodLiteral) { + return [type.value]; } - get outputKeys() { - return this.outputVariables; + else if (type instanceof ZodEnum) { + return type.options; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "chains", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputVariables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputVariables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "returnAll", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.chains = fields.chains; - this.inputVariables = fields.inputVariables; - this.outputVariables = fields.outputVariables ?? []; - if (this.outputVariables.length > 0 && fields.returnAll) { - throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."); - } - this.returnAll = fields.returnAll ?? false; - this._validateChains(); + else if (type instanceof ZodNativeEnum) { + return Object.keys(type.enum); } - /** @ignore */ - _validateChains() { - if (this.chains.length === 0) { - throw new Error("Sequential chain must have at least one chain."); - } - const memoryKeys = this.memory?.memoryKeys ?? []; - const inputKeysSet = new Set(this.inputKeys); - const memoryKeysSet = new Set(memoryKeys); - const keysIntersection = intersection(inputKeysSet, memoryKeysSet); - if (keysIntersection.size > 0) { - throw new Error(`The following keys: ${formatSet(keysIntersection)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`); - } - const availableKeys = union(inputKeysSet, memoryKeysSet); - for (const chain of this.chains) { - let missingKeys = difference(new Set(chain.inputKeys), availableKeys); - if (chain.memory) { - missingKeys = difference(missingKeys, new Set(chain.memory.memoryKeys)); - } - if (missingKeys.size > 0) { - throw new Error(`Missing variables for chain "${chain._chainType()}": ${formatSet(missingKeys)}. Only got the following variables: ${formatSet(availableKeys)}.`); - } - const outputKeysSet = new Set(chain.outputKeys); - const overlappingOutputKeys = intersection(availableKeys, outputKeysSet); - if (overlappingOutputKeys.size > 0) { - throw new Error(`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(overlappingOutputKeys)}. This can lead to unexpected behaviour.`); - } - for (const outputKey of outputKeysSet) { - availableKeys.add(outputKey); - } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else { + return null; + } +}; +class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.object) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; } - if (this.outputVariables.length === 0) { - if (this.returnAll) { - const outputKeys = difference(availableKeys, inputKeysSet); - this.outputVariables = Array.from(outputKeys); - } - else { - this.outputVariables = this.chains[this.chains.length - 1].outputKeys; - } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return parseUtil_1.INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); } else { - const missingKeys = difference(new Set(this.outputVariables), new Set(availableKeys)); - if (missingKeys.size > 0) { - throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${formatSet(missingKeys)}.`); - } + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); } } - /** @ignore */ - async _call(values, runManager) { - let input = {}; - const allChainValues = values; - let i = 0; - for (const chain of this.chains) { - i += 1; - input = await chain.call(allChainValues, runManager?.getChild(`step_${i}`)); - for (const key of Object.keys(input)) { - allChainValues[key] = input[key]; - } - } - const output = {}; - for (const key of this.outputVariables) { - output[key] = allChainValues[key]; - } - return output; + get discriminator() { + return this._def.discriminator; } - _chainType() { - return "sequential_chain"; + get options() { + return this._def.options; } - static async deserialize(data) { - const chains = []; - const inputVariables = data.input_variables; - const outputVariables = data.output_variables; - const serializedChains = data.chains; - for (const serializedChain of serializedChains) { - const deserializedChain = await base/* BaseChain.deserialize */.l.deserialize(serializedChain); - chains.push(deserializedChain); - } - return new SequentialChain({ chains, inputVariables, outputVariables }); + get optionsMap() { + return this._def.optionsMap; } - serialize() { - const chains = []; - for (const chain of this.chains) { - chains.push(chain.serialize()); + static create(discriminator, options, params) { + const optionsMap = new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } } - return { - _type: this._chainType(), - input_variables: this.inputVariables, - output_variables: this.outputVariables, - chains, - }; + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); } } -/** - * Simple chain where a single string output of one chain is fed directly into the next. - * @augments BaseChain - * @augments SimpleSequentialChainInput - * - * @example - * ```ts - * import { SimpleSequentialChain, LLMChain } from "langchain/chains"; - * import { OpenAI } from "langchain/llms/openai"; - * import { PromptTemplate } from "langchain/prompts"; - * - * // This is an LLMChain to write a synopsis given a title of a play. - * const llm = new OpenAI({ temperature: 0 }); - * const template = `You are a playwright. Given the title of play, it is your job to write a synopsis for that title. - * - * Title: {title} - * Playwright: This is a synopsis for the above play:` - * const promptTemplate = new PromptTemplate({ template, inputVariables: ["title"] }); - * const synopsisChain = new LLMChain({ llm, prompt: promptTemplate }); - * - * - * // This is an LLMChain to write a review of a play given a synopsis. - * const reviewLLM = new OpenAI({ temperature: 0 }) - * const reviewTemplate = `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. - * - * Play Synopsis: - * {synopsis} - * Review from a New York Times play critic of the above play:` - * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] }); - * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate }); - * - * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true}) - * const review = await overallChain.run("Tragedy at sunset on the beach") - * // the variable review contains resulting play review. - * ``` - */ -class SimpleSequentialChain extends base/* BaseChain */.l { - static lc_name() { - return "SimpleSequentialChain"; - } - get inputKeys() { - return [this.inputKey]; - } - get outputKeys() { - return [this.outputKey]; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "chains", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "input" - }); - Object.defineProperty(this, "outputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "output" - }); - Object.defineProperty(this, "trimOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.chains = fields.chains; - this.trimOutputs = fields.trimOutputs ?? false; - this._validateChains(); +exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; +function mergeValues(a, b) { + const aType = (0, util_1.getParsedType)(a); + const bType = (0, util_1.getParsedType)(b); + if (a === b) { + return { valid: true, data: a }; } - /** @ignore */ - _validateChains() { - for (const chain of this.chains) { - if (chain.inputKeys.filter((k) => !chain.memory?.memoryKeys.includes(k) ?? true).length !== 1) { - throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${chain.inputKeys.length} for ${chain._chainType()}.`); - } - if (chain.outputKeys.length !== 1) { - throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${chain.outputKeys.length} for ${chain._chainType()}.`); + else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { + const bKeys = util_1.util.objectKeys(b); + const sharedKeys = util_1.util + .objectKeys(a) + .filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; } + newObj[key] = sharedValue.data; } + return { valid: true, data: newObj }; } - /** @ignore */ - async _call(values, runManager) { - let input = values[this.inputKey]; - let i = 0; - for (const chain of this.chains) { - i += 1; - input = (await chain.call({ [chain.inputKeys[0]]: input, signal: values.signal }, runManager?.getChild(`step_${i}`)))[chain.outputKeys[0]]; - if (this.trimOutputs) { - input = input.trim(); + else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; } - await runManager?.handleText(input); + newArray.push(sharedValue.data); } - return { [this.outputKey]: input }; + return { valid: true, data: newArray }; } - _chainType() { - return "simple_sequential_chain"; + else if (aType === util_1.ZodParsedType.date && + bType === util_1.ZodParsedType.date && + +a === +b) { + return { valid: true, data: a }; } - static async deserialize(data) { - const chains = []; - const serializedChains = data.chains; - for (const serializedChain of serializedChains) { - const deserializedChain = await base/* BaseChain.deserialize */.l.deserialize(serializedChain); - chains.push(deserializedChain); - } - return new SimpleSequentialChain({ chains }); + else { + return { valid: false }; } - serialize() { - const chains = []; - for (const chain of this.chains) { - chains.push(chain.serialize()); - } - return { - _type: this._chainType(), - chains, +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { + return parseUtil_1.INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_intersection_types, + }); + return parseUtil_1.INVALID; + } + if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } } } - - -/***/ }), - -/***/ 9518: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -__nccwpck_require__.r(__webpack_exports__); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "VectorDBQAChain": () => (/* binding */ VectorDBQAChain) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(3197); -/* harmony import */ var _question_answering_load_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(3504); - - -/** - * Class that represents a VectorDBQAChain. It extends the `BaseChain` - * class and implements the `VectorDBQAChainInput` interface. It performs - * a similarity search using a vector store and combines the search - * results using a specified combine documents chain. - */ -class VectorDBQAChain extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain */ .l { - static lc_name() { - return "VectorDBQAChain"; - } - get inputKeys() { - return [this.inputKey]; - } - get outputKeys() { - return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "k", { - enumerable: true, - configurable: true, - writable: true, - value: 4 - }); - Object.defineProperty(this, "inputKey", { - enumerable: true, - configurable: true, - writable: true, - value: "query" - }); - Object.defineProperty(this, "vectorstore", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "combineDocumentsChain", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "returnSourceDocuments", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - this.vectorstore = fields.vectorstore; - this.combineDocumentsChain = fields.combineDocumentsChain; - this.inputKey = fields.inputKey ?? this.inputKey; - this.k = fields.k ?? this.k; - this.returnSourceDocuments = - fields.returnSourceDocuments ?? this.returnSourceDocuments; - } - /** @ignore */ - async _call(values, runManager) { - if (!(this.inputKey in values)) { - throw new Error(`Question key ${this.inputKey} not found.`); +exports.ZodIntersection = ZodIntersection; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.array) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; } - const question = values[this.inputKey]; - const docs = await this.vectorstore.similaritySearch(question, this.k, values.filter, runManager?.getChild("vectorstore")); - const inputs = { question, input_documents: docs }; - const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); - if (this.returnSourceDocuments) { - return { - ...result, - sourceDocuments: docs, - }; + if (ctx.data.length < this._def.items.length) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return parseUtil_1.INVALID; } - return result; - } - _chainType() { - return "vector_db_qa"; - } - static async deserialize(data, values) { - if (!("vectorstore" in values)) { - throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); } - const { vectorstore } = values; - if (!data.combine_documents_chain) { - throw new Error(`VectorDBQAChain must have combine_documents_chain in serialized data`); + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return parseUtil_1.ParseStatus.mergeArray(status, results); + }); + } + else { + return parseUtil_1.ParseStatus.mergeArray(status, items); } - return new VectorDBQAChain({ - combineDocumentsChain: await _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseChain.deserialize */ .l.deserialize(data.combine_documents_chain), - k: data.k, - vectorstore, - }); } - serialize() { - return { - _type: this._chainType(), - combine_documents_chain: this.combineDocumentsChain.serialize(), - k: this.k, - }; + get items() { + return this._def.items; } - /** - * Static method that creates a VectorDBQAChain instance from a - * BaseLanguageModel and a vector store. It also accepts optional options - * to customize the chain. - * @param llm The BaseLanguageModel instance. - * @param vectorstore The vector store used for similarity search. - * @param options Optional options to customize the chain. - * @returns A new instance of VectorDBQAChain. - */ - static fromLLM(llm, vectorstore, options) { - const qaChain = (0,_question_answering_load_js__WEBPACK_IMPORTED_MODULE_1__/* .loadQAStuffChain */ .cf)(llm); - return new this({ - vectorstore, - combineDocumentsChain: qaChain, - ...options, + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, }); } } - - -/***/ }), - -/***/ 27: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "ChatOpenAI": () => (/* binding */ ChatOpenAI), - "PromptLayerChatOpenAI": () => (/* binding */ PromptLayerChatOpenAI) -}); - -// EXTERNAL MODULE: ./node_modules/openai/index.mjs + 55 modules -var openai = __nccwpck_require__(1053); -// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/count_tokens.js -var count_tokens = __nccwpck_require__(8393); -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js -var schema = __nccwpck_require__(8102); -// EXTERNAL MODULE: ./node_modules/zod-to-json-schema/index.js -var zod_to_json_schema = __nccwpck_require__(8707); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/tools/convert_to_openai.js - -/** - * Formats a `StructuredTool` instance into a format that is compatible - * with OpenAI's ChatCompletionFunctions. It uses the `zodToJsonSchema` - * function to convert the schema of the `StructuredTool` into a JSON - * schema, which is then used as the parameters for the OpenAI function. - */ -function formatToOpenAIFunction(tool) { - return { - name: tool.name, - description: tool.description, - parameters: (0,zod_to_json_schema/* zodToJsonSchema */.Y_)(tool.schema), - }; -} - -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/azure.js -var azure = __nccwpck_require__(113); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/env.js -var env = __nccwpck_require__(5785); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/prompt-layer.js -var prompt_layer = __nccwpck_require__(2306); -// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules -var base_language = __nccwpck_require__(7679); -// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/manager.js + 13 modules -var manager = __nccwpck_require__(6009); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chat_models/base.js - - - -/** - * Creates a transform stream for encoding chat message chunks. - * @deprecated Use {@link BytesOutputParser} instead - * @returns A TransformStream instance that encodes chat message chunks. - */ -function createChatMessageChunkEncoderStream() { - const textEncoder = new TextEncoder(); - return new TransformStream({ - transform(chunk, controller) { - controller.enqueue(textEncoder.encode(chunk.content)); - }, - }); -} -/** - * Base class for chat models. It extends the BaseLanguageModel class and - * provides methods for generating chat based on input messages. - */ -class BaseChatModel extends base_language/* BaseLanguageModel */.qV { - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "chat_models", this._llmType()] - }); +exports.ZodTuple = ZodTuple; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; } - _separateRunnableConfigFromCallOptions(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - if (callOptions?.timeout && !callOptions.signal) { - callOptions.signal = AbortSignal.timeout(callOptions.timeout); + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.object) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + }); + } + if (ctx.common.async) { + return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); } - return [runnableConfig, callOptions]; } - /** - * Invokes the chat model with a single input. - * @param input The input for the language model. - * @param options The call options. - * @returns A Promise that resolves to a BaseMessageChunk. - */ - async invoke(input, options) { - const promptValue = BaseChatModel._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - const chatGeneration = result.generations[0][0]; - // TODO: Remove cast after figuring out inheritance - return chatGeneration.message; + get element() { + return this._def.valueType; } - // eslint-disable-next-line require-yield - async *_streamResponseChunks(_messages, _options, _runManager) { - throw new Error("Not implemented."); + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); } - async *_streamIterator(input, options) { - // Subclass check required to avoid double callbacks with default implementation - if (this._streamResponseChunks === - BaseChatModel.prototype._streamResponseChunks) { - yield this.invoke(input, options); +} +exports.ZodRecord = ZodRecord; +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.map) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.map, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; } - else { - const prompt = BaseChatModel._convertInputToPromptValue(input); - const messages = prompt.toChatMessages(); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); - const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [messages], undefined, undefined, extra); - let generationChunk; - try { - for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { - yield chunk.message; - if (!generationChunk) { - generationChunk = chunk; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_1.INVALID; } - else { - generationChunk = generationChunk.concat(chunk); + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); } + finalMap.set(key.value, value.value); } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); } - catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - // TODO: Remove cast after figuring out inheritance - generations: [[generationChunk]], - }))); + return { status: status.value, value: finalMap }; } } - /** @ignore */ - async _generateUncached(messages, parsedOptions, handledOptions) { - const baseMessages = messages.map((messageList) => messageList.map(schema/* coerceMessageLikeToMessage */.E1)); - // create callback manager and start run - const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, undefined, undefined, extra); - // generate results - const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); - // handle results - const generations = []; - const llmOutputs = []; - await Promise.all(results.map(async (pResult, i) => { - if (pResult.status === "fulfilled") { - const result = pResult.value; - generations[i] = result.generations; - llmOutputs[i] = result.llmOutput; - return runManagers?.[i]?.handleLLMEnd({ - generations: [result.generations], - llmOutput: result.llmOutput, +} +exports.ZodMap = ZodMap; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.set) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.set, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, }); + status.dirty(); } - else { - // status === "rejected" - await runManagers?.[i]?.handleLLMError(pResult.reason); - return Promise.reject(pResult.reason); + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); } - })); - // create combined output - const output = { - generations, - llmOutput: llmOutputs.length - ? this._combineLLMOutput?.(...llmOutputs) - : undefined, - }; - Object.defineProperty(output, schema/* RUN_KEY */.WH, { - value: runManagers - ? { runIds: runManagers?.map((manager) => manager.runId) } - : undefined, - configurable: true, - }); - return output; - } - /** - * Generates chat based on the input messages. - * @param messages An array of arrays of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generate(messages, options, callbacks) { - // parse call options - let parsedOptions; - if (Array.isArray(options)) { - parsedOptions = { stop: options }; } - else { - parsedOptions = options; + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return parseUtil_1.INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; } - const baseMessages = messages.map((messageList) => messageList.map(schema/* coerceMessageLikeToMessage */.E1)); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) { - return this._generateUncached(baseMessages, callOptions, runnableConfig); + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); } - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const missingPromptIndices = []; - const generations = await Promise.all(baseMessages.map(async (baseMessage, index) => { - // Join all content into one string for the prompt index - const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); - const result = await cache.lookup(prompt, llmStringKey); - if (!result) { - missingPromptIndices.push(index); - } - return result; - })); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - // Join all content into one string for the prompt index - const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); - return cache.update(prompt, llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; + else { + return finalizeSet(elements); } - return { generations, llmOutput }; - } - /** - * Get the parameters used to invoke the model - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - invocationParams(_options) { - return {}; - } - _modelType() { - return "base_chat_model"; - } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this.invocationParams(), - _type: this._llmType(), - _model: this._modelType(), - }; - } - /** - * Generates a prompt based on the input prompt values. - * @param promptValues An array of BasePromptValue instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generatePrompt(promptValues, options, callbacks) { - const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); - return this.generate(promptMessages, options, callbacks); - } - /** - * Makes a single call to the chat model. - * @param messages An array of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. - */ - async call(messages, options, callbacks) { - const result = await this.generate([messages.map(schema/* coerceMessageLikeToMessage */.E1)], options, callbacks); - const generations = result.generations; - return generations[0][0].message; } - /** - * Makes a single call to the chat model with a prompt value. - * @param promptValue The value of the prompt. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. - */ - async callPrompt(promptValue, options, callbacks) { - const promptMessages = promptValue.toChatMessages(); - return this.call(promptMessages, options, callbacks); + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, + }); } - /** - * Predicts the next message based on the input messages. - * @param messages An array of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. - */ - async predictMessages(messages, options, callbacks) { - return this.call(messages, options, callbacks); + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, + }); } - /** - * Predicts the next message based on a text input. - * @param text The text input. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a string. - */ - async predict(text, options, callbacks) { - const message = new schema/* HumanMessage */.xk(text); - const result = await this.call([message], options, callbacks); - return result.content; + size(size, message) { + return this.min(size, message).max(size, message); } -} -/** - * An abstract class that extends BaseChatModel and provides a simple - * implementation of _generate. - */ -class SimpleChatModel extends (/* unused pure expression or super */ null && (BaseChatModel)) { - async _generate(messages, options, runManager) { - const text = await this._call(messages, options, runManager); - const message = new AIMessage(text); - return { - generations: [ - { - text: message.content, - message, - }, - ], - }; + nonempty(message) { + return this.min(1, message); } } - -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/openai.js -var util_openai = __nccwpck_require__(8311); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chat_models/openai.js - - - - - - - - - -function extractGenericMessageCustomRole(message) { - if (message.role !== "system" && - message.role !== "assistant" && - message.role !== "user" && - message.role !== "function") { - console.warn(`Unknown message role: ${message.role}`); +exports.ZodSet = ZodSet; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; } - return message.role; -} -function messageToOpenAIRole(message) { - const type = message._getType(); - switch (type) { - case "system": - return "system"; - case "ai": - return "assistant"; - case "human": - return "user"; - case "function": - return "function"; - case "generic": { - if (!schema/* ChatMessage.isInstance */.J.isInstance(message)) - throw new Error("Invalid generic chat message"); - return extractGenericMessageCustomRole(message); + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.function) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.function, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; + } + function makeArgsIssue(args, error) { + return (0, parseUtil_1.makeIssue)({ + data: args, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + (0, errors_1.getErrorMap)(), + errors_1.defaultErrorMap, + ].filter((x) => !!x), + issueData: { + code: ZodError_1.ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return (0, parseUtil_1.makeIssue)({ + data: returns, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + (0, errors_1.getErrorMap)(), + errors_1.defaultErrorMap, + ].filter((x) => !!x), + issueData: { + code: ZodError_1.ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return (0, parseUtil_1.OK)(async function (...args) { + const error = new ZodError_1.ZodError([]); + const parsedArgs = await me._def.args + .parseAsync(args, params) + .catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + const me = this; + return (0, parseUtil_1.OK)(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); } - default: - throw new Error(`Unknown message type: ${type}`); } -} -function openAIResponseToChatMessage(message) { - switch (message.role) { - case "user": - return new schema/* HumanMessage */.xk(message.content || ""); - case "assistant": - return new schema/* AIMessage */.gY(message.content || "", { - function_call: message.function_call, - }); - case "system": - return new schema/* SystemMessage */.jN(message.content || ""); - default: - return new schema/* ChatMessage */.J(message.content || "", message.role ?? "unknown"); + parameters() { + return this._def.args; } -} -function _convertDeltaToMessageChunk( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -delta, defaultRole) { - const role = delta.role ?? defaultRole; - const content = delta.content ?? ""; - let additional_kwargs; - if (delta.function_call) { - additional_kwargs = { - function_call: delta.function_call, - }; + returnType() { + return this._def.returns; } - else { - additional_kwargs = {}; + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); } - if (role === "user") { - return new schema/* HumanMessageChunk */.ro({ content }); + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); } - else if (role === "assistant") { - return new schema/* AIMessageChunk */.GC({ content, additional_kwargs }); + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - else if (role === "system") { - return new schema/* SystemMessageChunk */.xq({ content }); + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; } - else if (role === "function") { - return new schema/* FunctionMessageChunk */.Cr({ - content, - additional_kwargs, - name: delta.name, + static create(args, returns, params) { + return new ZodFunction({ + args: (args + ? args + : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), }); } - else { - return new schema/* ChatMessageChunk */.HD({ content, role }); - } } -/** - * Wrapper around OpenAI large language models that use the Chat endpoint. - * - * To use you should have the `openai` package installed, with the - * `OPENAI_API_KEY` environment variable set. - * - * To use with Azure you should have the `openai` package installed, with the - * `AZURE_OPENAI_API_KEY`, - * `AZURE_OPENAI_API_INSTANCE_NAME`, - * `AZURE_OPENAI_API_DEPLOYMENT_NAME` - * and `AZURE_OPENAI_API_VERSION` environment variable set. - * `AZURE_OPENAI_BASE_PATH` is optional and will override `AZURE_OPENAI_API_INSTANCE_NAME` if you need to use a custom endpoint. - * - * @remarks - * Any parameters that are valid to be passed to {@link - * https://platform.openai.com/docs/api-reference/chat/create | - * `openai.createChatCompletion`} can be passed through {@link modelKwargs}, even - * if not explicitly available on this class. - */ -class ChatOpenAI extends BaseChatModel { - static lc_name() { - return "ChatOpenAI"; - } - get callKeys() { - return [ - ...super.callKeys, - "options", - "function_call", - "functions", - "tools", - "promptIndex", - ]; - } - get lc_secrets() { - return { - openAIApiKey: "OPENAI_API_KEY", - azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION", - }; +exports.ZodFunction = ZodFunction; +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); } - get lc_aliases() { - return { - modelName: "model", - openAIApiKey: "openai_api_key", - azureOpenAIApiVersion: "azure_openai_api_version", - azureOpenAIApiKey: "azure_openai_api_key", - azureOpenAIApiInstanceName: "azure_openai_api_instance_name", - azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", - }; + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } - constructor(fields, - /** @deprecated */ - configuration) { - super(fields ?? {}); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "temperature", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "topP", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "frequencyPenalty", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "presencePenalty", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "n", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "logitBias", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "modelName", { - enumerable: true, - configurable: true, - writable: true, - value: "gpt-3.5-turbo" - }); - Object.defineProperty(this, "modelKwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "stop", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "user", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "streaming", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "maxTokens", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "openAIApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiVersion", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiInstanceName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiDeploymentName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIBasePath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "organization", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "clientConfig", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.openAIApiKey = - fields?.openAIApiKey ?? (0,env/* getEnvironmentVariable */.lS)("OPENAI_API_KEY"); - this.azureOpenAIApiKey = - fields?.azureOpenAIApiKey ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_KEY"); - if (!this.azureOpenAIApiKey && !this.openAIApiKey) { - throw new Error("OpenAI or Azure OpenAI API key not found"); - } - this.azureOpenAIApiInstanceName = - fields?.azureOpenAIApiInstanceName ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = - fields?.azureOpenAIApiDeploymentName ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_DEPLOYMENT_NAME"); - this.azureOpenAIApiVersion = - fields?.azureOpenAIApiVersion ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = - fields?.azureOpenAIBasePath ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_BASE_PATH"); - this.organization = - fields?.configuration?.organization ?? - (0,env/* getEnvironmentVariable */.lS)("OPENAI_ORGANIZATION"); - this.modelName = fields?.modelName ?? this.modelName; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.maxTokens = fields?.maxTokens; - this.n = fields?.n ?? this.n; - this.logitBias = fields?.logitBias; - this.stop = fields?.stop; - this.user = fields?.user; - this.streaming = fields?.streaming ?? false; - if (this.azureOpenAIApiKey) { - if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { - throw new Error("Azure OpenAI API instance name not found"); - } - if (!this.azureOpenAIApiDeploymentName) { - throw new Error("Azure OpenAI API deployment name not found"); - } - if (!this.azureOpenAIApiVersion) { - throw new Error("Azure OpenAI API version not found"); - } - this.openAIApiKey = this.openAIApiKey ?? ""; +} +exports.ZodLazy = ZodLazy; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_1.ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return parseUtil_1.INVALID; } - this.clientConfig = { - apiKey: this.openAIApiKey, - organization: this.organization, - baseURL: configuration?.basePath ?? fields?.configuration?.basePath, - dangerouslyAllowBrowser: true, - defaultHeaders: configuration?.baseOptions?.headers ?? - fields?.configuration?.baseOptions?.headers, - defaultQuery: configuration?.baseOptions?.params ?? - fields?.configuration?.baseOptions?.params, - ...configuration, - ...fields?.configuration, - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - return { - model: this.modelName, - temperature: this.temperature, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens, - n: this.n, - logit_bias: this.logitBias, - stop: options?.stop ?? this.stop, - user: this.user, - stream: this.streaming, - functions: options?.functions ?? - (options?.tools - ? options?.tools.map(formatToOpenAIFunction) - : undefined), - function_call: options?.function_call, - ...this.modelKwargs, - }; + return { status: "valid", value: input.data }; } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.modelName, - ...this.invocationParams(), - ...this.clientConfig, - }; + get value() { + return this._def.value; } - async *_streamResponseChunks(messages, options, runManager) { - const messagesMapped = messages.map((message) => ({ - role: messageToOpenAIRole(message), - content: message.content, - name: message.name, - function_call: message.additional_kwargs - .function_call, - })); - const params = { - ...this.invocationParams(options), - messages: messagesMapped, - stream: true, - }; - let defaultRole; - const streamIterable = await this.completionWithRetry(params, options); - for await (const data of streamIterable) { - const choice = data?.choices[0]; - if (!choice) { - continue; - } - const { delta } = choice; - const chunk = _convertDeltaToMessageChunk(delta, defaultRole); - defaultRole = delta.role ?? defaultRole; - const newTokenIndices = { - prompt: options.promptIndex ?? 0, - completion: choice.index ?? 0, - }; - const generationChunk = new schema/* ChatGenerationChunk */.Ls({ - message: chunk, - text: chunk.content, - generationInfo: newTokenIndices, +} +exports.ZodLiteral = ZodLiteral; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_1.addIssueToContext)(ctx, { + expected: util_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_1.ZodIssueCode.invalid_type, }); - yield generationChunk; - // eslint-disable-next-line no-void - void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, undefined, undefined, undefined, { chunk: generationChunk }); + return parseUtil_1.INVALID; } - if (options.signal?.aborted) { - throw new Error("AbortError"); + if (this._def.values.indexOf(input.data) === -1) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_1.INVALID; } + return (0, parseUtil_1.OK)(input.data); } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return this._identifyingParams(); - } - /** @ignore */ - async _generate(messages, options, runManager) { - const tokenUsage = {}; - const params = this.invocationParams(options); - const messagesMapped = messages.map((message) => ({ - role: messageToOpenAIRole(message), - content: message.content, - name: message.name, - function_call: message.additional_kwargs - .function_call, - })); - if (params.stream) { - const stream = await this._streamResponseChunks(messages, options, runManager); - const finalChunks = {}; - for await (const chunk of stream) { - const index = chunk.generationInfo?.completion ?? 0; - if (finalChunks[index] === undefined) { - finalChunks[index] = chunk; - } - else { - finalChunks[index] = finalChunks[index].concat(chunk); - } - } - const generations = Object.entries(finalChunks) - .sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)) - .map(([_, value]) => value); - return { generations }; - } - else { - const data = await this.completionWithRetry({ - ...params, - stream: false, - messages: messagesMapped, - }, { - signal: options?.signal, - ...options?.options, - }); - const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data?.usage ?? {}; - if (completionTokens) { - tokenUsage.completionTokens = - (tokenUsage.completionTokens ?? 0) + completionTokens; - } - if (promptTokens) { - tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; - } - if (totalTokens) { - tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; - } - const generations = []; - for (const part of data?.choices ?? []) { - const text = part.message?.content ?? ""; - const generation = { - text, - message: openAIResponseToChatMessage(part.message ?? { role: "assistant" }), - }; - if (part.finish_reason) { - generation.generationInfo = { finish_reason: part.finish_reason }; - } - generations.push(generation); - } - return { - generations, - llmOutput: { tokenUsage }, - }; + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } + return enumValues; } - async getNumTokensFromMessages(messages) { - let totalCount = 0; - let tokensPerMessage = 0; - let tokensPerName = 0; - // From: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb - if ((0,count_tokens/* getModelNameForTiktoken */._i)(this.modelName) === "gpt-3.5-turbo") { - tokensPerMessage = 4; - tokensPerName = -1; + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - else if ((0,count_tokens/* getModelNameForTiktoken */._i)(this.modelName).startsWith("gpt-4")) { - tokensPerMessage = 3; - tokensPerName = 1; + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - const countPerMessage = await Promise.all(messages.map(async (message) => { - const textCount = await this.getNumTokens(message.content); - const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); - const nameCount = message.name !== undefined - ? tokensPerName + (await this.getNumTokens(message.name)) - : 0; - const count = textCount + tokensPerMessage + roleCount + nameCount; - totalCount += count; - return count; - })); - totalCount += 3; // every reply is primed with <|start|>assistant<|message|> - return { totalCount, countPerMessage }; + return enumValues; } - async completionWithRetry(request, options) { - const requestOptions = this._getClientOptions(options); - return this.caller.call(async () => { - try { - const res = await this.client.chat.completions.create(request, requestOptions); - return res; - } - catch (e) { - const error = (0,util_openai/* wrapOpenAIClientError */.K)(e); - throw error; - } - }); + extract(values) { + return ZodEnum.create(values); } - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - baseURL: this.clientConfig.baseURL, - }; - const endpoint = (0,azure/* getEndpoint */.O)(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0, - }; - if (!params.baseURL) { - delete params.baseURL; - } - this.client = new openai/* OpenAI */.Pp(params); + exclude(values) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); + } +} +exports.ZodEnum = ZodEnum; +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== util_1.ZodParsedType.string && + ctx.parsedType !== util_1.ZodParsedType.number) { + const expectedValues = util_1.util.objectValues(nativeEnumValues); + (0, parseUtil_1.addIssueToContext)(ctx, { + expected: util_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_1.ZodIssueCode.invalid_type, + }); + return parseUtil_1.INVALID; } - const requestOptions = { - ...this.clientConfig, - ...options, - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers, - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query, - }; + if (nativeEnumValues.indexOf(input.data) === -1) { + const expectedValues = util_1.util.objectValues(nativeEnumValues); + (0, parseUtil_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_1.INVALID; } - return requestOptions; - } - _llmType() { - return "openai"; + return (0, parseUtil_1.OK)(input.data); } - /** @ignore */ - _combineLLMOutput(...llmOutputs) { - return llmOutputs.reduce((acc, llmOutput) => { - if (llmOutput && llmOutput.tokenUsage) { - acc.tokenUsage.completionTokens += - llmOutput.tokenUsage.completionTokens ?? 0; - acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; - acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; - } - return acc; - }, { - tokenUsage: { - completionTokens: 0, - promptTokens: 0, - totalTokens: 0, - }, - }); + get enum() { + return this._def.values; } } -class PromptLayerChatOpenAI extends ChatOpenAI { - constructor(fields) { - super(fields); - Object.defineProperty(this, "promptLayerApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "plTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "returnPromptLayerId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.promptLayerApiKey = - fields?.promptLayerApiKey ?? - (typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.PROMPTLAYER_API_KEY - : undefined); - this.plTags = fields?.plTags ?? []; - this.returnPromptLayerId = fields?.returnPromptLayerId ?? false; +exports.ZodNativeEnum = ZodNativeEnum; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; } - async _generate(messages, options, runManager) { - const requestStartTime = Date.now(); - let parsedOptions; - if (Array.isArray(options)) { - parsedOptions = { stop: options }; - } - else if (options?.timeout && !options.signal) { - parsedOptions = { - ...options, - signal: AbortSignal.timeout(options.timeout), - }; - } - else { - parsedOptions = options ?? {}; + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_1.ZodParsedType.promise && + ctx.common.async === false) { + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.promise, + received: ctx.parsedType, + }); + return parseUtil_1.INVALID; } - const generatedResponses = await super._generate(messages, parsedOptions, runManager); - const requestEndTime = Date.now(); - const _convertMessageToDict = (message) => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let messageDict; - if (message._getType() === "human") { - messageDict = { role: "user", content: message.content }; - } - else if (message._getType() === "ai") { - messageDict = { role: "assistant", content: message.content }; + const promisified = ctx.parsedType === util_1.ZodParsedType.promise + ? ctx.data + : Promise.resolve(ctx.data); + return (0, parseUtil_1.OK)(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +exports.ZodPromise = ZodPromise; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + (0, parseUtil_1.addIssueToContext)(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.issues.length) { + return { + status: "dirty", + value: ctx.data, + }; } - else if (message._getType() === "function") { - messageDict = { role: "assistant", content: message.content }; + if (ctx.common.async) { + return Promise.resolve(processed).then((processed) => { + return this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + }); } - else if (message._getType() === "system") { - messageDict = { role: "system", content: message.content }; + else { + return this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); } - else if (message._getType() === "generic") { - messageDict = { - role: message.role, - content: message.content, - }; + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return parseUtil_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; } else { - throw new Error(`Got unknown type ${message}`); + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((inner) => { + if (inner.status === "aborted") + return parseUtil_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); } - return messageDict; - }; - const _createMessageDicts = (messages, callOptions) => { - const params = { - ...this.invocationParams(), - model: this.modelName, - }; - if (callOptions?.stop) { - if (Object.keys(params).includes("stop")) { - throw new Error("`stop` found in both the input and default params."); + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!(0, parseUtil_1.isValid)(base)) + return base; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } + return { status: status.value, value: result }; } - const messageDicts = messages.map((message) => _convertMessageToDict(message)); - return messageDicts; - }; - for (let i = 0; i < generatedResponses.generations.length; i += 1) { - const generation = generatedResponses.generations[i]; - const messageDicts = _createMessageDicts(messages, parsedOptions); - let promptLayerRequestId; - const parsedResp = [ - { - content: generation.text, - role: messageToOpenAIRole(generation.message), - }, - ]; - const promptLayerRespBody = await (0,prompt_layer/* promptLayerTrackRequest */.r)(this.caller, "langchain.PromptLayerChatOpenAI", { ...this._identifyingParams(), messages: messageDicts, stream: false }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); - if (this.returnPromptLayerId === true) { - if (promptLayerRespBody.success === true) { - promptLayerRequestId = promptLayerRespBody.request_id; - } - if (!generation.generationInfo || - typeof generation.generationInfo !== "object") { - generation.generationInfo = {}; - } - generation.generationInfo.promptLayerRequestId = promptLayerRequestId; + else { + return this._def.schema + ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) + .then((base) => { + if (!(0, parseUtil_1.isValid)(base)) + return base; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); + }); } } - return generatedResponses; + util_1.util.assertNever(effect); } } - - -/***/ }), - -/***/ 4624: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -// ESM COMPAT FLAG -__nccwpck_require__.r(__webpack_exports__); - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "OpenAI": () => (/* binding */ OpenAI), - "OpenAIChat": () => (/* reexport */ OpenAIChat), - "PromptLayerOpenAI": () => (/* binding */ PromptLayerOpenAI), - "PromptLayerOpenAIChat": () => (/* reexport */ PromptLayerOpenAIChat) -}); - -// EXTERNAL MODULE: ./node_modules/openai/index.mjs + 55 modules -var openai = __nccwpck_require__(1053); -// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/count_tokens.js -var count_tokens = __nccwpck_require__(8393); -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js -var schema = __nccwpck_require__(8102); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/azure.js -var azure = __nccwpck_require__(113); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/chunk.js -const chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => { - const chunkIndex = Math.floor(index / chunkSize); - const chunk = chunks[chunkIndex] || []; - // eslint-disable-next-line no-param-reassign - chunks[chunkIndex] = chunk.concat([elem]); - return chunks; -}, []); - -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/env.js -var env = __nccwpck_require__(5785); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/prompt-layer.js -var prompt_layer = __nccwpck_require__(2306); -// EXTERNAL MODULE: ./node_modules/langchain/dist/base_language/index.js + 2 modules -var base_language = __nccwpck_require__(7679); -// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/manager.js + 13 modules -var manager = __nccwpck_require__(6009); -// EXTERNAL MODULE: ./node_modules/langchain/dist/memory/base.js -var base = __nccwpck_require__(790); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/llms/base.js - - - - -/** - * LLM Wrapper. Provides an {@link call} (an {@link generate}) function that takes in a prompt (or prompts) and returns a string. - */ -class BaseLLM extends base_language/* BaseLanguageModel */.qV { - constructor({ concurrency, ...rest }) { - super(concurrency ? { maxConcurrency: concurrency, ...rest } : rest); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "llms", this._llmType()] - }); +exports.ZodEffects = ZodEffects; +exports.ZodTransformer = ZodEffects; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_1.ZodParsedType.undefined) { + return (0, parseUtil_1.OK)(undefined); + } + return this._def.innerType._parse(input); } - /** - * This method takes an input and options, and returns a string. It - * converts the input to a prompt value and generates a result based on - * the prompt. - * @param input Input for the LLM. - * @param options Options for the LLM call. - * @returns A string result based on the prompt. - */ - async invoke(input, options) { - const promptValue = BaseLLM._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - return result.generations[0][0].text; + unwrap() { + return this._def.innerType; } - // eslint-disable-next-line require-yield - async *_streamResponseChunks(_input, _options, _runManager) { - throw new Error("Not implemented."); +} +exports.ZodOptional = ZodOptional; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_1.ZodParsedType.null) { + return (0, parseUtil_1.OK)(null); + } + return this._def.innerType._parse(input); } - _separateRunnableConfigFromCallOptions(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - if (callOptions?.timeout && !callOptions.signal) { - callOptions.signal = AbortSignal.timeout(callOptions.timeout); + unwrap() { + return this._def.innerType; + } +} +exports.ZodNullable = ZodNullable; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === util_1.ZodParsedType.undefined) { + data = this._def.defaultValue(); } - return [runnableConfig, callOptions]; + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); } - async *_streamIterator(input, options) { - // Subclass check required to avoid double callbacks with default implementation - if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) { - yield this.invoke(input, options); + removeDefault() { + return this._def.innerType; + } +} +exports.ZodDefault = ZodDefault; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" + ? params.default + : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if ((0, parseUtil_1.isAsync)(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); } else { - const prompt = BaseLLM._convertInputToPromptValue(input); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); - const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], undefined, undefined, extra); - let generation = new schema/* GenerationChunk */.b6({ - text: "", + } + } + removeCatch() { + return this._def.innerType; + } +} +exports.ZodCatch = ZodCatch; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_1.ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_1.addIssueToContext)(ctx, { + code: ZodError_1.ZodIssueCode.invalid_type, + expected: util_1.ZodParsedType.nan, + received: ctx.parsedType, }); - try { - for await (const chunk of this._streamResponseChunks(input.toString(), callOptions, runManagers?.[0])) { - if (!generation) { - generation = chunk; - } - else { - generation = generation.concat(chunk); - } - if (typeof chunk.text === "string") { - yield chunk.text; - } - } - } - catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - generations: [[generation]], - }))); + return parseUtil_1.INVALID; } + return { status: "valid", value: input.data }; } - /** - * This method takes prompt values, options, and callbacks, and generates - * a result based on the prompts. - * @param promptValues Prompt values for the LLM. - * @param options Options for the LLM call. - * @param callbacks Callbacks for the LLM call. - * @returns An LLMResult based on the prompts. - */ - async generatePrompt(promptValues, options, callbacks) { - const prompts = promptValues.map((promptValue) => promptValue.toString()); - return this.generate(prompts, options, callbacks); +} +exports.ZodNaN = ZodNaN; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +exports.BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); } - /** - * Get the parameters used to invoke the model - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - invocationParams(_options) { - return {}; + unwrap() { + return this._def.type; } - _flattenLLMResult(llmResult) { - const llmResults = []; - for (let i = 0; i < llmResult.generations.length; i += 1) { - const genList = llmResult.generations[i]; - if (i === 0) { - llmResults.push({ - generations: [genList], - llmOutput: llmResult.llmOutput, +} +exports.ZodBranded = ZodBranded; +class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, }); + if (inResult.status === "aborted") + return parseUtil_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return (0, parseUtil_1.DIRTY)(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; } else { - const llmOutput = llmResult.llmOutput - ? { ...llmResult.llmOutput, tokenUsage: {} } - : undefined; - llmResults.push({ - generations: [genList], - llmOutput, + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, }); } } - return llmResults; } - /** @ignore */ - async _generateUncached(prompts, parsedOptions, handledOptions) { - const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, undefined, undefined, extra); - let output; - try { - output = await this._generate(prompts, parsedOptions, runManagers?.[0]); - } - catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - const flattenedOutputs = this._flattenLLMResult(output); - await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); - const runIds = runManagers?.map((manager) => manager.runId) || undefined; - // This defines RUN_KEY as a non-enumerable property on the output object - // so that it is not serialized when the output is stringified, and so that - // it isnt included when listing the keys of the output object. - Object.defineProperty(output, schema/* RUN_KEY */.WH, { - value: runIds ? { runIds } : undefined, - configurable: true, + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, }); - return output; - } - /** - * Run the LLM on the given prompts and input, handling caching. - */ - async generate(prompts, options, callbacks) { - if (!Array.isArray(prompts)) { - throw new Error("Argument 'prompts' is expected to be a string[]"); - } - let parsedOptions; - if (Array.isArray(options)) { - parsedOptions = { stop: options }; - } - else { - parsedOptions = options; - } - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) { - return this._generateUncached(prompts, callOptions, runnableConfig); - } - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const missingPromptIndices = []; - const generations = await Promise.all(prompts.map(async (prompt, index) => { - const result = await cache.lookup(prompt, llmStringKey); - if (!result) { - missingPromptIndices.push(index); - } - return result; - })); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - return cache.update(prompts[promptIndex], llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { generations, llmOutput }; - } - /** - * Convenience wrapper for {@link generate} that takes in a single string prompt and returns a single string output. - */ - async call(prompt, options, callbacks) { - const { generations } = await this.generate([prompt], options, callbacks); - return generations[0][0].text; - } - /** - * This method is similar to `call`, but it's used for making predictions - * based on the input text. - * @param text Input text for the prediction. - * @param options Options for the LLM call. - * @param callbacks Callbacks for the LLM call. - * @returns A prediction based on the input text. - */ - async predict(text, options, callbacks) { - return this.call(text, options, callbacks); - } - /** - * This method takes a list of messages, options, and callbacks, and - * returns a predicted message. - * @param messages A list of messages for the prediction. - * @param options Options for the LLM call. - * @param callbacks Callbacks for the LLM call. - * @returns A predicted message based on the list of messages. - */ - async predictMessages(messages, options, callbacks) { - const text = (0,base/* getBufferString */.zs)(messages); - const prediction = await this.call(text, options, callbacks); - return new schema/* AIMessage */.gY(prediction); - } - /** - * Get the identifying parameters of the LLM. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _identifyingParams() { - return {}; - } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType(), - }; - } - _modelType() { - return "base_llm"; } - /** - * @deprecated - * Load an LLM from a json-like object describing it. - */ - static async deserialize(data) { - const { _type, _model, ...rest } = data; - if (_model && _model !== "base_llm") { - throw new Error(`Cannot load LLM with model ${_model}`); - } - const Cls = { - openai: (await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 4624))).OpenAI, - }[_type]; - if (Cls === undefined) { - throw new Error(`Cannot load LLM with type ${_type}`); +} +exports.ZodPipeline = ZodPipeline; +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + if ((0, parseUtil_1.isValid)(result)) { + result.value = Object.freeze(result.value); } - return new Cls(rest); + return result; } } +exports.ZodReadonly = ZodReadonly; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +const custom = (check, params = {}, fatal) => { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + var _a, _b; + if (!check(data)) { + const p = typeof params === "function" + ? params(data) + : typeof params === "string" + ? { message: params } + : params; + const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; + const p2 = typeof p === "string" ? { message: p } : p; + ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); + } + }); + return ZodAny.create(); +}; +exports.custom = custom; +exports.late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); +class Class { + constructor(..._) { } +} +const instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}`, +}) => (0, exports.custom)((data) => data instanceof cls, params); +exports["instanceof"] = instanceOfType; +const stringType = ZodString.create; +exports.string = stringType; +const numberType = ZodNumber.create; +exports.number = numberType; +const nanType = ZodNaN.create; +exports.nan = nanType; +const bigIntType = ZodBigInt.create; +exports.bigint = bigIntType; +const booleanType = ZodBoolean.create; +exports.boolean = booleanType; +const dateType = ZodDate.create; +exports.date = dateType; +const symbolType = ZodSymbol.create; +exports.symbol = symbolType; +const undefinedType = ZodUndefined.create; +exports.undefined = undefinedType; +const nullType = ZodNull.create; +exports["null"] = nullType; +const anyType = ZodAny.create; +exports.any = anyType; +const unknownType = ZodUnknown.create; +exports.unknown = unknownType; +const neverType = ZodNever.create; +exports.never = neverType; +const voidType = ZodVoid.create; +exports["void"] = voidType; +const arrayType = ZodArray.create; +exports.array = arrayType; +const objectType = ZodObject.create; +exports.object = objectType; +const strictObjectType = ZodObject.strictCreate; +exports.strictObject = strictObjectType; +const unionType = ZodUnion.create; +exports.union = unionType; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +exports.discriminatedUnion = discriminatedUnionType; +const intersectionType = ZodIntersection.create; +exports.intersection = intersectionType; +const tupleType = ZodTuple.create; +exports.tuple = tupleType; +const recordType = ZodRecord.create; +exports.record = recordType; +const mapType = ZodMap.create; +exports.map = mapType; +const setType = ZodSet.create; +exports.set = setType; +const functionType = ZodFunction.create; +exports["function"] = functionType; +const lazyType = ZodLazy.create; +exports.lazy = lazyType; +const literalType = ZodLiteral.create; +exports.literal = literalType; +const enumType = ZodEnum.create; +exports["enum"] = enumType; +const nativeEnumType = ZodNativeEnum.create; +exports.nativeEnum = nativeEnumType; +const promiseType = ZodPromise.create; +exports.promise = promiseType; +const effectsType = ZodEffects.create; +exports.effect = effectsType; +exports.transformer = effectsType; +const optionalType = ZodOptional.create; +exports.optional = optionalType; +const nullableType = ZodNullable.create; +exports.nullable = nullableType; +const preprocessType = ZodEffects.createWithPreprocess; +exports.preprocess = preprocessType; +const pipelineType = ZodPipeline.create; +exports.pipeline = pipelineType; +const ostring = () => stringType().optional(); +exports.ostring = ostring; +const onumber = () => numberType().optional(); +exports.onumber = onumber; +const oboolean = () => booleanType().optional(); +exports.oboolean = oboolean; +exports.coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +exports.NEVER = parseUtil_1.INVALID; + + +/***/ }), + +/***/ 6144: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.run = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const index_js_1 = __nccwpck_require__(5370); +const dotenv_1 = __importDefault(__nccwpck_require__(2437)); +const utils_js_1 = __nccwpck_require__(1314); +dotenv_1.default.config(); /** - * LLM class that provides a simpler interface to subclass than {@link BaseLLM}. - * - * Requires only implementing a simpler {@link _call} method instead of {@link _generate}. - * - * @augments BaseLLM + * The main function for the action. + * @returns {Promise} Resolves when the action is complete. */ -class LLM extends BaseLLM { - async _generate(prompts, options, runManager) { - const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { ...options, promptIndex }, runManager).then((text) => [{ text }]))); - return { generations }; - } +function run() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + try { + // Extract the PR number from the GitHub context + const pullRequestNumber = (_a = github.context.payload.pull_request) === null || _a === void 0 ? void 0 : _a.number; + utils_js_1.Logger.log('pullRequestNumber', pullRequestNumber); + utils_js_1.Logger.log('github.context', github.context); + // If the PR number is not found, exit the action + if (!pullRequestNumber) { + utils_js_1.Logger.warn('Could not get pull request number from context, exiting'); + return; + } + // Get the changes in the PR + const changes = yield (0, index_js_1.getChanges)(pullRequestNumber); + if (!changes) { + utils_js_1.Logger.warn('Could not get changes, exiting'); + return; + } + // Summarize the changes + const summary = yield (0, index_js_1.summarizeChanges)(changes); + if (!summary) { + utils_js_1.Logger.warn('Could not summarize changes, exiting'); + return; + } + // Post the summary as a comment + yield (0, index_js_1.postComment)(pullRequestNumber, summary); + } + catch (error) { + // Set the action as failed if there is an error + core.setFailed(error === null || error === void 0 ? void 0 : error.message); + } + }); } +exports.run = run; +// eslint-disable-next-line @typescript-eslint/no-floating-promises +run().catch(error => core.setFailed('Workflow failed! ' + error.message)); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/openai.js -var util_openai = __nccwpck_require__(8311); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/llms/openai-chat.js +/***/ }), +/***/ 9699: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generatePrompt = exports.prompt = void 0; +exports.prompt = ` +As an expert PR reviewer with extensive knowledge of version control systems, provide a concise summary of the review for the git diff. +### Instructions +Your summary should include an analysis of the changes made in the git diff, highlighting significant modifications, additions, and deletions. -/** - * Wrapper around OpenAI large language models that use the Chat endpoint. - * - * To use you should have the `openai` package installed, with the - * `OPENAI_API_KEY` environment variable set. - * - * To use with Azure you should have the `openai` package installed, with the - * `AZURE_OPENAI_API_KEY`, - * `AZURE_OPENAI_API_INSTANCE_NAME`, - * `AZURE_OPENAI_API_DEPLOYMENT_NAME` - * and `AZURE_OPENAI_API_VERSION` environment variable set. - * - * @remarks - * Any parameters that are valid to be passed to {@link - * https://platform.openai.com/docs/api-reference/chat/create | - * `openai.createCompletion`} can be passed through {@link modelKwargs}, even - * if not explicitly available on this class. - * - * @augments BaseLLM - * @augments OpenAIInput - * @augments AzureOpenAIChatInput - */ -class OpenAIChat extends LLM { - static lc_name() { - return "OpenAIChat"; - } - get callKeys() { - return [...super.callKeys, "options", "promptIndex"]; - } - get lc_secrets() { - return { - openAIApiKey: "OPENAI_API_KEY", - azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION", - }; - } - get lc_aliases() { - return { - modelName: "model", - openAIApiKey: "openai_api_key", - azureOpenAIApiVersion: "azure_openai_api_version", - azureOpenAIApiKey: "azure_openai_api_key", - azureOpenAIApiInstanceName: "azure_openai_api_instance_name", - azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", - }; +Be specific and descriptive, accurately identifying the affected files and lines of code. + +Present your summary in a clear and concise manner, ensuring readability and comprehension for all stakeholders involved in the code review process. + +Length: Aim for a summary of around 3-5 sentences. + +Style: Maintain a professional and objective tone in your review, emphasizing the technical aspects and impact of the changes rather than personal opinions. + +Formatting: Use Markdown to format your summary. +e.g. + ## Title + + # Issue Reference + + - This PR fixes/closes/relates to issue #[issue number] + + ## Description + + - Detailed explanation of what this PR does and why it's needed. + + ## Why? + + - Explanation of the reasoning behind the changes. + + ## Testing Scope + + - Scenarios to be tested based on the changes of this PR e.g table was updated so all CRUD operations should be tested. + `; +const generatePrompt = () => { }; +exports.generatePrompt = generatePrompt; + + +/***/ }), + +/***/ 1256: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - constructor(fields, - /** @deprecated */ - configuration) { - super(fields ?? {}); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "temperature", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "topP", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "frequencyPenalty", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "presencePenalty", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "n", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "logitBias", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxTokens", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "modelName", { - enumerable: true, - configurable: true, - writable: true, - value: "gpt-3.5-turbo" - }); - Object.defineProperty(this, "prefixMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "modelKwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "stop", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "user", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "streaming", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "openAIApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiVersion", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiInstanceName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiDeploymentName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIBasePath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "organization", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "clientConfig", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.openAIApiKey = - fields?.openAIApiKey ?? (0,env/* getEnvironmentVariable */.lS)("OPENAI_API_KEY"); - this.azureOpenAIApiKey = - fields?.azureOpenAIApiKey ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_KEY"); - if (!this.azureOpenAIApiKey && !this.openAIApiKey) { - throw new Error("OpenAI or Azure OpenAI API key not found"); - } - this.azureOpenAIApiInstanceName = - fields?.azureOpenAIApiInstanceName ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = - (fields?.azureOpenAIApiCompletionsDeploymentName || - fields?.azureOpenAIApiDeploymentName) ?? - ((0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_DEPLOYMENT_NAME")); - this.azureOpenAIApiVersion = - fields?.azureOpenAIApiVersion ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = - fields?.azureOpenAIBasePath ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_BASE_PATH"); - this.organization = - fields?.configuration?.organization ?? - (0,env/* getEnvironmentVariable */.lS)("OPENAI_ORGANIZATION"); - this.modelName = fields?.modelName ?? this.modelName; - this.prefixMessages = fields?.prefixMessages ?? this.prefixMessages; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.n = fields?.n ?? this.n; - this.logitBias = fields?.logitBias; - this.maxTokens = fields?.maxTokens; - this.stop = fields?.stop; - this.user = fields?.user; - this.streaming = fields?.streaming ?? false; - if (this.n > 1) { - throw new Error("Cannot use n > 1 in OpenAIChat LLM. Use ChatOpenAI Chat Model instead."); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getChanges = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const axios_1 = __importDefault(__nccwpck_require__(8757)); +const utils_js_1 = __nccwpck_require__(1314); +function getChanges(pullRequestNumber) { + return __awaiter(this, void 0, void 0, function* () { + try { + utils_js_1.Logger.log('getting changes', pullRequestNumber); + const githubToken = core.getInput('token'); + const octokit = github.getOctokit(githubToken); + const repo = github.context.repo; + const { data: files } = yield octokit.rest.pulls.get(Object.assign(Object.assign({}, repo), { pull_number: pullRequestNumber, mediaType: { + format: 'diff' + } })); + utils_js_1.Logger.log('got changes diff', files); + const response = yield axios_1.default.get(files.diff_url); + utils_js_1.Logger.log('diff', response.data); + return response.data; } - if (this.azureOpenAIApiKey) { - if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { - throw new Error("Azure OpenAI API instance name not found"); - } - if (!this.azureOpenAIApiDeploymentName) { - throw new Error("Azure OpenAI API deployment name not found"); - } - if (!this.azureOpenAIApiVersion) { - throw new Error("Azure OpenAI API version not found"); - } - this.openAIApiKey = this.openAIApiKey ?? ""; + catch (error) { + utils_js_1.Logger.error('error getting changes'); } - this.clientConfig = { - apiKey: this.openAIApiKey, - organization: this.organization, - baseURL: configuration?.basePath ?? fields?.configuration?.basePath, - dangerouslyAllowBrowser: true, - defaultHeaders: configuration?.baseOptions?.headers ?? - fields?.configuration?.baseOptions?.headers, - defaultQuery: configuration?.baseOptions?.params ?? - fields?.configuration?.baseOptions?.params, - ...configuration, - ...fields?.configuration, - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - return { - model: this.modelName, - temperature: this.temperature, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - n: this.n, - logit_bias: this.logitBias, - max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens, - stop: options?.stop ?? this.stop, - user: this.user, - stream: this.streaming, - ...this.modelKwargs, - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.modelName, - ...this.invocationParams(), - ...this.clientConfig, - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return { - model_name: this.modelName, - ...this.invocationParams(), - ...this.clientConfig, - }; + }); +} +exports.getChanges = getChanges; + + +/***/ }), + +/***/ 5370: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - /** - * Formats the messages for the OpenAI API. - * @param prompt The prompt to be formatted. - * @returns Array of formatted messages. - */ - formatMessages(prompt) { - const message = { - role: "user", - content: prompt, - }; - return this.prefixMessages ? [...this.prefixMessages, message] : [message]; + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(1256), exports); +__exportStar(__nccwpck_require__(3764), exports); +__exportStar(__nccwpck_require__(1177), exports); + + +/***/ }), + +/***/ 3764: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - async *_streamResponseChunks(prompt, options, runManager) { - const params = { - ...this.invocationParams(options), - messages: this.formatMessages(prompt), - stream: true, - }; - const stream = await this.completionWithRetry(params, options); - for await (const data of stream) { - const choice = data?.choices[0]; - if (!choice) { - continue; - } - const { delta } = choice; - const generationChunk = new schema/* GenerationChunk */.b6({ - text: delta.content ?? "", + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.postComment = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const utils_js_1 = __nccwpck_require__(1314); +function postComment(pullRequestNumber, summary) { + return __awaiter(this, void 0, void 0, function* () { + const githubToken = core.getInput('token'); + const octokit = github.getOctokit(githubToken); + const repo = github.context.repo; + utils_js_1.Logger.log('posted comment', github.context); + const { data } = yield octokit.rest.pulls.update(Object.assign(Object.assign({}, repo), { pull_number: pullRequestNumber, body: summary })); + utils_js_1.Logger.log('posted comment', data.body); + }); +} +exports.postComment = postComment; + + +/***/ }), + +/***/ 1177: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.summarizeChanges = void 0; +const openai_1 = __nccwpck_require__(147); +const chains_1 = __nccwpck_require__(9248); +const text_splitter_1 = __nccwpck_require__(8356); +const prompts_1 = __nccwpck_require__(224); +const prompts_js_1 = __nccwpck_require__(9699); +const utils_js_1 = __nccwpck_require__(1314); +function summarizeChanges(diff) { + return __awaiter(this, void 0, void 0, function* () { + try { + utils_js_1.Logger.log('summarizing changes'); + const model = new openai_1.OpenAI({ temperature: 0 }); + utils_js_1.Logger.log('created model'); + const textSplitter = new text_splitter_1.RecursiveCharacterTextSplitter({ + chunkSize: 1000, + separators: ['diff --git'], + chunkOverlap: 0, + keepSeparator: true }); - yield generationChunk; - const newTokenIndices = { - prompt: options.promptIndex ?? 0, - completion: choice.index ?? 0, - }; - // eslint-disable-next-line no-void - void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices); - } - if (options.signal?.aborted) { - throw new Error("AbortError"); - } - } - /** @ignore */ - async _call(prompt, options, runManager) { - const params = this.invocationParams(options); - if (params.stream) { - const stream = await this._streamResponseChunks(prompt, options, runManager); - let finalChunk; - for await (const chunk of stream) { - if (finalChunk === undefined) { - finalChunk = chunk; - } - else { - finalChunk = finalChunk.concat(chunk); - } - } - return finalChunk?.text ?? ""; - } - else { - const response = await this.completionWithRetry({ - ...params, - stream: false, - messages: this.formatMessages(prompt), - }, { - signal: options.signal, - ...options.options, + utils_js_1.Logger.log('created text splitter'); + const docs = yield textSplitter.createDocuments([diff]); + const basePromptTemplate = prompts_1.PromptTemplate.fromTemplate(prompts_js_1.prompt); + utils_js_1.Logger.log('created prompt template'); + const chain = (0, chains_1.loadSummarizationChain)(model, { + prompt: basePromptTemplate, + verbose: true, + type: 'stuff' }); - return response?.choices[0]?.message?.content ?? ""; - } - } - async completionWithRetry(request, options) { - const requestOptions = this._getClientOptions(options); - return this.caller.call(async () => { - try { - const res = await this.client.chat.completions.create(request, requestOptions); - return res; - } - catch (e) { - const error = (0,util_openai/* wrapOpenAIClientError */.K)(e); - throw error; - } - }); - } - /** @ignore */ - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - baseURL: this.clientConfig.baseURL, - }; - const endpoint = (0,azure/* getEndpoint */.O)(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0, - }; - if (!params.baseURL) { - delete params.baseURL; - } - this.client = new openai/* OpenAI */.Pp(params); + utils_js_1.Logger.log('loaded summarization chain'); + const res = yield chain.call({ + input_documents: docs + }); + utils_js_1.Logger.log('summarized changes'); + console.log({ res }); + return res.output.join('\n'); } - const requestOptions = { - ...this.clientConfig, - ...options, - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers, - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query, - }; + catch (e) { + utils_js_1.Logger.log('error summarizing changes'); + utils_js_1.Logger.error(JSON.stringify(e)); } - return requestOptions; - } - _llmType() { - return "openai"; - } + }); } -/** - * PromptLayer wrapper to OpenAIChat - */ -class PromptLayerOpenAIChat extends OpenAIChat { - get lc_secrets() { - return { - promptLayerApiKey: "PROMPTLAYER_API_KEY", - }; +exports.summarizeChanges = summarizeChanges; + + +/***/ }), + +/***/ 1314: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "promptLayerApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "plTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "returnPromptLayerId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.plTags = fields?.plTags ?? []; - this.returnPromptLayerId = fields?.returnPromptLayerId ?? false; - this.promptLayerApiKey = - fields?.promptLayerApiKey ?? - (0,env/* getEnvironmentVariable */.lS)("PROMPTLAYER_API_KEY"); - if (!this.promptLayerApiKey) { - throw new Error("Missing PromptLayer API key"); - } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Logger = void 0; +const core = __importStar(__nccwpck_require__(2186)); +class Logger { + static log(...args) { + const message = args.map(arg => JSON.stringify(arg)).join(' '); + core.info(message); } - async _generate(prompts, options, runManager) { - let choice; - const generations = await Promise.all(prompts.map(async (prompt) => { - const requestStartTime = Date.now(); - const text = await this._call(prompt, options, runManager); - const requestEndTime = Date.now(); - choice = [{ text }]; - const parsedResp = { - text, - }; - const promptLayerRespBody = await (0,prompt_layer/* promptLayerTrackRequest */.r)(this.caller, "langchain.PromptLayerOpenAIChat", - // eslint-disable-next-line @typescript-eslint/no-explicit-any - { ...this._identifyingParams(), prompt }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); - if (this.returnPromptLayerId === true && - promptLayerRespBody.success === true) { - choice[0].generationInfo = { - promptLayerRequestId: promptLayerRespBody.request_id, - }; - } - return choice; - })); - return { generations }; + static warn(message) { + core.warning(message); + } + static error(message, ...args) { + const formattedArgs = args.map(arg => JSON.stringify(arg)).join(' '); + core.error(`${message}: ${formattedArgs}`); } } +exports.Logger = Logger; -;// CONCATENATED MODULE: ./node_modules/langchain/dist/llms/openai.js +/***/ }), +/***/ 2877: +/***/ ((module) => { +module.exports = eval("require")("encoding"); +/***/ }), +/***/ 9491: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); +/***/ }), +/***/ 6113: +/***/ ((module) => { -/** - * Wrapper around OpenAI large language models. - * - * To use you should have the `openai` package installed, with the - * `OPENAI_API_KEY` environment variable set. - * - * To use with Azure you should have the `openai` package installed, with the - * `AZURE_OPENAI_API_KEY`, - * `AZURE_OPENAI_API_INSTANCE_NAME`, - * `AZURE_OPENAI_API_DEPLOYMENT_NAME` - * and `AZURE_OPENAI_API_VERSION` environment variable set. - * - * @remarks - * Any parameters that are valid to be passed to {@link - * https://platform.openai.com/docs/api-reference/completions/create | - * `openai.createCompletion`} can be passed through {@link modelKwargs}, even - * if not explicitly available on this class. - */ -class OpenAI extends BaseLLM { - static lc_name() { - return "OpenAI"; - } - get callKeys() { - return [...super.callKeys, "options"]; - } - get lc_secrets() { - return { - openAIApiKey: "OPENAI_API_KEY", - azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION", - }; - } - get lc_aliases() { - return { - modelName: "model", - openAIApiKey: "openai_api_key", - azureOpenAIApiVersion: "azure_openai_api_version", - azureOpenAIApiKey: "azure_openai_api_key", - azureOpenAIApiInstanceName: "azure_openai_api_instance_name", - azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", - }; - } - constructor(fields, - /** @deprecated */ - configuration) { - if ((fields?.modelName?.startsWith("gpt-3.5-turbo") || - fields?.modelName?.startsWith("gpt-4")) && - !fields?.modelName?.includes("-instruct")) { - // eslint-disable-next-line no-constructor-return - return new OpenAIChat(fields, configuration); - } - super(fields ?? {}); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "temperature", { - enumerable: true, - configurable: true, - writable: true, - value: 0.7 - }); - Object.defineProperty(this, "maxTokens", { - enumerable: true, - configurable: true, - writable: true, - value: 256 - }); - Object.defineProperty(this, "topP", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "frequencyPenalty", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "presencePenalty", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "n", { - enumerable: true, - configurable: true, - writable: true, - value: 1 - }); - Object.defineProperty(this, "bestOf", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "logitBias", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "modelName", { - enumerable: true, - configurable: true, - writable: true, - value: "text-davinci-003" - }); - Object.defineProperty(this, "modelKwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchSize", { - enumerable: true, - configurable: true, - writable: true, - value: 20 - }); - Object.defineProperty(this, "timeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "stop", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "user", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "streaming", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "openAIApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiVersion", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiInstanceName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIApiDeploymentName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "azureOpenAIBasePath", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "organization", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "clientConfig", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.openAIApiKey = - fields?.openAIApiKey ?? (0,env/* getEnvironmentVariable */.lS)("OPENAI_API_KEY"); - this.azureOpenAIApiKey = - fields?.azureOpenAIApiKey ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_KEY"); - if (!this.azureOpenAIApiKey && !this.openAIApiKey) { - throw new Error("OpenAI or Azure OpenAI API key not found"); +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); + +/***/ }), + +/***/ 2361: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); + +/***/ }), + +/***/ 7147: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); + +/***/ }), + +/***/ 3685: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); + +/***/ }), + +/***/ 5687: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); + +/***/ }), + +/***/ 1808: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); + +/***/ }), + +/***/ 7561: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); + +/***/ }), + +/***/ 4492: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); + +/***/ }), + +/***/ 2037: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); + +/***/ }), + +/***/ 1017: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); + +/***/ }), + +/***/ 5477: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("punycode"); + +/***/ }), + +/***/ 2781: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); + +/***/ }), + +/***/ 4404: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); + +/***/ }), + +/***/ 6224: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty"); + +/***/ }), + +/***/ 7310: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); + +/***/ }), + +/***/ 3837: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); + +/***/ }), + +/***/ 1267: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); + +/***/ }), + +/***/ 9796: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); + +/***/ }), + +/***/ 1778: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + +/***/ }), + +/***/ 5860: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Encoder = exports.FormDataEncoder = void 0; +const createBoundary_1 = __importDefault(__nccwpck_require__(7956)); +const isPlainObject_1 = __importDefault(__nccwpck_require__(5240)); +const normalizeValue_1 = __importDefault(__nccwpck_require__(1391)); +const escapeName_1 = __importDefault(__nccwpck_require__(3864)); +const isFileLike_1 = __nccwpck_require__(6860); +const isFormData_1 = __nccwpck_require__(1633); +const defaultOptions = { + enableAdditionalHeaders: false +}; +class FormDataEncoder { + constructor(form, boundaryOrOptions, options) { + _FormDataEncoder_instances.add(this); + _FormDataEncoder_CRLF.set(this, "\r\n"); + _FormDataEncoder_CRLF_BYTES.set(this, void 0); + _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0); + _FormDataEncoder_DASHES.set(this, "-".repeat(2)); + _FormDataEncoder_encoder.set(this, new TextEncoder()); + _FormDataEncoder_footer.set(this, void 0); + _FormDataEncoder_form.set(this, void 0); + _FormDataEncoder_options.set(this, void 0); + if (!(0, isFormData_1.isFormData)(form)) { + throw new TypeError("Expected first argument to be a FormData instance."); } - this.azureOpenAIApiInstanceName = - fields?.azureOpenAIApiInstanceName ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = - (fields?.azureOpenAIApiCompletionsDeploymentName || - fields?.azureOpenAIApiDeploymentName) ?? - ((0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_DEPLOYMENT_NAME")); - this.azureOpenAIApiVersion = - fields?.azureOpenAIApiVersion ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = - fields?.azureOpenAIBasePath ?? - (0,env/* getEnvironmentVariable */.lS)("AZURE_OPENAI_BASE_PATH"); - this.organization = - fields?.configuration?.organization ?? - (0,env/* getEnvironmentVariable */.lS)("OPENAI_ORGANIZATION"); - this.modelName = fields?.modelName ?? this.modelName; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.batchSize = fields?.batchSize ?? this.batchSize; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.maxTokens = fields?.maxTokens ?? this.maxTokens; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.n = fields?.n ?? this.n; - this.bestOf = fields?.bestOf ?? this.bestOf; - this.logitBias = fields?.logitBias; - this.stop = fields?.stop; - this.user = fields?.user; - this.streaming = fields?.streaming ?? false; - if (this.streaming && this.bestOf && this.bestOf > 1) { - throw new Error("Cannot stream results when bestOf > 1"); + let boundary; + if ((0, isPlainObject_1.default)(boundaryOrOptions)) { + options = boundaryOrOptions; } - if (this.azureOpenAIApiKey) { - if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { - throw new Error("Azure OpenAI API instance name not found"); - } - if (!this.azureOpenAIApiDeploymentName) { - throw new Error("Azure OpenAI API deployment name not found"); - } - if (!this.azureOpenAIApiVersion) { - throw new Error("Azure OpenAI API version not found"); - } - this.openAIApiKey = this.openAIApiKey ?? ""; + else { + boundary = boundaryOrOptions; } - this.clientConfig = { - apiKey: this.openAIApiKey, - organization: this.organization, - baseURL: configuration?.basePath ?? fields?.configuration?.basePath, - dangerouslyAllowBrowser: true, - defaultHeaders: configuration?.baseOptions?.headers ?? - fields?.configuration?.baseOptions?.headers, - defaultQuery: configuration?.baseOptions?.params ?? - fields?.configuration?.baseOptions?.params, - ...configuration, - ...fields?.configuration, - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - return { - model: this.modelName, - temperature: this.temperature, - max_tokens: this.maxTokens, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - n: this.n, - best_of: this.bestOf, - logit_bias: this.logitBias, - stop: options?.stop ?? this.stop, - user: this.user, - stream: this.streaming, - ...this.modelKwargs, - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.modelName, - ...this.invocationParams(), - ...this.clientConfig, - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return this._identifyingParams(); - } - /** - * Call out to OpenAI's endpoint with k unique prompts - * - * @param [prompts] - The prompts to pass into the model. - * @param [options] - Optional list of stop words to use when generating. - * @param [runManager] - Optional callback manager to use when generating. - * - * @returns The full LLM output. - * - * @example - * ```ts - * import { OpenAI } from "langchain/llms/openai"; - * const openai = new OpenAI(); - * const response = await openai.generate(["Tell me a joke."]); - * ``` - */ - async _generate(prompts, options, runManager) { - const subPrompts = chunkArray(prompts, this.batchSize); - const choices = []; - const tokenUsage = {}; - const params = this.invocationParams(options); - if (params.max_tokens === -1) { - if (prompts.length !== 1) { - throw new Error("max_tokens set to -1 not supported for multiple inputs"); - } - params.max_tokens = await (0,count_tokens/* calculateMaxTokens */.F1)({ - prompt: prompts[0], - // Cast here to allow for other models that may not fit the union - modelName: this.modelName, - }); + if (!boundary) { + boundary = (0, createBoundary_1.default)(); } - for (let i = 0; i < subPrompts.length; i += 1) { - const data = params.stream - ? await (async () => { - const choices = []; - let response; - const stream = await this.completionWithRetry({ - ...params, - stream: true, - prompt: subPrompts[i], - }, options); - for await (const message of stream) { - // on the first message set the response properties - if (!response) { - response = { - id: message.id, - object: message.object, - created: message.created, - model: message.model, - }; - } - // on all messages, update choice - for (const part of message.choices) { - if (!choices[part.index]) { - choices[part.index] = part; - } - else { - const choice = choices[part.index]; - choice.text += part.text; - choice.finish_reason = part.finish_reason; - choice.logprobs = part.logprobs; - } - void runManager?.handleLLMNewToken(part.text, { - prompt: Math.floor(part.index / this.n), - completion: part.index % this.n, - }); - } - } - if (options.signal?.aborted) { - throw new Error("AbortError"); - } - return { ...response, choices }; - })() - : await this.completionWithRetry({ - ...params, - stream: false, - prompt: subPrompts[i], - }, { - signal: options.signal, - ...options.options, - }); - choices.push(...data.choices); - const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage - ? data.usage - : { - completion_tokens: undefined, - prompt_tokens: undefined, - total_tokens: undefined, - }; - if (completionTokens) { - tokenUsage.completionTokens = - (tokenUsage.completionTokens ?? 0) + completionTokens; - } - if (promptTokens) { - tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; - } - if (totalTokens) { - tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; - } + if (typeof boundary !== "string") { + throw new TypeError("Expected boundary argument to be a string."); } - const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ - text: choice.text ?? "", - generationInfo: { - finishReason: choice.finish_reason, - logprobs: choice.logprobs, - }, - }))); - return { - generations, - llmOutput: { tokenUsage }, - }; + if (options && !(0, isPlainObject_1.default)(options)) { + throw new TypeError("Expected options argument to be an object."); + } + __classPrivateFieldSet(this, _FormDataEncoder_form, form, "f"); + __classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f"); + __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")), "f"); + __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f"); + this.boundary = `form-data-boundary-${boundary}`; + this.contentType = `multipart/form-data; boundary=${this.boundary}`; + __classPrivateFieldSet(this, _FormDataEncoder_footer, __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f"); + this.contentLength = String(this.getContentLength()); + this.headers = Object.freeze({ + "Content-Type": this.contentType, + "Content-Length": this.contentLength + }); + Object.defineProperties(this, { + boundary: { writable: false, configurable: false }, + contentType: { writable: false, configurable: false }, + contentLength: { writable: false, configurable: false }, + headers: { writable: false, configurable: false } + }); } - // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation? - async *_streamResponseChunks(input, options, runManager) { - const params = { - ...this.invocationParams(options), - prompt: input, - stream: true, - }; - const stream = await this.completionWithRetry(params, options); - for await (const data of stream) { - const choice = data?.choices[0]; - if (!choice) { - continue; - } - const chunk = new schema/* GenerationChunk */.b6({ - text: choice.text, - generationInfo: { - finishReason: choice.finish_reason, - }, - }); - yield chunk; - // eslint-disable-next-line no-void - void runManager?.handleLLMNewToken(chunk.text ?? ""); + getContentLength() { + let length = 0; + for (const [name, raw] of __classPrivateFieldGet(this, _FormDataEncoder_form, "f")) { + const value = (0, isFileLike_1.isFileLike)(raw) ? raw : __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode((0, normalizeValue_1.default)(raw)); + length += __classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength; + length += (0, isFileLike_1.isFileLike)(value) ? value.size : value.byteLength; + length += __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f"); } - if (options.signal?.aborted) { - throw new Error("AbortError"); + return length + __classPrivateFieldGet(this, _FormDataEncoder_footer, "f").byteLength; + } + *values() { + for (const [name, raw] of __classPrivateFieldGet(this, _FormDataEncoder_form, "f").entries()) { + const value = (0, isFileLike_1.isFileLike)(raw) ? raw : __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode((0, normalizeValue_1.default)(raw)); + yield __classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value); + yield value; + yield __classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f"); } + yield __classPrivateFieldGet(this, _FormDataEncoder_footer, "f"); } - async completionWithRetry(request, options) { - const requestOptions = this._getClientOptions(options); - return this.caller.call(async () => { - try { - const res = await this.client.completions.create(request, requestOptions); - return res; + async *encode() { + for (const part of this.values()) { + if ((0, isFileLike_1.isFileLike)(part)) { + yield* part.stream(); } - catch (e) { - const error = (0,util_openai/* wrapOpenAIClientError */.K)(e); - throw error; + else { + yield part; } - }); + } } - /** - * Calls the OpenAI API with retry logic in case of failures. - * @param request The request to send to the OpenAI API. - * @param options Optional configuration for the API call. - * @returns The response from the OpenAI API. - */ - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - baseURL: this.clientConfig.baseURL, - }; - const endpoint = (0,azure/* getEndpoint */.O)(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0, - }; - if (!params.baseURL) { - delete params.baseURL; - } - this.client = new openai/* OpenAI */.Pp(params); + [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) { + let header = ""; + header += `${__classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; + header += `Content-Disposition: form-data; name="${(0, escapeName_1.default)(name)}"`; + if ((0, isFileLike_1.isFileLike)(value)) { + header += `; filename="${(0, escapeName_1.default)(value.name)}"${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; + header += `Content-Type: ${value.type || "application/octet-stream"}`; } - const requestOptions = { - ...this.clientConfig, - ...options, - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers, - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query, - }; + if (__classPrivateFieldGet(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) { + header += `${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${(0, isFileLike_1.isFileLike)(value) ? value.size : value.byteLength}`; } - return requestOptions; + return __classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${header}${__classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`); + }, Symbol.iterator)]() { + return this.values(); } - _llmType() { - return "openai"; + [Symbol.asyncIterator]() { + return this.encode(); } } -/** - * PromptLayer wrapper to OpenAI - * @augments OpenAI - */ -class PromptLayerOpenAI extends OpenAI { - get lc_secrets() { - return { - promptLayerApiKey: "PROMPTLAYER_API_KEY", - }; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "promptLayerApiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "plTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "returnPromptLayerId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.plTags = fields?.plTags ?? []; - this.promptLayerApiKey = - fields?.promptLayerApiKey ?? - (0,env/* getEnvironmentVariable */.lS)("PROMPTLAYER_API_KEY"); - this.returnPromptLayerId = fields?.returnPromptLayerId; - if (!this.promptLayerApiKey) { - throw new Error("Missing PromptLayer API key"); - } +exports.FormDataEncoder = FormDataEncoder; +exports.Encoder = FormDataEncoder; + + +/***/ }), + +/***/ 6921: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + +/***/ }), + +/***/ 8824: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(5860), exports); +__exportStar(__nccwpck_require__(1778), exports); +__exportStar(__nccwpck_require__(6921), exports); +__exportStar(__nccwpck_require__(6860), exports); +__exportStar(__nccwpck_require__(1633), exports); + + +/***/ }), + +/***/ 7956: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; +function createBoundary() { + let size = 16; + let res = ""; + while (size--) { + res += alphabet[(Math.random() * alphabet.length) << 0]; } - async _generate(prompts, options, runManager) { - const requestStartTime = Date.now(); - const generations = await super._generate(prompts, options, runManager); - for (let i = 0; i < generations.generations.length; i += 1) { - const requestEndTime = Date.now(); - const parsedResp = { - text: generations.generations[i][0].text, - llm_output: generations.llmOutput, - }; - const promptLayerRespBody = await (0,prompt_layer/* promptLayerTrackRequest */.r)(this.caller, "langchain.PromptLayerOpenAI", - // eslint-disable-next-line @typescript-eslint/no-explicit-any - { ...this._identifyingParams(), prompt: prompts[i] }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); - let promptLayerRequestId; - if (this.returnPromptLayerId === true) { - if (promptLayerRespBody && promptLayerRespBody.success === true) { - promptLayerRequestId = promptLayerRespBody.request_id; - } - generations.generations[i][0].generationInfo = { - ...generations.generations[i][0].generationInfo, - promptLayerRequestId, - }; - } - } - return generations; + return res; +} +exports["default"] = createBoundary; + + +/***/ }), + +/***/ 3864: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const escapeName = (name) => String(name) + .replace(/\r/g, "%0D") + .replace(/\n/g, "%0A") + .replace(/"/g, "%22"); +exports["default"] = escapeName; + + +/***/ }), + +/***/ 6860: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isFileLike = void 0; +const isFunction_1 = __importDefault(__nccwpck_require__(2498)); +const isFileLike = (value) => Boolean(value + && typeof value === "object" + && (0, isFunction_1.default)(value.constructor) + && value[Symbol.toStringTag] === "File" + && (0, isFunction_1.default)(value.stream) + && value.name != null + && value.size != null + && value.lastModified != null); +exports.isFileLike = isFileLike; + + +/***/ }), + +/***/ 1633: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isFormDataLike = exports.isFormData = void 0; +const isFunction_1 = __importDefault(__nccwpck_require__(2498)); +const isFormData = (value) => Boolean(value + && (0, isFunction_1.default)(value.constructor) + && value[Symbol.toStringTag] === "FormData" + && (0, isFunction_1.default)(value.append) + && (0, isFunction_1.default)(value.getAll) + && (0, isFunction_1.default)(value.entries) + && (0, isFunction_1.default)(value[Symbol.iterator])); +exports.isFormData = isFormData; +exports.isFormDataLike = exports.isFormData; + + +/***/ }), + +/***/ 2498: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const isFunction = (value) => (typeof value === "function"); +exports["default"] = isFunction; + + +/***/ }), + +/***/ 5240: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); +function isPlainObject(value) { + if (getType(value) !== "object") { + return false; + } + const pp = Object.getPrototypeOf(value); + if (pp === null || pp === undefined) { + return true; } + const Ctor = pp.constructor && pp.constructor.toString(); + return Ctor === Object.toString(); } - +exports["default"] = isPlainObject; /***/ }), -/***/ 4432: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 1391: +/***/ ((__unused_webpack_module, exports) => { -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "i": () => (/* binding */ Serializable), - "j": () => (/* binding */ get_lc_unique_name) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const normalizeValue = (value) => String(value) + .replace(/\r|\n/g, (match, i, str) => { + if ((match === "\r" && str[i + 1] !== "\n") + || (match === "\n" && str[i - 1] !== "\r")) { + return "\r\n"; + } + return match; }); +exports["default"] = normalizeValue; -// EXTERNAL MODULE: ./node_modules/decamelize/index.js -var decamelize = __nccwpck_require__(159); -// EXTERNAL MODULE: ./node_modules/langchain/node_modules/camelcase/index.js -var camelcase = __nccwpck_require__(996); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/load/map_keys.js +/***/ }), -function keyToJson(key, map) { - return map?.[key] || decamelize(key); -} -function keyFromJson(key, map) { - return map?.[key] || camelCase(key); -} -function mapKeys(fields, mapper, map) { - const mapped = {}; - for (const key in fields) { - if (Object.hasOwn(fields, key)) { - mapped[mapper(key, map)] = fields[key]; - } - } - return mapped; -} +/***/ 6637: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -;// CONCATENATED MODULE: ./node_modules/langchain/dist/load/serializable.js -function shallowCopy(obj) { - return Array.isArray(obj) ? [...obj] : { ...obj }; -} -function replaceSecrets(root, secretsMap) { - const result = shallowCopy(root); - for (const [path, secretId] of Object.entries(secretsMap)) { - const [last, ...partsReverse] = path.split(".").reverse(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let current = result; - for (const part of partsReverse.reverse()) { - if (current[part] === undefined) { - break; - } - current[part] = shallowCopy(current[part]); - current = current[part]; +/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _Blob_parts, _Blob_type, _Blob_size; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Blob = void 0; +const web_streams_polyfill_1 = __nccwpck_require__(5650); +const isFunction_1 = __nccwpck_require__(4245); +const blobHelpers_1 = __nccwpck_require__(7058); +class Blob { + constructor(blobParts = [], options = {}) { + _Blob_parts.set(this, []); + _Blob_type.set(this, ""); + _Blob_size.set(this, 0); + options !== null && options !== void 0 ? options : (options = {}); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': " + + "The provided value cannot be converted to a sequence."); } - if (current[last] !== undefined) { - current[last] = { - lc: 1, - type: "secret", - id: [secretId], - }; + if (!(0, isFunction_1.isFunction)(blobParts[Symbol.iterator])) { + throw new TypeError("Failed to construct 'Blob': " + + "The object must have a callable @@iterator property."); } + if (typeof options !== "object" && !(0, isFunction_1.isFunction)(options)) { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + const encoder = new TextEncoder(); + for (const raw of blobParts) { + let part; + if (ArrayBuffer.isView(raw)) { + part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); + } + else if (raw instanceof ArrayBuffer) { + part = new Uint8Array(raw.slice(0)); + } + else if (raw instanceof Blob) { + part = raw; + } + else { + part = encoder.encode(String(raw)); + } + __classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f"); + __classPrivateFieldGet(this, _Blob_parts, "f").push(part); + } + const type = options.type === undefined ? "" : String(options.type); + __classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f"); } - return result; -} -/** - * Get a unique name for the module, rather than parent class implementations. - * Should not be subclassed, subclass lc_name above instead. - */ -function get_lc_unique_name( -// eslint-disable-next-line @typescript-eslint/no-use-before-define -serializableClass) { - // "super" here would refer to the parent class of Serializable, - // when we want the parent class of the module actually calling this method. - const parentClass = Object.getPrototypeOf(serializableClass); - const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && - (typeof parentClass.lc_name !== "function" || - serializableClass.lc_name() !== parentClass.lc_name()); - if (lcNameIsSubclassed) { - return serializableClass.lc_name(); - } - else { - return serializableClass.name; - } -} -class Serializable { - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - get_lc_unique_name(this.constructor), - ]; - } - /** - * A map of secrets, which will be omitted from serialization. - * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". - * Values are the secret ids, which will be used when deserializing. - */ - get lc_secrets() { - return undefined; + static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) { + return Boolean(value + && typeof value === "object" + && (0, isFunction_1.isFunction)(value.constructor) + && ((0, isFunction_1.isFunction)(value.stream) + || (0, isFunction_1.isFunction)(value.arrayBuffer)) + && /^(Blob|File)$/.test(value[Symbol.toStringTag])); } - /** - * A map of additional attributes to merge with constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the attribute values, which will be serialized. - * These attributes need to be accepted by the constructor as arguments. - */ - get lc_attributes() { - return undefined; + get type() { + return __classPrivateFieldGet(this, _Blob_type, "f"); } - /** - * A map of aliases for constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the alias that will replace the key in serialization. - * This is used to eg. make argument names match Python. - */ - get lc_aliases() { - return undefined; + get size() { + return __classPrivateFieldGet(this, _Blob_size, "f"); } - constructor(kwargs, ..._args) { - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + slice(start, end, contentType) { + return new Blob((0, blobHelpers_1.sliceBlob)(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), { + type: contentType }); - this.lc_kwargs = kwargs || {}; } - toJSON() { - if (!this.lc_serializable) { - return this.toJSONNotImplemented(); - } - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - this.lc_kwargs instanceof Serializable || - typeof this.lc_kwargs !== "object" || - Array.isArray(this.lc_kwargs)) { - // We do not support serialization of classes with arg not a POJO - // I'm aware the check above isn't as strict as it could be - return this.toJSONNotImplemented(); + async text() { + const decoder = new TextDecoder(); + let result = ""; + for await (const chunk of (0, blobHelpers_1.consumeBlobParts)(__classPrivateFieldGet(this, _Blob_parts, "f"))) { + result += decoder.decode(chunk, { stream: true }); } - const aliases = {}; - const secrets = {}; - const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { - acc[key] = key in this ? this[key] : this.lc_kwargs[key]; - return acc; - }, {}); - // get secrets, attributes and aliases from all superclasses - for ( - // eslint-disable-next-line @typescript-eslint/no-this-alias - let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { - Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); - Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); - Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + result += decoder.decode(); + return result; + } + async arrayBuffer() { + const view = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of (0, blobHelpers_1.consumeBlobParts)(__classPrivateFieldGet(this, _Blob_parts, "f"))) { + view.set(chunk, offset); + offset += chunk.length; } - // include all secrets used, even if not in kwargs, - // will be replaced with sentinel value in replaceSecrets - Object.keys(secrets).forEach((keyPath) => { - // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any - let read = this; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let write = kwargs; - const [last, ...partsReverse] = keyPath.split(".").reverse(); - for (const key of partsReverse.reverse()) { - if (!(key in read) || read[key] === undefined) - return; - if (!(key in write) || write[key] === undefined) { - if (typeof read[key] === "object" && read[key] != null) { - write[key] = {}; - } - else if (Array.isArray(read[key])) { - write[key] = []; - } + return view.buffer; + } + stream() { + const iterator = (0, blobHelpers_1.consumeBlobParts)(__classPrivateFieldGet(this, _Blob_parts, "f"), true); + return new web_streams_polyfill_1.ReadableStream({ + async pull(controller) { + const { value, done } = await iterator.next(); + if (done) { + return queueMicrotask(() => controller.close()); } - read = read[key]; - write = write[key]; - } - if (last in read && read[last] !== undefined) { - write[last] = write[last] || read[last]; + controller.enqueue(value); + }, + async cancel() { + await iterator.return(); } }); - return { - lc: 1, - type: "constructor", - id: this.lc_id, - kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases), - }; } - toJSONNotImplemented() { - return { - lc: 1, - type: "not_implemented", - id: this.lc_id, - }; + get [Symbol.toStringTag]() { + return "Blob"; } } +exports.Blob = Blob; +Object.defineProperties(Blob.prototype, { + type: { enumerable: true }, + size: { enumerable: true }, + slice: { enumerable: true }, + stream: { enumerable: true }, + text: { enumerable: true }, + arrayBuffer: { enumerable: true } +}); /***/ }), -/***/ 790: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 3637: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "zs": () => (/* binding */ getBufferString) -/* harmony export */ }); -/* unused harmony exports BaseMemory, getInputValue, getOutputValue, getPromptInputKey */ -/** - * Abstract base class for memory in LangChain's Chains. Memory refers to - * the state in Chains. It can be used to store information about past - * executions of a Chain and inject that information into the inputs of - * future executions of the Chain. - */ -class BaseMemory { -} -const getValue = (values, key) => { - if (key !== undefined) { - return values[key]; - } - const keys = Object.keys(values); - if (keys.length === 1) { - return values[keys[0]]; - } -}; -/** - * This function is used by memory classes to select the input value - * to use for the memory. If there is only one input value, it is used. - * If there are multiple input values, the inputKey must be specified. - */ -const getInputValue = (inputValues, inputKey) => { - const value = getValue(inputValues, inputKey); - if (!value) { - const keys = Object.keys(inputValues); - throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); - } - return value; + +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; -/** - * This function is used by memory classes to select the output value - * to use for the memory. If there is only one output value, it is used. - * If there are multiple output values, the outputKey must be specified. - * If no outputKey is specified, an error is thrown. - */ -const getOutputValue = (outputValues, outputKey) => { - const value = getValue(outputValues, outputKey); - if (!value) { - const keys = Object.keys(outputValues); - throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); - } - return value; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; -/** - * This function is used by memory classes to get a string representation - * of the chat message history, based on the message content and role. - */ -function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { - const string_messages = []; - for (const m of messages) { - let role; - if (m._getType() === "human") { - role = humanPrefix; - } - else if (m._getType() === "ai") { - role = aiPrefix; - } - else if (m._getType() === "system") { - role = "System"; - } - else if (m._getType() === "function") { - role = "Function"; - } - else if (m._getType() === "generic") { - role = m.role; +var _File_name, _File_lastModified; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.File = void 0; +const Blob_1 = __nccwpck_require__(6637); +class File extends Blob_1.Blob { + constructor(fileBits, name, options = {}) { + super(fileBits, options); + _File_name.set(this, void 0); + _File_lastModified.set(this, 0); + if (arguments.length < 2) { + throw new TypeError("Failed to construct 'File': 2 arguments required, " + + `but only ${arguments.length} present.`); } - else { - throw new Error(`Got unsupported message type: ${m}`); + __classPrivateFieldSet(this, _File_name, String(name), "f"); + const lastModified = options.lastModified === undefined + ? Date.now() + : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + __classPrivateFieldSet(this, _File_lastModified, lastModified, "f"); } - const nameStr = m.name ? `${m.name}, ` : ""; - string_messages.push(`${role}: ${nameStr}${m.content}`); } - return string_messages.join("\n"); -} -/** - * Function used by memory classes to get the key of the prompt input, - * excluding any keys that are memory variables or the "stop" key. If - * there is not exactly one prompt input key, an error is thrown. - */ -function getPromptInputKey(inputs, memoryVariables) { - const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); - if (promptInputKeys.length !== 1) { - throw new Error(`One input key expected, but got ${promptInputKeys.length}`); + static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) { + return value instanceof Blob_1.Blob + && value[Symbol.toStringTag] === "File" + && typeof value.name === "string"; + } + get name() { + return __classPrivateFieldGet(this, _File_name, "f"); + } + get lastModified() { + return __classPrivateFieldGet(this, _File_lastModified, "f"); + } + get webkitRelativePath() { + return ""; + } + get [Symbol.toStringTag]() { + return "File"; } - return promptInputKeys[0]; } +exports.File = File; /***/ }), -/***/ 5411: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "Al": () => (/* binding */ BaseStringPromptTemplate), -/* harmony export */ "dy": () => (/* binding */ BasePromptTemplate), -/* harmony export */ "nw": () => (/* binding */ StringPromptValue) -/* harmony export */ }); -/* unused harmony export BaseExampleSelector */ -/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(8102); -/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(4432); -/* harmony import */ var _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(1972); -// Default generic "any" values are for backwards compatibility. -// Replace with "string" when we are comfortable with a breaking change. - +/***/ 7268: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/** - * Represents a prompt value as a string. It extends the BasePromptValue - * class and overrides the toString and toChatMessages methods. - */ -class StringPromptValue extends _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BasePromptValue */ .MJ { - constructor(value) { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "prompts", "base"] +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _FormData_instances, _FormData_entries, _FormData_setEntry; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FormData = void 0; +const util_1 = __nccwpck_require__(3837); +const File_1 = __nccwpck_require__(3637); +const isFile_1 = __nccwpck_require__(4529); +const isBlob_1 = __nccwpck_require__(5493); +const isFunction_1 = __nccwpck_require__(4245); +const deprecateConstructorEntries_1 = __nccwpck_require__(2689); +class FormData { + constructor(entries) { + _FormData_instances.add(this); + _FormData_entries.set(this, new Map()); + if (entries) { + (0, deprecateConstructorEntries_1.deprecateConstructorEntries)(); + entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName)); + } + } + static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) { + return Boolean(value + && (0, isFunction_1.isFunction)(value.constructor) + && value[Symbol.toStringTag] === "FormData" + && (0, isFunction_1.isFunction)(value.append) + && (0, isFunction_1.isFunction)(value.set) + && (0, isFunction_1.isFunction)(value.get) + && (0, isFunction_1.isFunction)(value.getAll) + && (0, isFunction_1.isFunction)(value.has) + && (0, isFunction_1.isFunction)(value.delete) + && (0, isFunction_1.isFunction)(value.entries) + && (0, isFunction_1.isFunction)(value.values) + && (0, isFunction_1.isFunction)(value.keys) + && (0, isFunction_1.isFunction)(value[Symbol.iterator]) + && (0, isFunction_1.isFunction)(value.forEach)); + } + append(name, value, fileName) { + __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { + name, + fileName, + append: true, + rawValue: value, + argsLength: arguments.length }); - Object.defineProperty(this, "value", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + set(name, value, fileName) { + __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { + name, + fileName, + append: false, + rawValue: value, + argsLength: arguments.length }); - this.value = value; } - toString() { - return this.value; + get(name) { + const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); + if (!field) { + return null; + } + return field[0]; + } + getAll(name) { + const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); + if (!field) { + return []; + } + return field.slice(); + } + has(name) { + return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name)); + } + delete(name) { + __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name)); + } + *keys() { + for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) { + yield key; + } + } + *entries() { + for (const name of this.keys()) { + const values = this.getAll(name); + for (const value of values) { + yield [name, value]; + } + } + } + *values() { + for (const [, value] of this) { + yield value; + } + } + [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) { + const methodName = append ? "append" : "set"; + if (argsLength < 2) { + throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` + + `2 arguments required, but only ${argsLength} present.`); + } + name = String(name); + let value; + if ((0, isFile_1.isFile)(rawValue)) { + value = fileName === undefined + ? rawValue + : new File_1.File([rawValue], fileName, { + type: rawValue.type, + lastModified: rawValue.lastModified + }); + } + else if ((0, isBlob_1.isBlob)(rawValue)) { + value = new File_1.File([rawValue], fileName === undefined ? "blob" : fileName, { + type: rawValue.type + }); + } + else if (fileName) { + throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` + + "parameter 2 is not of type 'Blob'."); + } + else { + value = String(rawValue); + } + const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name); + if (!values) { + return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); + } + if (!append) { + return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); + } + values.push(value); + }, Symbol.iterator)]() { + return this.entries(); + } + forEach(callback, thisArg) { + for (const [name, value] of this) { + callback.call(thisArg, value, name, this); + } + } + get [Symbol.toStringTag]() { + return "FormData"; } - toChatMessages() { - return [new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .HumanMessage */ .xk(this.value)]; + [util_1.inspect.custom]() { + return this[Symbol.toStringTag]; } } -/** - * Base class for prompt templates. Exposes a format method that returns a - * string prompt given a set of input values. - */ -class BasePromptTemplate extends _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_2__/* .Runnable */ .eq { - get lc_attributes() { - return { - partialVariables: undefined, // python doesn't support this yet - }; +exports.FormData = FormData; + + +/***/ }), + +/***/ 7058: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.sliceBlob = exports.consumeBlobParts = void 0; +const isFunction_1 = __nccwpck_require__(4245); +const CHUNK_SIZE = 65536; +async function* clonePart(part) { + const end = part.byteOffset + part.byteLength; + let position = part.byteOffset; + while (position !== end) { + const size = Math.min(end - position, CHUNK_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); } - constructor(input) { - super(input); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "prompts", this._getPromptType()] - }); - Object.defineProperty(this, "inputVariables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputParser", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "partialVariables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - const { inputVariables } = input; - if (inputVariables.includes("stop")) { - throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); - } - Object.assign(this, input); +} +async function* consumeNodeBlob(blob) { + let position = 0; + while (position !== blob.size) { + const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); } - /** - * Merges partial variables and user variables. - * @param userVariables The user variables to merge with the partial variables. - * @returns A Promise that resolves to an object containing the merged variables. - */ - async mergePartialAndUserVariables(userVariables) { - const partialVariables = this.partialVariables ?? {}; - const partialValues = {}; - for (const [key, value] of Object.entries(partialVariables)) { - if (typeof value === "string") { - partialValues[key] = value; +} +async function* consumeBlobParts(parts, clone = false) { + for (const part of parts) { + if (ArrayBuffer.isView(part)) { + if (clone) { + yield* clonePart(part); } else { - partialValues[key] = await value(); + yield part; } } - const allKwargs = { - ...partialValues, - ...userVariables, - }; - return allKwargs; - } - /** - * Invokes the prompt template with the given input and options. - * @param input The input to invoke the prompt template with. - * @param options Optional configuration for the callback. - * @returns A Promise that resolves to the output of the prompt template. - */ - async invoke(input, options) { - return this._callWithConfig((input) => this.formatPromptValue(input), input, { ...options, runType: "prompt" }); - } - /** - * Return a json-like object representing this prompt template. - * @deprecated - */ - serialize() { - throw new Error("Use .toJSON() instead"); + else if ((0, isFunction_1.isFunction)(part.stream)) { + yield* part.stream(); + } + else { + yield* consumeNodeBlob(part); + } } - /** - * @deprecated - * Load a prompt template from a json-like object describing it. - * - * @remarks - * Deserializing needs to be async because templates (e.g. {@link FewShotPromptTemplate}) can - * reference remote resources that we read asynchronously with a web - * request. - */ - static async deserialize(data) { - switch (data._type) { - case "prompt": { - const { PromptTemplate } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 3379)); - return PromptTemplate.deserialize(data); - } - case undefined: { - const { PromptTemplate } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 3379)); - return PromptTemplate.deserialize({ ...data, _type: "prompt" }); +} +exports.consumeBlobParts = consumeBlobParts; +function* sliceBlob(blobParts, blobSize, start = 0, end) { + end !== null && end !== void 0 ? end : (end = blobSize); + let relativeStart = start < 0 + ? Math.max(blobSize + start, 0) + : Math.min(start, blobSize); + let relativeEnd = end < 0 + ? Math.max(blobSize + end, 0) + : Math.min(end, blobSize); + const span = Math.max(relativeEnd - relativeStart, 0); + let added = 0; + for (const part of blobParts) { + if (added >= span) { + break; + } + const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && partSize <= relativeStart) { + relativeStart -= partSize; + relativeEnd -= partSize; + } + else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd)); + added += chunk.byteLength; } - case "few_shot": { - const { FewShotPromptTemplate } = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 609)); - return FewShotPromptTemplate.deserialize(data); + else { + chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd)); + added += chunk.size; } - default: - throw new Error(`Invalid prompt type in config: ${data._type}`); + relativeEnd -= partSize; + relativeStart = 0; + yield chunk; } } } -/** - * Base class for string prompt templates. It extends the - * BasePromptTemplate class and overrides the formatPromptValue method to - * return a StringPromptValue. - */ -class BaseStringPromptTemplate extends BasePromptTemplate { - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new StringPromptValue(formattedPrompt); - } -} -/** - * Base class for example selectors. - */ -class BaseExampleSelector extends (/* unused pure expression or super */ null && (Serializable)) { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "prompts", "selectors"] - }); - } -} +exports.sliceBlob = sliceBlob; /***/ }), -/***/ 6704: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 2689: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "GU": () => (/* binding */ ChatPromptValue), -/* harmony export */ "gc": () => (/* binding */ AIMessagePromptTemplate), -/* harmony export */ "kq": () => (/* binding */ HumanMessagePromptTemplate), -/* harmony export */ "ks": () => (/* binding */ ChatPromptTemplate), -/* harmony export */ "ov": () => (/* binding */ SystemMessagePromptTemplate) -/* harmony export */ }); -/* unused harmony exports BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate */ -/* harmony import */ var _schema_index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(8102); -/* harmony import */ var _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(1972); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(5411); -/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(3379); -// Default generic "any" values are for backwards compatibility. -// Replace with "string" when we are comfortable with a breaking change. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.deprecateConstructorEntries = void 0; +const util_1 = __nccwpck_require__(3837); +exports.deprecateConstructorEntries = (0, util_1.deprecate)(() => { }, "Constructor \"entries\" argument is not spec-compliant " + + "and will be removed in next major release."); +/***/ }), -/** - * Abstract class that serves as a base for creating message prompt - * templates. It defines how to format messages for different roles in a - * conversation. - */ -class BaseMessagePromptTemplate extends _schema_runnable_index_js__WEBPACK_IMPORTED_MODULE_1__/* .Runnable */ .eq { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "prompts", "chat"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - /** - * Calls the formatMessages method with the provided input and options. - * @param input Input for the formatMessages method - * @param options Optional BaseCallbackConfig - * @returns Formatted output messages - */ - async invoke(input, options) { - return this._callWithConfig((input) => this.formatMessages(input), input, { ...options, runType: "prompt" }); - } -} -/** - * Class that represents a chat prompt value. It extends the - * BasePromptValue and includes an array of BaseMessage instances. - */ -class ChatPromptValue extends _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BasePromptValue */ .MJ { - static lc_name() { - return "ChatPromptValue"; +/***/ 8735: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + 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"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + 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"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _FileFromPath_path, _FileFromPath_start; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fileFromPath = exports.fileFromPathSync = void 0; +const fs_1 = __nccwpck_require__(7147); +const path_1 = __nccwpck_require__(1017); +const node_domexception_1 = __importDefault(__nccwpck_require__(7760)); +const File_1 = __nccwpck_require__(3637); +const isPlainObject_1 = __importDefault(__nccwpck_require__(4722)); +__exportStar(__nccwpck_require__(4529), exports); +const MESSAGE = "The requested file could not be read, " + + "typically due to permission problems that have occurred after a reference " + + "to a file was acquired."; +class FileFromPath { + constructor(input) { + _FileFromPath_path.set(this, void 0); + _FileFromPath_start.set(this, void 0); + __classPrivateFieldSet(this, _FileFromPath_path, input.path, "f"); + __classPrivateFieldSet(this, _FileFromPath_start, input.start || 0, "f"); + this.name = (0, path_1.basename)(__classPrivateFieldGet(this, _FileFromPath_path, "f")); + this.size = input.size; + this.lastModified = input.lastModified; } - constructor(fields) { - if (Array.isArray(fields)) { - // eslint-disable-next-line no-param-reassign - fields = { messages: fields }; - } - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "prompts", "chat"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "messages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + slice(start, end) { + return new FileFromPath({ + path: __classPrivateFieldGet(this, _FileFromPath_path, "f"), + lastModified: this.lastModified, + size: end - start, + start }); - this.messages = fields.messages; - } - toString() { - return JSON.stringify(this.messages); - } - toChatMessages() { - return this.messages; - } -} -/** - * Class that represents a placeholder for messages in a chat prompt. It - * extends the BaseMessagePromptTemplate. - */ -class MessagesPlaceholder extends (/* unused pure expression or super */ null && (BaseMessagePromptTemplate)) { - static lc_name() { - return "MessagesPlaceholder"; } - constructor(fields) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign - fields = { variableName: fields }; + async *stream() { + const { mtimeMs } = await fs_1.promises.stat(__classPrivateFieldGet(this, _FileFromPath_path, "f")); + if (mtimeMs > this.lastModified) { + throw new node_domexception_1.default(MESSAGE, "NotReadableError"); + } + if (this.size) { + yield* (0, fs_1.createReadStream)(__classPrivateFieldGet(this, _FileFromPath_path, "f"), { + start: __classPrivateFieldGet(this, _FileFromPath_start, "f"), + end: __classPrivateFieldGet(this, _FileFromPath_start, "f") + this.size - 1 + }); } - super(fields); - Object.defineProperty(this, "variableName", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.variableName = fields.variableName; - } - get inputVariables() { - return [this.variableName]; } - formatMessages(values) { - return Promise.resolve(values[this.variableName]); + get [(_FileFromPath_path = new WeakMap(), _FileFromPath_start = new WeakMap(), Symbol.toStringTag)]() { + return "File"; } } -/** - * Abstract class that serves as a base for creating message string prompt - * templates. It extends the BaseMessagePromptTemplate. - */ -class BaseMessageStringPromptTemplate extends BaseMessagePromptTemplate { - constructor(fields) { - if (!("prompt" in fields)) { - // eslint-disable-next-line no-param-reassign - fields = { prompt: fields }; - } - super(fields); - Object.defineProperty(this, "prompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.prompt = fields.prompt; +function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) { + let filename; + if ((0, isPlainObject_1.default)(filenameOrOptions)) { + [options, filename] = [filenameOrOptions, undefined]; } - get inputVariables() { - return this.prompt.inputVariables; + else { + filename = filenameOrOptions; } - async formatMessages(values) { - return [await this.format(values)]; + const file = new FileFromPath({ path, size, lastModified: mtimeMs }); + if (!filename) { + filename = file.name; } + return new File_1.File([file], filename, { + ...options, lastModified: file.lastModified + }); } -/** - * Abstract class that serves as a base for creating chat prompt - * templates. It extends the BasePromptTemplate. - */ -class BaseChatPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_2__/* .BasePromptTemplate */ .dy { - constructor(input) { - super(input); - } - async format(values) { - return (await this.formatPromptValue(values)).toString(); +function fileFromPathSync(path, filenameOrOptions, options = {}) { + const stats = (0, fs_1.statSync)(path); + return createFileFromPath(path, stats, filenameOrOptions, options); +} +exports.fileFromPathSync = fileFromPathSync; +async function fileFromPath(path, filenameOrOptions, options) { + const stats = await fs_1.promises.stat(path); + return createFileFromPath(path, stats, filenameOrOptions, options); +} +exports.fileFromPath = fileFromPath; + + +/***/ }), + +/***/ 880: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +__exportStar(__nccwpck_require__(7268), exports); +__exportStar(__nccwpck_require__(6637), exports); +__exportStar(__nccwpck_require__(3637), exports); + + +/***/ }), + +/***/ 5493: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBlob = void 0; +const Blob_1 = __nccwpck_require__(6637); +const isBlob = (value) => value instanceof Blob_1.Blob; +exports.isBlob = isBlob; + + +/***/ }), + +/***/ 4529: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isFile = void 0; +const File_1 = __nccwpck_require__(3637); +const isFile = (value) => value instanceof File_1.File; +exports.isFile = isFile; + + +/***/ }), + +/***/ 4245: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isFunction = void 0; +const isFunction = (value) => (typeof value === "function"); +exports.isFunction = isFunction; + + +/***/ }), + +/***/ 4722: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); +function isPlainObject(value) { + if (getType(value) !== "object") { + return false; } - async formatPromptValue(values) { - const resultMessages = await this.formatMessages(values); - return new ChatPromptValue(resultMessages); + const pp = Object.getPrototypeOf(value); + if (pp === null || pp === undefined) { + return true; } + const Ctor = pp.constructor && pp.constructor.toString(); + return Ctor === Object.toString(); } +exports["default"] = isPlainObject; + + +/***/ }), + +/***/ 4484: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + /** - * Class that represents a chat message prompt template. It extends the - * BaseMessageStringPromptTemplate. + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ -class ChatMessagePromptTemplate extends BaseMessageStringPromptTemplate { - static lc_name() { - return "ChatMessagePromptTemplate"; - } - constructor(fields, role) { - if (!("prompt" in fields)) { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { prompt: fields, role: role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; - } - async format(values) { - return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .ChatMessage */ .J(await this.prompt.format(values), this.role); - } - static fromTemplate(template, role) { - return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template), role); - } +var __importDefault = + (this && this.__importDefault) || + function (mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDefaultAgent = void 0; +const agentkeepalive_1 = __importDefault(__nccwpck_require__(4623)); +const abort_controller_1 = __nccwpck_require__(1659); +const defaultHttpAgent = new agentkeepalive_1.default({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent = new agentkeepalive_1.default.HttpsAgent({ + keepAlive: true, + timeout: 5 * 60 * 1000, +}); +// Polyfill global object if needed. +if (typeof AbortController === 'undefined') { + AbortController = abort_controller_1.AbortController; } +const getDefaultAgent = (url) => { + if (defaultHttpsAgent && url.startsWith('https')) return defaultHttpsAgent; + return defaultHttpAgent; +}; +exports.getDefaultAgent = getDefaultAgent; +//# sourceMappingURL=agent.node.js.map + + +/***/ }), + +/***/ 4899: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ + +const nf = __nccwpck_require__(467); + +exports.fetch = nf.default; +exports.Request = nf.Request; +exports.Response = nf.Response; +exports.Headers = nf.Headers; + +exports.isPolyfilled = true; + + +/***/ }), + +/***/ 8244: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + /** - * Class that represents a human message prompt template. It extends the - * BaseMessageStringPromptTemplate. + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ -class HumanMessagePromptTemplate extends BaseMessageStringPromptTemplate { - static lc_name() { - return "HumanMessagePromptTemplate"; - } - async format(values) { - return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .HumanMessage */ .xk(await this.prompt.format(values)); - } - static fromTemplate(template) { - return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template)); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fileFromPath = void 0; +const file_from_path_1 = __nccwpck_require__(8735); +let warned = false; +async function fileFromPath(path, ...args) { + if (!warned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + warned = true; + } + return await (0, file_from_path_1.fileFromPath)(path, ...args); } +exports.fileFromPath = fileFromPath; +//# sourceMappingURL=fileFromPath.node.js.map + + +/***/ }), + +/***/ 7744: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /** - * Class that represents an AI message prompt template. It extends the - * BaseMessageStringPromptTemplate. + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ -class AIMessagePromptTemplate extends BaseMessageStringPromptTemplate { - static lc_name() { - return "AIMessagePromptTemplate"; - } - async format(values) { - return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .AIMessage */ .gY(await this.prompt.format(values)); - } - static fromTemplate(template) { - return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template)); - } -} + +const fd = __nccwpck_require__(880); + +exports.FormData = fd.FormData; +exports.File = fd.File; +exports.Blob = fd.Blob; + +exports.isPolyfilled = true; + + +/***/ }), + +/***/ 8462: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + /** - * Class that represents a system message prompt template. It extends the - * BaseMessageStringPromptTemplate. + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ -class SystemMessagePromptTemplate extends BaseMessageStringPromptTemplate { - static lc_name() { - return "SystemMessagePromptTemplate"; - } - async format(values) { - return new _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .SystemMessage */ .jN(await this.prompt.format(values)); - } - static fromTemplate(template) { - return new this(_prompt_js__WEBPACK_IMPORTED_MODULE_3__.PromptTemplate.fromTemplate(template)); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getMultipartRequestOptions = void 0; +const node_stream_1 = __nccwpck_require__(4492); +const form_data_encoder_1 = __nccwpck_require__(8824); +const uploads_1 = __nccwpck_require__(6800); +async function getMultipartRequestOptions(form, opts) { + const encoder = new form_data_encoder_1.FormDataEncoder(form); + const readable = node_stream_1.Readable.from(encoder); + const body = new uploads_1.MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + return { ...opts, body: body, headers }; } -function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { - return (typeof baseMessagePromptTemplateLike - .formatMessages === "function"); +exports.getMultipartRequestOptions = getMultipartRequestOptions; +//# sourceMappingURL=getMultipartRequestOptions.node.js.map + + +/***/ }), + +/***/ 9104: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isFsReadStream = void 0; +const node_fs_1 = __nccwpck_require__(7561); +function isFsReadStream(value) { + return value instanceof node_fs_1.ReadStream; } -function _coerceMessagePromptTemplateLike(messagePromptTemplateLike) { - if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || - (0,_schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .isBaseMessage */ .QW)(messagePromptTemplateLike)) { - return messagePromptTemplateLike; - } - const message = (0,_schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .coerceMessageLikeToMessage */ .E1)(messagePromptTemplateLike); - if (message._getType() === "human") { - return HumanMessagePromptTemplate.fromTemplate(message.content); - } - else if (message._getType() === "ai") { - return AIMessagePromptTemplate.fromTemplate(message.content); - } - else if (message._getType() === "system") { - return SystemMessagePromptTemplate.fromTemplate(message.content); - } - else if (_schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .ChatMessage.isInstance */ .J.isInstance(message)) { - return ChatMessagePromptTemplate.fromTemplate(message.content, message.role); - } - else { - throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); - } +exports.isFsReadStream = isFsReadStream; +//# sourceMappingURL=node-readable.node.js.map + + +/***/ }), + +/***/ 1798: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __classPrivateFieldSet = + (this && this.__classPrivateFieldSet) || + function (receiver, state, value, kind, f) { + if (kind === 'm') throw new TypeError('Private method is not writable'); + if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a setter'); + 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'); + return ( + kind === 'a' ? f.call(receiver, value) + : f ? (f.value = value) + : state.set(receiver, value), + value + ); + }; +var __classPrivateFieldGet = + (this && this.__classPrivateFieldGet) || + function (receiver, state, kind, f) { + if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter'); + 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'); + return ( + kind === 'm' ? f + : kind === 'a' ? f.call(receiver) + : f ? f.value + : state.get(receiver) + ); + }; +var _AbstractPage_client; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toBase64 = + exports.getHeader = + exports.isHeadersProtocol = + exports.isRunningInBrowser = + exports.debug = + exports.hasOwn = + exports.isEmptyObj = + exports.maybeCoerceBoolean = + exports.maybeCoerceFloat = + exports.maybeCoerceInteger = + exports.coerceBoolean = + exports.coerceFloat = + exports.coerceInteger = + exports.readEnv = + exports.ensurePresent = + exports.castToError = + exports.safeJSON = + exports.isRequestOptions = + exports.createResponseHeaders = + exports.PagePromise = + exports.AbstractPage = + exports.APIResource = + exports.APIClient = + exports.APIPromise = + exports.createForm = + exports.multipartFormRequestOptions = + exports.maybeMultipartFormRequestOptions = + void 0; +const version_1 = __nccwpck_require__(6417); +const streaming_1 = __nccwpck_require__(884); +const error_1 = __nccwpck_require__(8905); +const agent_1 = __nccwpck_require__(4484); +const fetch_1 = __nccwpck_require__(4899); +const uploads_1 = __nccwpck_require__(6800); +var uploads_2 = __nccwpck_require__(6800); +Object.defineProperty(exports, "maybeMultipartFormRequestOptions", ({ + enumerable: true, + get: function () { + return uploads_2.maybeMultipartFormRequestOptions; + }, +})); +Object.defineProperty(exports, "multipartFormRequestOptions", ({ + enumerable: true, + get: function () { + return uploads_2.multipartFormRequestOptions; + }, +})); +Object.defineProperty(exports, "createForm", ({ + enumerable: true, + get: function () { + return uploads_2.createForm; + }, +})); +const MAX_RETRIES = 2; +async function defaultParseResponse(props) { + const { response } = props; + if (props.options.stream) { + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + return new streaming_1.Stream(response, props.controller); + } + const contentType = response.headers.get('content-type'); + if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { + const json = await response.json(); + debug('response', response.status, response.url, response.headers, json); + return json; + } + // TODO handle blob, arraybuffer, other content types, etc. + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + return text; } /** - * Class that represents a chat prompt. It extends the - * BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate - * instances to format a series of messages for a conversation. + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. */ -class ChatPromptTemplate extends BaseChatPromptTemplate { - static lc_name() { - return "ChatPromptTemplate"; +class APIPromise extends Promise { + constructor(responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + } + _thenUnwrap(transform) { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); } - get lc_aliases() { - return { - promptMessages: "messages", - }; + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +exports.APIPromise = APIPromise; +class APIClient { + constructor({ + baseURL, + maxRetries, + timeout = 600000, // 10 minutes + httpAgent, + fetch: overridenFetch, + }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger( + 'maxRetries', + maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES, + ); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : fetch_1.fetch; + } + authHeaders(opts) { + return {}; + } + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + defaultHeaders(opts) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + /** + * Override this to add your own headers validation: + */ + validateHeaders(headers, customHeaders) {} + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + calculateContentLength(body) { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } } - constructor(input) { - super(input); - Object.defineProperty(this, "promptMessages", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.assign(this, input); - if (this.validateTemplate) { - const inputVariablesMessages = new Set(); - for (const promptMessage of this.promptMessages) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (promptMessage instanceof _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseMessage */ .ku) - continue; - for (const inputVariable of promptMessage.inputVariables) { - inputVariablesMessages.add(inputVariable); - } - } - const totalInputVariables = this.inputVariables; - const inputVariablesInstance = new Set(this.partialVariables - ? totalInputVariables.concat(Object.keys(this.partialVariables)) - : totalInputVariables); - const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); - if (difference.size > 0) { - throw new Error(`Input variables \`${[ - ...difference, - ]}\` are not used in any of the prompt messages.`); - } - const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); - if (otherDifference.size > 0) { - throw new Error(`Input variables \`${[ - ...otherDifference, - ]}\` are used in prompt messages but not in the prompt template.`); - } - } + return null; + } + buildRequest(options) { + var _a, _b, _c, _d, _e, _f; + const { method, path, query, headers: headers = {} } = options; + const body = + (0, uploads_1.isMultipartBody)(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + const url = this.buildURL(path, query); + if ('timeout' in options) validatePositiveInteger('timeout', options.timeout); + const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout; + const httpAgent = + ( + (_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null && + _c !== void 0 + ) ? + _c + : (0, agent_1.getDefaultAgent)(url); + const minAgentTimeout = timeout + 1000; + if ( + typeof (( + (_d = httpAgent === null || httpAgent === void 0 ? void 0 : httpAgent.options) === null || + _d === void 0 + ) ? + void 0 + : _d.timeout) === 'number' && + minAgentTimeout > ((_e = httpAgent.options.timeout) !== null && _e !== void 0 ? _e : 0) + ) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + httpAgent.options.timeout = minAgentTimeout; } - _getPromptType() { - return "chat"; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; } - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let resultMessages = []; - for (const promptMessage of this.promptMessages) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (promptMessage instanceof _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseMessage */ .ku) { - resultMessages.push(promptMessage); - } - else { - const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { - if (!(inputVariable in allValues)) { - throw new Error(`Missing value for input variable \`${inputVariable.toString()}\``); - } - acc[inputVariable] = allValues[inputVariable]; - return acc; - }, {}); - const message = await promptMessage.formatMessages(inputValues); - resultMessages = resultMessages.concat(message); - } - } - return resultMessages; + const reqHeaders = { + ...(contentLength && { 'Content-Length': contentLength }), + ...this.defaultHeaders(options), + ...headers, + }; + // let builtin fetch set the Content-Type for multipart bodies + if ((0, uploads_1.isMultipartBody)(options.body) && !fetch_1.isPolyfilled) { + delete reqHeaders['Content-Type']; } - async partial(values) { - // This is implemented in a way it doesn't require making - // BaseMessagePromptTemplate aware of .partial() - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...(this.partialVariables ?? {}), - ...values, - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables, - }; - return new ChatPromptTemplate(promptDict); + // Strip any headers being explicitly omitted with null + Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]); + const req = { + method, + ...(body && { body: body }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: (_f = options.signal) !== null && _f !== void 0 ? _f : null, + }; + this.validateHeaders(reqHeaders, headers); + return { req, url, timeout }; + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) {} + parseHeaders(headers) { + return ( + !headers ? {} + : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) + : { ...headers } + ); + } + makeStatusError(status, error, message, headers) { + return error_1.APIError.generate(status, error, message, headers); + } + request(options, remainingRetries = null) { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + async makeRequest(optionsInput, retriesRemaining) { + var _a, _b, _c; + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries; } - /** - * Create a chat model-specific prompt from individual chat messages - * or message-like tuples. - * @param promptMessages Messages to be passed to the chat model - * @returns A new ChatPromptTemplate - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static fromMessages(promptMessages) { - const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat( - // eslint-disable-next-line no-instanceof/no-instanceof - promptMessage instanceof ChatPromptTemplate - ? promptMessage.promptMessages - : [_coerceMessagePromptTemplateLike(promptMessage)]), []); - const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => - // eslint-disable-next-line no-instanceof/no-instanceof - promptMessage instanceof ChatPromptTemplate - ? Object.assign(acc, promptMessage.partialVariables) - : acc, Object.create(null)); - const inputVariables = new Set(); - for (const promptMessage of flattenedMessages) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (promptMessage instanceof _schema_index_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseMessage */ .ku) - continue; - for (const inputVariable of promptMessage.inputVariables) { - if (inputVariable in flattenedPartialVariables) { - continue; - } - inputVariables.add(inputVariable); - } - } - return new ChatPromptTemplate({ - inputVariables: [...inputVariables], - promptMessages: flattenedMessages, - partialVariables: flattenedPartialVariables, - }); + const { req, url, timeout } = this.buildRequest(options); + await this.prepareRequest(req, { url, options }); + debug('request', url, options, req.headers); + if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) { + throw new error_1.APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError); + if (response instanceof Error) { + if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) { + throw new error_1.APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new error_1.APIConnectionTimeoutError(); + } + throw new error_1.APIConnectionError({ cause: response }); + } + const responseHeaders = (0, exports.createResponseHeaders)(response.headers); + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + const errText = await response.text().catch(() => 'Unknown'); + const errJSON = (0, exports.safeJSON)(errText); + const errMessage = errJSON ? undefined : errText; + debug('response', response.status, url, responseHeaders, errMessage); + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; } - /** @deprecated Renamed to .fromMessages */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static fromPromptMessages(promptMessages) { - return this.fromMessages(promptMessages); + return { response, options, controller }; + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + buildURL(path, query) { + const url = + isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; } -} - - -/***/ }), - -/***/ 609: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -__nccwpck_require__.r(__webpack_exports__); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "FewShotPromptTemplate": () => (/* binding */ FewShotPromptTemplate) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(5411); -/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(837); -/* harmony import */ var _prompt_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(3379); - - - -/** - * Prompt template that contains few-shot examples. - * @augments BasePromptTemplate - * @augments FewShotPromptTemplateInput - */ -class FewShotPromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { - constructor(input) { - super(input); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "examples", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "exampleSelector", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "examplePrompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "suffix", { - enumerable: true, - configurable: true, - writable: true, - value: "" - }); - Object.defineProperty(this, "exampleSeparator", { - enumerable: true, - configurable: true, - writable: true, - value: "\n\n" - }); - Object.defineProperty(this, "prefix", { - enumerable: true, - configurable: true, - writable: true, - value: "" - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.assign(this, input); - if (this.examples !== undefined && this.exampleSelector !== undefined) { - throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - } - if (this.examples === undefined && this.exampleSelector === undefined) { - throw new Error("One of 'examples' and 'example_selector' should be provided"); + if (query) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; } - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) { - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - } - (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + if (value === null) { + return `${encodeURIComponent(key)}=`; } + throw new Error( + `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`, + ); + }) + .join('&'); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, ...options } = init || {}; + if (signal) signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + return this.getRequestClient() + .fetch(url, { signal: controller.signal, ...options }) + .finally(() => { + clearTimeout(timeout); + }); + } + getRequestClient() { + return { fetch: this.fetch }; + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') return true; + if (shouldRetryHeader === 'false') return false; + // Retry on lock timeouts. + if (response.status === 409) return true; + // Retry on rate limits. + if (response.status === 429) return true; + // Retry internal errors. + if (response.status >= 500) return true; + return false; + } + async retryRequest(options, retriesRemaining, responseHeaders) { + var _a; + retriesRemaining -= 1; + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + // + // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: ". + // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details. + const retryAfter = parseInt( + (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) || + '', + ); + const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries; + const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000; + await sleep(timeout); + return this.makeRequest(options, retriesRemaining); + } + calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 2; + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says. + if (Number.isInteger(retryAfter) && retryAfter <= 60) { + return retryAfter; } - _getPromptType() { - return "few_shot"; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay); + // Apply some jitter, plus-or-minus half a second. + const jitter = Math.random() - 0.5; + return sleepSeconds + jitter; + } + getUserAgent() { + return `${this.constructor.name}/JS ${version_1.VERSION}`; + } +} +exports.APIClient = APIClient; +class APIResource { + constructor(client) { + this.client = client; + this.get = client.get.bind(client); + this.post = client.post.bind(client); + this.patch = client.patch.bind(client); + this.put = client.put.bind(client); + this.delete = client.delete.bind(client); + this.getAPIList = client.getAPIList.bind(client); + } +} +exports.APIResource = APIResource; +class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, 'f'); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) return false; + return this.nextPageInfo() != null; + } + async getNextPage() { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new Error( + 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.', + ); } - async getExamples(inputVariables) { - if (this.examples !== undefined) { - return this.examples; - } - if (this.exampleSelector !== undefined) { - return this.exampleSelector.selectExamples(inputVariables); - } - throw new Error("One of 'examples' and 'example_selector' should be provided"); + const nextOptions = { ...this.options }; + if ('params' in nextInfo) { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...(this.partialVariables ?? {}), - ...values, - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables, - }; - return new FewShotPromptTemplate(promptDict); + return await __classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList( + this.constructor, + nextOptions, + ); + } + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); - const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); - return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(template, this.templateFormat, allValues); + } + async *[((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } } - serialize() { - if (this.exampleSelector || !this.examples) { - throw new Error("Serializing an example selector is not currently supported"); - } - if (this.outputParser !== undefined) { - throw new Error("Serializing an output parser is not currently supported"); - } - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - example_prompt: this.examplePrompt.serialize(), - example_separator: this.exampleSeparator, - suffix: this.suffix, - prefix: this.prefix, - template_format: this.templateFormat, - examples: this.examples, - }; + } +} +exports.AbstractPage = AbstractPage; +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class PagePromise extends APIPromise { + constructor(client, request, Page) { + super( + request, + async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options), + ); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; } - static async deserialize(data) { - const { example_prompt } = data; - if (!example_prompt) { - throw new Error("Missing example prompt"); - } - const examplePrompt = await _prompt_js__WEBPACK_IMPORTED_MODULE_2__.PromptTemplate.deserialize(example_prompt); - let examples; - if (Array.isArray(data.examples)) { - examples = data.examples; - } - else { - throw new Error("Invalid examples format. Only list or string are supported."); - } - return new FewShotPromptTemplate({ - inputVariables: data.input_variables, - examplePrompt, - examples, - exampleSeparator: data.example_separator, - prefix: data.prefix, - suffix: data.suffix, - templateFormat: data.template_format, - }); + } +} +exports.PagePromise = PagePromise; +const createResponseHeaders = (headers) => { + return new Proxy( + Object.fromEntries( + // @ts-ignore + headers.entries(), + ), + { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }, + ); +}; +exports.createResponseHeaders = createResponseHeaders; +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys = { + method: true, + path: true, + query: true, + body: true, + headers: true, + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, +}; +const isRequestOptions = (obj) => { + return ( + typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)) + ); +}; +exports.isRequestOptions = isRequestOptions; +const getPlatformProperties = () => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': Deno.version, + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') return 'x32'; + if (arch === 'x86_64' || arch === 'x64') return 'x64'; + if (arch === 'arm') return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') return 'arm64'; + if (arch) return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) return 'iOS'; + if (platform === 'android') return 'Android'; + if (platform === 'darwin') return 'MacOS'; + if (platform === 'win32') return 'Windows'; + if (platform === 'freebsd') return 'FreeBSD'; + if (platform === 'openbsd') return 'OpenBSD'; + if (platform === 'linux') return 'Linux'; + if (platform) return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return _platformHeaders !== null && _platformHeaders !== void 0 ? + _platformHeaders + : (_platformHeaders = getPlatformProperties()); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return undefined; + } +}; +exports.safeJSON = safeJSON; +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new Error(`${name} must be an integer`); + } + if (n < 0) { + throw new Error(`${name} must be a positive integer`); + } + return n; +}; +const castToError = (err) => { + if (err instanceof Error) return err; + return new Error(err); +}; +exports.castToError = castToError; +const ensurePresent = (value) => { + if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`); + return value; +}; +exports.ensurePresent = ensurePresent; +/** + * Read an environment variable. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + var _a, _b, _c, _d; + if (typeof process !== 'undefined') { + return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ? + _b + : undefined; + } + if (typeof Deno !== 'undefined') { + return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ? + void 0 + : _d.call(_c, env); + } + return undefined; +}; +exports.readEnv = readEnv; +const coerceInteger = (value) => { + if (typeof value === 'number') return Math.round(value); + if (typeof value === 'string') return parseInt(value, 10); + throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +exports.coerceInteger = coerceInteger; +const coerceFloat = (value) => { + if (typeof value === 'number') return value; + if (typeof value === 'string') return parseFloat(value); + throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +exports.coerceFloat = coerceFloat; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') return value; + if (typeof value === 'string') return value === 'true'; + return Boolean(value); +}; +exports.coerceBoolean = coerceBoolean; +const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceInteger)(value); +}; +exports.maybeCoerceInteger = maybeCoerceInteger; +const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceFloat)(value); +}; +exports.maybeCoerceFloat = maybeCoerceFloat; +const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceBoolean)(value); +}; +exports.maybeCoerceBoolean = maybeCoerceBoolean; +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) return true; + for (const _k in obj) return false; + return true; +} +exports.isEmptyObj = isEmptyObj; +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +exports.hasOwn = hasOwn; +function debug(action, ...args) { + if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } } +exports.debug = debug; +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined' + ); +}; +exports.isRunningInBrowser = isRunningInBrowser; +const isHeadersProtocol = (headers) => { + return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function'; +}; +exports.isHeadersProtocol = isHeadersProtocol; +const getHeader = (headers, key) => { + const lowerKey = key.toLowerCase(); + if ((0, exports.isHeadersProtocol)(headers)) return headers.get(key) || headers.get(lowerKey); + const value = headers[key] || headers[lowerKey]; + if (Array.isArray(value)) { + if (value.length <= 1) return value[0]; + console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`); + return value[0]; + } + return value; +}; +exports.getHeader = getHeader; +/** + * Encodes a string to Base64 format. + */ +const toBase64 = (str) => { + if (!str) return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + if (typeof btoa !== 'undefined') { + return btoa(str); + } + throw new Error('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; +exports.toBase64 = toBase64; +//# sourceMappingURL=core.js.map /***/ }), -/***/ 4910: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "gc": () => (/* reexport */ chat/* AIMessagePromptTemplate */.gc), - "ks": () => (/* reexport */ chat/* ChatPromptTemplate */.ks), - "kq": () => (/* reexport */ chat/* HumanMessagePromptTemplate */.kq), - "Pf": () => (/* reexport */ prompts_prompt.PromptTemplate), - "ov": () => (/* reexport */ chat/* SystemMessagePromptTemplate */.ov) -}); - -// UNUSED EXPORTS: BaseChatPromptTemplate, BaseExampleSelector, BasePromptSelector, BasePromptTemplate, BaseStringPromptTemplate, ChatMessagePromptTemplate, ConditionalPromptSelector, FewShotPromptTemplate, LengthBasedExampleSelector, MessagesPlaceholder, PipelinePromptTemplate, SemanticSimilarityExampleSelector, StringPromptValue, checkValidTemplate, isChatModel, isLLM, parseTemplate, renderTemplate +/***/ 8905: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/base.js -var base = __nccwpck_require__(5411); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js -var prompts_prompt = __nccwpck_require__(3379); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/LengthBasedExampleSelector.js -/** - * Calculates the length of a text based on the number of words and lines. - */ -function getLengthBased(text) { - return text.split(/\n| /).length; -} -/** - * A specialized example selector that selects examples based on their - * length, ensuring that the total length of the selected examples does - * not exceed a specified maximum length. - */ -class LengthBasedExampleSelector extends (/* unused pure expression or super */ null && (BaseExampleSelector)) { - constructor(data) { - super(data); - Object.defineProperty(this, "examples", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "examplePrompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "getTextLength", { - enumerable: true, - configurable: true, - writable: true, - value: getLengthBased - }); - Object.defineProperty(this, "maxLength", { - enumerable: true, - configurable: true, - writable: true, - value: 2048 - }); - Object.defineProperty(this, "exampleTextLengths", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - this.examplePrompt = data.examplePrompt; - this.maxLength = data.maxLength ?? 2048; - this.getTextLength = data.getTextLength ?? getLengthBased; +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InternalServerError = + exports.RateLimitError = + exports.UnprocessableEntityError = + exports.ConflictError = + exports.NotFoundError = + exports.PermissionDeniedError = + exports.AuthenticationError = + exports.BadRequestError = + exports.APIConnectionTimeoutError = + exports.APIConnectionError = + exports.APIUserAbortError = + exports.APIError = + void 0; +const core_1 = __nccwpck_require__(1798); +class APIError extends Error { + constructor(status, error, message, headers) { + super(APIError.makeMessage(error, message)); + this.status = status; + this.headers = headers; + const data = error; + this.error = data; + this.code = data === null || data === void 0 ? void 0 : data['code']; + this.param = data === null || data === void 0 ? void 0 : data['param']; + this.type = data === null || data === void 0 ? void 0 : data['type']; + } + static makeMessage(error, message) { + return ( + ( + error === null || error === void 0 ? void 0 : error.message + ) ? + typeof error.message === 'string' ? error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message || 'Unknown error occurred' + ); + } + static generate(status, errorResponse, message, headers) { + if (!status) { + return new APIConnectionError({ cause: (0, core_1.castToError)(errorResponse) }); } - /** - * Adds an example to the list of examples and calculates its length. - * @param example The example to be added. - * @returns Promise that resolves when the example has been added and its length calculated. - */ - async addExample(example) { - this.examples.push(example); - const stringExample = await this.examplePrompt.format(example); - this.exampleTextLengths.push(this.getTextLength(stringExample)); + const error = errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); } - /** - * Calculates the lengths of the examples. - * @param v Array of lengths of the examples. - * @param values Instance of LengthBasedExampleSelector. - * @returns Promise that resolves with an array of lengths of the examples. - */ - async calculateExampleTextLengths(v, values) { - if (v.length > 0) { - return v; - } - const { examples, examplePrompt } = values; - const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); - return stringExamples.map((eg) => this.getTextLength(eg)); + if (status === 401) { + return new AuthenticationError(status, error, message, headers); } - /** - * Selects examples until the total length of the selected examples - * reaches the maxLength. - * @param inputVariables The input variables for the examples. - * @returns Promise that resolves with an array of selected examples. - */ - async selectExamples(inputVariables) { - const inputs = Object.values(inputVariables).join(" "); - let remainingLength = this.maxLength - this.getTextLength(inputs); - let i = 0; - const examples = []; - while (remainingLength > 0 && i < this.examples.length) { - const newLength = remainingLength - this.exampleTextLengths[i]; - if (newLength < 0) { - break; - } - else { - examples.push(this.examples[i]); - remainingLength = newLength; - } - i += 1; - } - return examples; + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); } - /** - * Creates a new instance of LengthBasedExampleSelector and adds a list of - * examples to it. - * @param examples Array of examples to be added. - * @param args Input parameters for the LengthBasedExampleSelector. - * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. - */ - static async fromExamples(examples, args) { - const selector = new LengthBasedExampleSelector(args); - await Promise.all(examples.map((eg) => selector.addExample(eg))); - return selector; + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); } + return new APIError(status, error, message, headers); + } +} +exports.APIError = APIError; +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + this.status = undefined; + } +} +exports.APIUserAbortError = APIUserAbortError; +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + this.status = undefined; + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) this.cause = cause; + } +} +exports.APIConnectionError = APIConnectionError; +class APIConnectionTimeoutError extends APIConnectionError { + constructor() { + super({ message: 'Request timed out.' }); + } +} +exports.APIConnectionTimeoutError = APIConnectionTimeoutError; +class BadRequestError extends APIError { + constructor() { + super(...arguments); + this.status = 400; + } +} +exports.BadRequestError = BadRequestError; +class AuthenticationError extends APIError { + constructor() { + super(...arguments); + this.status = 401; + } +} +exports.AuthenticationError = AuthenticationError; +class PermissionDeniedError extends APIError { + constructor() { + super(...arguments); + this.status = 403; + } +} +exports.PermissionDeniedError = PermissionDeniedError; +class NotFoundError extends APIError { + constructor() { + super(...arguments); + this.status = 404; + } +} +exports.NotFoundError = NotFoundError; +class ConflictError extends APIError { + constructor() { + super(...arguments); + this.status = 409; + } +} +exports.ConflictError = ConflictError; +class UnprocessableEntityError extends APIError { + constructor() { + super(...arguments); + this.status = 422; + } +} +exports.UnprocessableEntityError = UnprocessableEntityError; +class RateLimitError extends APIError { + constructor() { + super(...arguments); + this.status = 429; + } } +exports.RateLimitError = RateLimitError; +class InternalServerError extends APIError {} +exports.InternalServerError = InternalServerError; +//# sourceMappingURL=error.js.map -;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/selectors/SemanticSimilarityExampleSelector.js +/***/ }), -function sortedValues(values) { - return Object.keys(values) - .sort() - .map((key) => values[key]); -} -/** - * Class that selects examples based on semantic similarity. It extends - * the BaseExampleSelector class. - */ -class SemanticSimilarityExampleSelector extends (/* unused pure expression or super */ null && (BaseExampleSelector)) { - constructor(data) { - super(data); - Object.defineProperty(this, "vectorStore", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "k", { - enumerable: true, - configurable: true, - writable: true, - value: 4 - }); - Object.defineProperty(this, "exampleKeys", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputKeys", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.vectorStore = data.vectorStore; - this.k = data.k ?? 4; - this.exampleKeys = data.exampleKeys; - this.inputKeys = data.inputKeys; - } - /** - * Method that adds a new example to the vectorStore. The example is - * converted to a string and added to the vectorStore as a document. - * @param example The example to be added to the vectorStore. - * @returns Promise that resolves when the example has been added to the vectorStore. - */ - async addExample(example) { - const inputKeys = this.inputKeys ?? Object.keys(example); - const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})).join(" "); - await this.vectorStore.addDocuments([ - new Document({ - pageContent: stringExample, - metadata: { example }, - }), - ]); +/***/ 47: +/***/ (function(module, exports, __nccwpck_require__) { + + +// File generated from our OpenAPI spec by Stainless. +var __createBinding = + (this && this.__createBinding) || + (Object.create ? + function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); } - /** - * Method that selects which examples to use based on semantic similarity. - * It performs a similarity search in the vectorStore using the input - * variables and returns the examples with the highest similarity. - * @param inputVariables The input variables used for the similarity search. - * @returns Promise that resolves with an array of the selected examples. - */ - async selectExamples(inputVariables) { - const inputKeys = this.inputKeys ?? Object.keys(inputVariables); - const query = sortedValues(inputKeys.reduce((acc, key) => ({ ...acc, [key]: inputVariables[key] }), {})).join(" "); - const exampleDocs = await this.vectorStore.similaritySearch(query, this.k); - const examples = exampleDocs.map((doc) => doc.metadata); - if (this.exampleKeys) { - // If example keys are provided, filter examples to those keys. - return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {})); - } - return examples; + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create ? + function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fileFromPath = + exports.toFile = + exports.UnprocessableEntityError = + exports.PermissionDeniedError = + exports.InternalServerError = + exports.AuthenticationError = + exports.BadRequestError = + exports.RateLimitError = + exports.ConflictError = + exports.NotFoundError = + exports.APIUserAbortError = + exports.APIConnectionTimeoutError = + exports.APIConnectionError = + exports.APIError = + exports.OpenAI = + void 0; +const Core = __importStar(__nccwpck_require__(1798)); +const Pagination = __importStar(__nccwpck_require__(7401)); +const API = __importStar(__nccwpck_require__(5690)); +const Errors = __importStar(__nccwpck_require__(8905)); +const Uploads = __importStar(__nccwpck_require__(6800)); +/** API Client for interfacing with the OpenAI API. */ +class OpenAI extends Core.APIClient { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string} [opts.apiKey=process.env['OPENAI_API_KEY']] - The API Key to send to the API. + * @param {string} [opts.baseURL] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * @param {string | null} [opts.organization] + */ + constructor(_b) { + var _c, _d; + var { + apiKey = Core.readEnv('OPENAI_API_KEY'), + organization = (_c = Core.readEnv('OPENAI_ORG_ID')) !== null && _c !== void 0 ? _c : null, + ...opts + } = _b === void 0 ? {} : _b; + if (apiKey === undefined) { + throw new Error( + "The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'my apiKey' }).", + ); } - /** - * Static method that creates a new instance of - * SemanticSimilarityExampleSelector. It takes a list of examples, an - * instance of Embeddings, a VectorStore class, and an options object as - * parameters. It converts the examples to strings, creates a VectorStore - * from the strings and the embeddings, and returns a new - * SemanticSimilarityExampleSelector with the created VectorStore and the - * options provided. - * @param examples The list of examples to be used. - * @param embeddings The instance of Embeddings to be used. - * @param vectorStoreCls The VectorStore class to be used. - * @param options The options object for the SemanticSimilarityExampleSelector. - * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. - */ - static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { - const inputKeys = options.inputKeys ?? null; - const stringExamples = examples.map((example) => sortedValues(inputKeys - ? inputKeys.reduce((acc, key) => ({ ...acc, [key]: example[key] }), {}) - : example).join(" ")); - const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, // metadatas - embeddings, options); - return new SemanticSimilarityExampleSelector({ - vectorStore, - k: options.k ?? 4, - exampleKeys: options.exampleKeys, - inputKeys: options.inputKeys, - }); + const options = { + apiKey, + organization, + baseURL: `https://api.openai.com/v1`, + ...opts, + }; + if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { + throw new Error( + "It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n", + ); } + super({ + baseURL: options.baseURL, + timeout: (_d = options.timeout) !== null && _d !== void 0 ? _d : 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this.completions = new API.Completions(this); + this.chat = new API.Chat(this); + this.edits = new API.Edits(this); + this.embeddings = new API.Embeddings(this); + this.files = new API.Files(this); + this.images = new API.Images(this); + this.audio = new API.Audio(this); + this.moderations = new API.Moderations(this); + this.models = new API.Models(this); + this.fineTuning = new API.FineTuning(this); + this.fineTunes = new API.FineTunes(this); + this._options = options; + this.apiKey = apiKey; + this.organization = organization; + } + defaultQuery() { + return this._options.defaultQuery; + } + defaultHeaders(opts) { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + authHeaders(opts) { + return { Authorization: `Bearer ${this.apiKey}` }; + } } +exports.OpenAI = OpenAI; +_a = OpenAI; +OpenAI.OpenAI = _a; +OpenAI.APIError = Errors.APIError; +OpenAI.APIConnectionError = Errors.APIConnectionError; +OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; +OpenAI.APIUserAbortError = Errors.APIUserAbortError; +OpenAI.NotFoundError = Errors.NotFoundError; +OpenAI.ConflictError = Errors.ConflictError; +OpenAI.RateLimitError = Errors.RateLimitError; +OpenAI.BadRequestError = Errors.BadRequestError; +OpenAI.AuthenticationError = Errors.AuthenticationError; +OpenAI.InternalServerError = Errors.InternalServerError; +OpenAI.PermissionDeniedError = Errors.PermissionDeniedError; +OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError; +(exports.APIError = Errors.APIError), + (exports.APIConnectionError = Errors.APIConnectionError), + (exports.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError), + (exports.APIUserAbortError = Errors.APIUserAbortError), + (exports.NotFoundError = Errors.NotFoundError), + (exports.ConflictError = Errors.ConflictError), + (exports.RateLimitError = Errors.RateLimitError), + (exports.BadRequestError = Errors.BadRequestError), + (exports.AuthenticationError = Errors.AuthenticationError), + (exports.InternalServerError = Errors.InternalServerError), + (exports.PermissionDeniedError = Errors.PermissionDeniedError), + (exports.UnprocessableEntityError = Errors.UnprocessableEntityError); +exports.toFile = Uploads.toFile; +exports.fileFromPath = Uploads.fileFromPath; +(function (OpenAI) { + // Helper functions + OpenAI.toFile = Uploads.toFile; + OpenAI.fileFromPath = Uploads.fileFromPath; + OpenAI.Page = Pagination.Page; + OpenAI.CursorPage = Pagination.CursorPage; + OpenAI.Completions = API.Completions; + OpenAI.Chat = API.Chat; + OpenAI.Edits = API.Edits; + OpenAI.Embeddings = API.Embeddings; + OpenAI.Files = API.Files; + OpenAI.FileObjectsPage = API.FileObjectsPage; + OpenAI.Images = API.Images; + OpenAI.Audio = API.Audio; + OpenAI.Moderations = API.Moderations; + OpenAI.Models = API.Models; + OpenAI.ModelsPage = API.ModelsPage; + OpenAI.FineTuning = API.FineTuning; + OpenAI.FineTunes = API.FineTunes; + OpenAI.FineTunesPage = API.FineTunesPage; +})((OpenAI = exports.OpenAI || (exports.OpenAI = {}))); +exports = module.exports = OpenAI; +exports["default"] = OpenAI; +//# sourceMappingURL=index.js.map + + +/***/ }), -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/few_shot.js -var few_shot = __nccwpck_require__(609); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/chat.js -var chat = __nccwpck_require__(6704); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/template.js -var template = __nccwpck_require__(837); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/pipeline.js +/***/ 7401: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CursorPage = exports.Page = void 0; +const core_1 = __nccwpck_require__(1798); /** - * Class that handles a sequence of prompts, each of which may require - * different input variables. Includes methods for formatting these - * prompts, extracting required input values, and handling partial - * prompts. + * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ -class PipelinePromptTemplate extends (/* unused pure expression or super */ null && (BasePromptTemplate)) { - static lc_name() { - return "PipelinePromptTemplate"; - } - constructor(input) { - super({ ...input, inputVariables: [] }); - Object.defineProperty(this, "pipelinePrompts", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "finalPrompt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.pipelinePrompts = input.pipelinePrompts; - this.finalPrompt = input.finalPrompt; - this.inputVariables = this.computeInputValues(); - } - /** - * Computes the input values required by the pipeline prompts. - * @returns Array of input values required by the pipeline prompts. - */ - computeInputValues() { - const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); - const inputValues = this.pipelinePrompts - .map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))) - .flat(); - return [...new Set(inputValues)]; - } - static extractRequiredInputValues(allValues, requiredValueNames) { - return requiredValueNames.reduce((requiredValues, valueName) => { - // eslint-disable-next-line no-param-reassign - requiredValues[valueName] = allValues[valueName]; - return requiredValues; - }, {}); - } - /** - * Formats the pipeline prompts based on the provided input values. - * @param values Input values to format the pipeline prompts. - * @returns Promise that resolves with the formatted input values. - */ - async formatPipelinePrompts(values) { - const allValues = await this.mergePartialAndUserVariables(values); - for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this - .pipelinePrompts) { - const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); - // eslint-disable-next-line no-instanceof/no-instanceof - if (pipelinePrompt instanceof ChatPromptTemplate) { - allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); - } - else { - allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); - } - } - return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); - } - /** - * Formats the final prompt value based on the provided input values. - * @param values Input values to format the final prompt value. - * @returns Promise that resolves with the formatted final prompt value. - */ - async formatPromptValue(values) { - return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); - } - async format(values) { - return this.finalPrompt.format(await this.formatPipelinePrompts(values)); +class Page extends core_1.AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.object = body.object; + this.data = body.data; + } + getPaginatedItems() { + return this.data; + } + // @deprecated Please use `nextPageInfo()` instead + /** + * This page represents a response that isn't actually paginated at the API level + * so there will never be any next page params. + */ + nextPageParams() { + return null; + } + nextPageInfo() { + return null; + } +} +exports.Page = Page; +class CursorPage extends core_1.AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data; + } + getPaginatedItems() { + return this.data; + } + // @deprecated Please use `nextPageInfo()` instead + nextPageParams() { + const info = this.nextPageInfo(); + if (!info) return null; + if ('params' in info) return info.params; + const params = Object.fromEntries(info.url.searchParams); + if (!Object.keys(params).length) return null; + return params; + } + nextPageInfo() { + var _a, _b; + if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.length)) { + return null; } - /** - * Handles partial prompts, which are prompts that have been partially - * filled with input values. - * @param values Partial input values. - * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. - */ - async partial(values) { - const promptDict = { ...this }; - promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); - promptDict.partialVariables = { - ...(this.partialVariables ?? {}), - ...values, + const next = (_b = this.data[this.data.length - 1]) === null || _b === void 0 ? void 0 : _b.id; + if (!next) return null; + return { params: { after: next } }; + } +} +exports.CursorPage = CursorPage; +//# sourceMappingURL=pagination.js.map + + +/***/ }), + +/***/ 9593: +/***/ ((__unused_webpack_module, exports) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.APIResource = void 0; +class APIResource { + constructor(client) { + this.client = client; + this.get = client.get.bind(client); + this.post = client.post.bind(client); + this.patch = client.patch.bind(client); + this.put = client.put.bind(client); + this.delete = client.delete.bind(client); + this.getAPIList = client.getAPIList.bind(client); + } +} +exports.APIResource = APIResource; +//# sourceMappingURL=resource.js.map + + +/***/ }), + +/***/ 6376: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +// File generated from our OpenAPI spec by Stainless. +var __createBinding = + (this && this.__createBinding) || + (Object.create ? + function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, }; - return new PipelinePromptTemplate(promptDict); - } - serialize() { - throw new Error("Not implemented."); - } - _getPromptType() { - return "pipeline"; + } + Object.defineProperty(o, k2, desc); } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create ? + function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Audio = void 0; +const resource_1 = __nccwpck_require__(9593); +const transcriptions_1 = __nccwpck_require__(5622); +const translations_1 = __nccwpck_require__(7735); +const API = __importStar(__nccwpck_require__(6750)); +class Audio extends resource_1.APIResource { + constructor() { + super(...arguments); + this.transcriptions = new transcriptions_1.Transcriptions(this.client); + this.translations = new translations_1.Translations(this.client); + } } +exports.Audio = Audio; +(function (Audio) { + Audio.Transcriptions = API.Transcriptions; + Audio.Translations = API.Translations; +})((Audio = exports.Audio || (exports.Audio = {}))); +//# sourceMappingURL=audio.js.map -;// CONCATENATED MODULE: ./node_modules/langchain/dist/prompts/index.js +/***/ }), +/***/ 6750: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Translations = exports.Transcriptions = exports.Audio = void 0; +var audio_1 = __nccwpck_require__(6376); +Object.defineProperty(exports, "Audio", ({ + enumerable: true, + get: function () { + return audio_1.Audio; + }, +})); +var transcriptions_1 = __nccwpck_require__(5622); +Object.defineProperty(exports, "Transcriptions", ({ + enumerable: true, + get: function () { + return transcriptions_1.Transcriptions; + }, +})); +var translations_1 = __nccwpck_require__(7735); +Object.defineProperty(exports, "Translations", ({ + enumerable: true, + get: function () { + return translations_1.Translations; + }, +})); +//# sourceMappingURL=index.js.map +/***/ }), +/***/ 5622: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Transcriptions = void 0; +const resource_1 = __nccwpck_require__(9593); +const core_1 = __nccwpck_require__(1798); +class Transcriptions extends resource_1.APIResource { + /** + * Transcribes audio into the input language. + */ + create(body, options) { + return this.post('/audio/transcriptions', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } +} +exports.Transcriptions = Transcriptions; +(function (Transcriptions) {})((Transcriptions = exports.Transcriptions || (exports.Transcriptions = {}))); +//# sourceMappingURL=transcriptions.js.map /***/ }), -/***/ 3379: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -__nccwpck_require__.r(__webpack_exports__); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "PromptTemplate": () => (/* binding */ PromptTemplate) -/* harmony export */ }); -/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(5411); -/* harmony import */ var _template_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(837); -// Default generic "any" values are for backwards compatibility. -// Replace with "string" when we are comfortable with a breaking change. +/***/ 7735: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Schema to represent a basic prompt for an LLM. - * @augments BasePromptTemplate - * @augments PromptTemplateInput - * - * @example - * ```ts - * import { PromptTemplate } from "langchain/prompts"; - * - * const prompt = new PromptTemplate({ - * inputVariables: ["foo"], - * template: "Say {foo}", - * }); - * ``` - */ -class PromptTemplate extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .BaseStringPromptTemplate */ .Al { - static lc_name() { - return "PromptTemplate"; - } - constructor(input) { - super(input); - Object.defineProperty(this, "template", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "templateFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "f-string" - }); - Object.defineProperty(this, "validateTemplate", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.assign(this, input); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) { - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - } - (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .checkValidTemplate */ .af)(this.template, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - return (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .renderTemplate */ .SM)(this.template, this.templateFormat, allValues); - } - /** - * Take examples in list format with prefix and suffix to create a prompt. - * - * Intended to be used a a way to dynamically create a prompt from examples. - * - * @param examples - List of examples to use in the prompt. - * @param suffix - String to go after the list of examples. Should generally set up the user's input. - * @param inputVariables - A list of variable names the final prompt template will expect - * @param exampleSeparator - The separator to use in between examples - * @param prefix - String that should go before any examples. Generally includes examples. - * - * @returns The final prompt template generated. - */ - static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { - const template = [prefix, ...examples, suffix].join(exampleSeparator); - return new PromptTemplate({ - inputVariables, - template, - }); - } - /** - * Load prompt template from a template f-string - */ - static fromTemplate(template, { templateFormat = "f-string", ...rest } = {}) { - if (templateFormat === "jinja2") { - throw new Error("jinja2 templates are not currently supported."); - } - const names = new Set(); - (0,_template_js__WEBPACK_IMPORTED_MODULE_1__/* .parseTemplate */ .$M)(template, templateFormat).forEach((node) => { - if (node.type === "variable") { - names.add(node.name); - } - }); - return new PromptTemplate({ - // Rely on extracted types - // eslint-disable-next-line @typescript-eslint/no-explicit-any - inputVariables: [...names], - templateFormat, - template, - ...rest, - }); - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of PromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...(this.partialVariables ?? {}), - ...values, - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables, - }; - return new PromptTemplate(promptDict); - } - serialize() { - if (this.outputParser !== undefined) { - throw new Error("Cannot serialize a prompt template with an output parser"); - } - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - template: this.template, - template_format: this.templateFormat, +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Translations = void 0; +const resource_1 = __nccwpck_require__(9593); +const core_1 = __nccwpck_require__(1798); +class Translations extends resource_1.APIResource { + /** + * Translates audio into English. + */ + create(body, options) { + return this.post('/audio/translations', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } +} +exports.Translations = Translations; +(function (Translations) {})((Translations = exports.Translations || (exports.Translations = {}))); +//# sourceMappingURL=translations.js.map + + +/***/ }), + +/***/ 7670: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +// File generated from our OpenAPI spec by Stainless. +var __createBinding = + (this && this.__createBinding) || + (Object.create ? + function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, }; + } + Object.defineProperty(o, k2, desc); } - static async deserialize(data) { - if (!data.template) { - throw new Error("Prompt template must have a template"); - } - const res = new PromptTemplate({ - inputVariables: data.input_variables, - template: data.template, - templateFormat: data.template_format, - }); - return res; - } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create ? + function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Chat = void 0; +const resource_1 = __nccwpck_require__(9593); +const completions_1 = __nccwpck_require__(2875); +const API = __importStar(__nccwpck_require__(8240)); +class Chat extends resource_1.APIResource { + constructor() { + super(...arguments); + this.completions = new completions_1.Completions(this.client); + } } +exports.Chat = Chat; +(function (Chat) { + Chat.Completions = API.Completions; +})((Chat = exports.Chat || (exports.Chat = {}))); +//# sourceMappingURL=chat.js.map /***/ }), -/***/ 837: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 2875: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "$M": () => (/* binding */ parseTemplate), -/* harmony export */ "SM": () => (/* binding */ renderTemplate), -/* harmony export */ "af": () => (/* binding */ checkValidTemplate) -/* harmony export */ }); -/* unused harmony exports parseFString, interpolateFString, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING */ -const parseFString = (template) => { - // Core logic replicated from internals of pythons built in Formatter class. - // https://github.com/python/cpython/blob/135ec7cefbaffd516b77362ad2b2ad1025af462e/Objects/stringlib/unicode_format.h#L700-L706 - const chars = template.split(""); - const nodes = []; - const nextBracket = (bracket, start) => { - for (let i = start; i < chars.length; i += 1) { - if (bracket.includes(chars[i])) { - return i; - } - } - return -1; - }; - let i = 0; - while (i < chars.length) { - if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { - nodes.push({ type: "literal", text: "{" }); - i += 2; - } - else if (chars[i] === "}" && - i + 1 < chars.length && - chars[i + 1] === "}") { - nodes.push({ type: "literal", text: "}" }); - i += 2; - } - else if (chars[i] === "{") { - const j = nextBracket("}", i); - if (j < 0) { - throw new Error("Unclosed '{' in template."); - } - nodes.push({ - type: "variable", - name: chars.slice(i + 1, j).join(""), - }); - i = j + 1; - } - else if (chars[i] === "}") { - throw new Error("Single '}' in template."); - } - else { - const next = nextBracket("{}", i); - const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); - nodes.push({ type: "literal", text }); - i = next < 0 ? chars.length : next; - } - } - return nodes; -}; -const interpolateFString = (template, values) => parseFString(template).reduce((res, node) => { - if (node.type === "variable") { - if (node.name in values) { - return res + values[node.name]; - } - throw new Error(`Missing value for input ${node.name}`); - } - return res + node.text; -}, ""); -const DEFAULT_FORMATTER_MAPPING = { - "f-string": interpolateFString, - jinja2: (_, __) => "", -}; -const DEFAULT_PARSER_MAPPING = { - "f-string": parseFString, - jinja2: (_) => [], -}; -const renderTemplate = (template, templateFormat, inputValues) => DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); -const parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); -const checkValidTemplate = (template, templateFormat, inputVariables) => { - if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { - const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); - throw new Error(`Invalid template format. Got \`${templateFormat}\`; - should be one of ${validFormats}`); - } - try { - const dummyInputs = inputVariables.reduce((acc, v) => { - acc[v] = "foo"; - return acc; - }, {}); - renderTemplate(template, templateFormat, dummyInputs); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - throw new Error(`Invalid prompt schema: ${e.message}`); - } -}; + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Completions = void 0; +const resource_1 = __nccwpck_require__(9593); +class Completions extends resource_1.APIResource { + create(body, options) { + var _a; + return this.post('/chat/completions', { + body, + ...options, + stream: (_a = body.stream) !== null && _a !== void 0 ? _a : false, + }); + } +} +exports.Completions = Completions; +(function (Completions) {})((Completions = exports.Completions || (exports.Completions = {}))); +//# sourceMappingURL=completions.js.map + + +/***/ }), + +/***/ 8240: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Completions = exports.Chat = void 0; +var chat_1 = __nccwpck_require__(7670); +Object.defineProperty(exports, "Chat", ({ + enumerable: true, + get: function () { + return chat_1.Chat; + }, +})); +var completions_1 = __nccwpck_require__(2875); +Object.defineProperty(exports, "Completions", ({ + enumerable: true, + get: function () { + return completions_1.Completions; + }, +})); +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 9327: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Completions = void 0; +const resource_1 = __nccwpck_require__(9593); +class Completions extends resource_1.APIResource { + create(body, options) { + var _a; + return this.post('/completions', { + body, + ...options, + stream: (_a = body.stream) !== null && _a !== void 0 ? _a : false, + }); + } +} +exports.Completions = Completions; +(function (Completions) {})((Completions = exports.Completions || (exports.Completions = {}))); +//# sourceMappingURL=completions.js.map + + +/***/ }), + +/***/ 4259: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Edits = void 0; +const resource_1 = __nccwpck_require__(9593); +class Edits extends resource_1.APIResource { + /** + * Creates a new edit for the provided input, instruction, and parameters. + * + * @deprecated The Edits API is deprecated; please use Chat Completions instead. + * + * https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api + */ + create(body, options) { + return this.post('/edits', { body, ...options }); + } +} +exports.Edits = Edits; +(function (Edits) {})((Edits = exports.Edits || (exports.Edits = {}))); +//# sourceMappingURL=edits.js.map /***/ }), -/***/ 8102: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/***/ 8064: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "Cr": () => (/* binding */ FunctionMessageChunk), -/* harmony export */ "E1": () => (/* binding */ coerceMessageLikeToMessage), -/* harmony export */ "GC": () => (/* binding */ AIMessageChunk), -/* harmony export */ "H2": () => (/* binding */ BaseCache), -/* harmony export */ "HD": () => (/* binding */ ChatMessageChunk), -/* harmony export */ "J": () => (/* binding */ ChatMessage), -/* harmony export */ "Ls": () => (/* binding */ ChatGenerationChunk), -/* harmony export */ "MJ": () => (/* binding */ BasePromptValue), -/* harmony export */ "QW": () => (/* binding */ isBaseMessage), -/* harmony export */ "WH": () => (/* binding */ RUN_KEY), -/* harmony export */ "b6": () => (/* binding */ GenerationChunk), -/* harmony export */ "gY": () => (/* binding */ AIMessage), -/* harmony export */ "jN": () => (/* binding */ SystemMessage), -/* harmony export */ "ku": () => (/* binding */ BaseMessage), -/* harmony export */ "ro": () => (/* binding */ HumanMessageChunk), -/* harmony export */ "xk": () => (/* binding */ HumanMessage), -/* harmony export */ "xq": () => (/* binding */ SystemMessageChunk) -/* harmony export */ }); -/* unused harmony exports BaseMessageChunk, BaseChatMessage, HumanChatMessage, AIChatMessage, SystemChatMessage, FunctionMessage, mapStoredMessageToChatMessage, BaseChatMessageHistory, BaseListChatMessageHistory, BaseFileStore, BaseEntityStore, Docstore */ -/* harmony import */ var _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(4432); -const RUN_KEY = "__run"; -/** - * Chunk of a single generation. Used for streaming. - */ -class GenerationChunk { - constructor(fields) { - Object.defineProperty(this, "text", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "generationInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.text = fields.text; - this.generationInfo = fields.generationInfo; - } - concat(chunk) { - return new GenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo, - }, - }); - } +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Embeddings = void 0; +const resource_1 = __nccwpck_require__(9593); +class Embeddings extends resource_1.APIResource { + /** + * Creates an embedding vector representing the input text. + */ + create(body, options) { + return this.post('/embeddings', { body, ...options }); + } } -/** - * Base class for all types of messages in a conversation. It includes - * properties like `content`, `name`, and `additional_kwargs`. It also - * includes methods like `toDict()` and `_getType()`. - */ -class BaseMessage extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable */ .i { - /** - * @deprecated - * Use {@link BaseMessage.content} instead. - */ - get text() { - return this.content; - } - constructor(fields, - /** @deprecated */ - kwargs) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign - fields = { content: fields, additional_kwargs: kwargs }; - } - // Make sure the default value for additional_kwargs is passed into super() for serialization - if (!fields.additional_kwargs) { - // eslint-disable-next-line no-param-reassign - fields.additional_kwargs = {}; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - /** The text of the message. */ - Object.defineProperty(this, "content", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** The name of the message sender in a multi-user chat. */ - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** Additional keyword arguments */ - Object.defineProperty(this, "additional_kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = fields.name; - this.content = fields.content; - this.additional_kwargs = fields.additional_kwargs; - } - toDict() { - return { - type: this._getType(), - data: this.toJSON() - .kwargs, - }; - } +exports.Embeddings = Embeddings; +(function (Embeddings) {})((Embeddings = exports.Embeddings || (exports.Embeddings = {}))); +//# sourceMappingURL=embeddings.js.map + + +/***/ }), + +/***/ 3873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileObjectsPage = exports.Files = void 0; +const resource_1 = __nccwpck_require__(9593); +const core_1 = __nccwpck_require__(1798); +const pagination_1 = __nccwpck_require__(7401); +class Files extends resource_1.APIResource { + /** + * Upload a file that contains document(s) to be used across various + * endpoints/features. Currently, the size of all the files uploaded by one + * organization can be up to 1 GB. Please contact us if you need to increase the + * storage limit. + */ + create(body, options) { + return this.post('/files', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } + /** + * Returns information about a specific file. + */ + retrieve(fileId, options) { + return this.get(`/files/${fileId}`, options); + } + /** + * Returns a list of files that belong to the user's organization. + */ + list(options) { + return this.getAPIList('/files', FileObjectsPage, options); + } + /** + * Delete a file. + */ + del(fileId, options) { + return this.delete(`/files/${fileId}`, options); + } + /** + * Returns the contents of the specified file + */ + retrieveContent(fileId, options) { + return this.get(`/files/${fileId}/content`, { + ...options, + headers: { + Accept: 'application/json', + ...(options === null || options === void 0 ? void 0 : options.headers), + }, + }); + } } +exports.Files = Files; /** - * Represents a chunk of a message, which can be concatenated with other - * message chunks. It includes a method `_merge_kwargs_dict()` for merging - * additional keyword arguments from another `BaseMessageChunk` into this - * one. It also overrides the `__add__()` method to support concatenation - * of `BaseMessageChunk` instances. + * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ -class BaseMessageChunk extends BaseMessage { - static _mergeAdditionalKwargs(left, right) { - const merged = { ...left }; - for (const [key, value] of Object.entries(right)) { - if (merged[key] === undefined) { - merged[key] = value; - } - else if (typeof merged[key] !== typeof value) { - throw new Error(`additional_kwargs[${key}] already exists in the message chunk, but with a different type.`); - } - else if (typeof merged[key] === "string") { - merged[key] = merged[key] + value; - } - else if (!Array.isArray(merged[key]) && - typeof merged[key] === "object") { - merged[key] = this._mergeAdditionalKwargs(merged[key], value); - } - else { - throw new Error(`additional_kwargs[${key}] already exists in this message chunk.`); - } - } - return merged; - } +class FileObjectsPage extends pagination_1.Page {} +exports.FileObjectsPage = FileObjectsPage; +(function (Files) {})((Files = exports.Files || (exports.Files = {}))); +//# sourceMappingURL=files.js.map + + +/***/ }), + +/***/ 3379: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FineTunesPage = exports.FineTunes = void 0; +const resource_1 = __nccwpck_require__(9593); +const pagination_1 = __nccwpck_require__(7401); +class FineTunes extends resource_1.APIResource { + /** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/legacy-fine-tuning) + */ + create(body, options) { + return this.post('/fine-tunes', { body, ...options }); + } + /** + * Gets info about the fine-tune job. + * + * [Learn more about fine-tuning](/docs/guides/legacy-fine-tuning) + */ + retrieve(fineTuneId, options) { + return this.get(`/fine-tunes/${fineTuneId}`, options); + } + /** + * List your organization's fine-tuning jobs + */ + list(options) { + return this.getAPIList('/fine-tunes', FineTunesPage, options); + } + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuneId, options) { + return this.post(`/fine-tunes/${fineTuneId}/cancel`, options); + } + listEvents(fineTuneId, query, options) { + var _a; + return this.get(`/fine-tunes/${fineTuneId}/events`, { + query, + timeout: 86400000, + ...options, + stream: + (_a = query === null || query === void 0 ? void 0 : query.stream) !== null && _a !== void 0 ? + _a + : false, + }); + } } +exports.FineTunes = FineTunes; /** - * Represents a human message in a conversation. + * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ -class HumanMessage extends BaseMessage { - static lc_name() { - return "HumanMessage"; - } - _getType() { - return "human"; +class FineTunesPage extends pagination_1.Page {} +exports.FineTunesPage = FineTunesPage; +(function (FineTunes) {})((FineTunes = exports.FineTunes || (exports.FineTunes = {}))); +//# sourceMappingURL=fine-tunes.js.map + + +/***/ }), + +/***/ 1364: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +// File generated from our OpenAPI spec by Stainless. +var __createBinding = + (this && this.__createBinding) || + (Object.create ? + function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + }, + }; + } + Object.defineProperty(o, k2, desc); } + : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); +var __setModuleDefault = + (this && this.__setModuleDefault) || + (Object.create ? + function (o, v) { + Object.defineProperty(o, 'default', { enumerable: true, value: v }); + } + : function (o, v) { + o['default'] = v; + }); +var __importStar = + (this && this.__importStar) || + function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) + for (var k in mod) + if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FineTuning = void 0; +const resource_1 = __nccwpck_require__(9593); +const jobs_1 = __nccwpck_require__(4900); +const API = __importStar(__nccwpck_require__(8093)); +class FineTuning extends resource_1.APIResource { + constructor() { + super(...arguments); + this.jobs = new jobs_1.Jobs(this.client); + } } -/** - * Represents a chunk of a human message, which can be concatenated with - * other human message chunks. - */ -class HumanMessageChunk extends BaseMessageChunk { - static lc_name() { - return "HumanMessageChunk"; - } - _getType() { - return "human"; +exports.FineTuning = FineTuning; +(function (FineTuning) { + FineTuning.Jobs = API.Jobs; + FineTuning.FineTuningJobsPage = API.FineTuningJobsPage; + FineTuning.FineTuningJobEventsPage = API.FineTuningJobEventsPage; +})((FineTuning = exports.FineTuning || (exports.FineTuning = {}))); +//# sourceMappingURL=fine-tuning.js.map + + +/***/ }), + +/***/ 8093: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Jobs = exports.FineTuningJobEventsPage = exports.FineTuningJobsPage = exports.FineTuning = void 0; +var fine_tuning_1 = __nccwpck_require__(1364); +Object.defineProperty(exports, "FineTuning", ({ + enumerable: true, + get: function () { + return fine_tuning_1.FineTuning; + }, +})); +var jobs_1 = __nccwpck_require__(4900); +Object.defineProperty(exports, "FineTuningJobsPage", ({ + enumerable: true, + get: function () { + return jobs_1.FineTuningJobsPage; + }, +})); +Object.defineProperty(exports, "FineTuningJobEventsPage", ({ + enumerable: true, + get: function () { + return jobs_1.FineTuningJobEventsPage; + }, +})); +Object.defineProperty(exports, "Jobs", ({ + enumerable: true, + get: function () { + return jobs_1.Jobs; + }, +})); +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 4900: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FineTuningJobEventsPage = exports.FineTuningJobsPage = exports.Jobs = void 0; +const resource_1 = __nccwpck_require__(9593); +const core_1 = __nccwpck_require__(1798); +const pagination_1 = __nccwpck_require__(7401); +class Jobs extends resource_1.APIResource { + /** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ + create(body, options) { + return this.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ + retrieve(fineTuningJobId, options) { + return this.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); + } + list(query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.list({}, query); } - concat(chunk) { - return new HumanMessageChunk({ - content: this.content + chunk.content, - additional_kwargs: HumanMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), - }); + return this.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + */ + cancel(fineTuningJobId, options) { + return this.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); + } + listEvents(fineTuningJobId, query = {}, options) { + if ((0, core_1.isRequestOptions)(query)) { + return this.listEvents(fineTuningJobId, {}, query); } + return this.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { + query, + ...options, + }); + } } -/** - * Represents an AI message in a conversation. - */ -class AIMessage extends BaseMessage { - static lc_name() { - return "AIMessage"; - } - _getType() { - return "ai"; - } +exports.Jobs = Jobs; +class FineTuningJobsPage extends pagination_1.CursorPage {} +exports.FineTuningJobsPage = FineTuningJobsPage; +class FineTuningJobEventsPage extends pagination_1.CursorPage {} +exports.FineTuningJobEventsPage = FineTuningJobEventsPage; +(function (Jobs) {})((Jobs = exports.Jobs || (exports.Jobs = {}))); +//# sourceMappingURL=jobs.js.map + + +/***/ }), + +/***/ 2621: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Images = void 0; +const resource_1 = __nccwpck_require__(9593); +const core_1 = __nccwpck_require__(1798); +class Images extends resource_1.APIResource { + /** + * Creates a variation of a given image. + */ + createVariation(body, options) { + return this.post('/images/variations', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } + /** + * Creates an edited or extended image given an original image and a prompt. + */ + edit(body, options) { + return this.post('/images/edits', (0, core_1.multipartFormRequestOptions)({ body, ...options })); + } + /** + * Creates an image given a prompt. + */ + generate(body, options) { + return this.post('/images/generations', { body, ...options }); + } } -/** - * Represents a chunk of an AI message, which can be concatenated with - * other AI message chunks. - */ -class AIMessageChunk extends BaseMessageChunk { - static lc_name() { - return "AIMessageChunk"; - } - _getType() { - return "ai"; - } - concat(chunk) { - return new AIMessageChunk({ - content: this.content + chunk.content, - additional_kwargs: AIMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), - }); - } +exports.Images = Images; +(function (Images) {})((Images = exports.Images || (exports.Images = {}))); +//# sourceMappingURL=images.js.map + + +/***/ }), + +/***/ 5690: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Moderations = + exports.Models = + exports.ModelsPage = + exports.Images = + exports.FineTuning = + exports.FineTunes = + exports.FineTunesPage = + exports.Files = + exports.FileObjectsPage = + exports.Edits = + exports.Embeddings = + exports.Completions = + exports.Chat = + exports.Audio = + void 0; +var audio_1 = __nccwpck_require__(6376); +Object.defineProperty(exports, "Audio", ({ + enumerable: true, + get: function () { + return audio_1.Audio; + }, +})); +var chat_1 = __nccwpck_require__(7670); +Object.defineProperty(exports, "Chat", ({ + enumerable: true, + get: function () { + return chat_1.Chat; + }, +})); +var completions_1 = __nccwpck_require__(9327); +Object.defineProperty(exports, "Completions", ({ + enumerable: true, + get: function () { + return completions_1.Completions; + }, +})); +var embeddings_1 = __nccwpck_require__(8064); +Object.defineProperty(exports, "Embeddings", ({ + enumerable: true, + get: function () { + return embeddings_1.Embeddings; + }, +})); +var edits_1 = __nccwpck_require__(4259); +Object.defineProperty(exports, "Edits", ({ + enumerable: true, + get: function () { + return edits_1.Edits; + }, +})); +var files_1 = __nccwpck_require__(3873); +Object.defineProperty(exports, "FileObjectsPage", ({ + enumerable: true, + get: function () { + return files_1.FileObjectsPage; + }, +})); +Object.defineProperty(exports, "Files", ({ + enumerable: true, + get: function () { + return files_1.Files; + }, +})); +var fine_tunes_1 = __nccwpck_require__(3379); +Object.defineProperty(exports, "FineTunesPage", ({ + enumerable: true, + get: function () { + return fine_tunes_1.FineTunesPage; + }, +})); +Object.defineProperty(exports, "FineTunes", ({ + enumerable: true, + get: function () { + return fine_tunes_1.FineTunes; + }, +})); +var fine_tuning_1 = __nccwpck_require__(1364); +Object.defineProperty(exports, "FineTuning", ({ + enumerable: true, + get: function () { + return fine_tuning_1.FineTuning; + }, +})); +var images_1 = __nccwpck_require__(2621); +Object.defineProperty(exports, "Images", ({ + enumerable: true, + get: function () { + return images_1.Images; + }, +})); +var models_1 = __nccwpck_require__(6467); +Object.defineProperty(exports, "ModelsPage", ({ + enumerable: true, + get: function () { + return models_1.ModelsPage; + }, +})); +Object.defineProperty(exports, "Models", ({ + enumerable: true, + get: function () { + return models_1.Models; + }, +})); +var moderations_1 = __nccwpck_require__(2085); +Object.defineProperty(exports, "Moderations", ({ + enumerable: true, + get: function () { + return moderations_1.Moderations; + }, +})); +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 6467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ModelsPage = exports.Models = void 0; +const resource_1 = __nccwpck_require__(9593); +const pagination_1 = __nccwpck_require__(7401); +class Models extends resource_1.APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this.get(`/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this.getAPIList('/models', ModelsPage, options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization. + */ + del(model, options) { + return this.delete(`/models/${model}`, options); + } } +exports.Models = Models; /** - * Represents a system message in a conversation. + * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ -class SystemMessage extends BaseMessage { - static lc_name() { - return "SystemMessage"; - } - _getType() { - return "system"; - } +class ModelsPage extends pagination_1.Page {} +exports.ModelsPage = ModelsPage; +(function (Models) {})((Models = exports.Models || (exports.Models = {}))); +//# sourceMappingURL=models.js.map + + +/***/ }), + +/***/ 2085: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Moderations = void 0; +const resource_1 = __nccwpck_require__(9593); +class Moderations extends resource_1.APIResource { + /** + * Classifies if text violates OpenAI's Content Policy + */ + create(body, options) { + return this.post('/moderations', { body, ...options }); + } } -/** - * Represents a chunk of a system message, which can be concatenated with - * other system message chunks. - */ -class SystemMessageChunk extends BaseMessageChunk { - static lc_name() { - return "SystemMessageChunk"; - } - _getType() { - return "system"; +exports.Moderations = Moderations; +(function (Moderations) {})((Moderations = exports.Moderations || (exports.Moderations = {}))); +//# sourceMappingURL=moderations.js.map + + +/***/ }), + +/***/ 884: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Stream = void 0; +class Stream { + constructor(response, controller) { + this.response = response; + this.controller = controller; + this.decoder = new SSEDecoder(); + } + async *iterMessages() { + if (!this.response.body) { + this.controller.abort(); + throw new Error(`Attempted to iterate over a response with no body`); } - concat(chunk) { - return new SystemMessageChunk({ - content: this.content + chunk.content, - additional_kwargs: SystemMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), - }); + const lineDecoder = new LineDecoder(); + const iter = readableStreamAsyncIterable(this.response.body); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + const sse = this.decoder.decode(line); + if (sse) yield sse; + } } -} -/** - * @deprecated - * Use {@link BaseMessage} instead. - */ -const BaseChatMessage = (/* unused pure expression or super */ null && (BaseMessage)); -/** - * @deprecated - * Use {@link HumanMessage} instead. - */ -const HumanChatMessage = (/* unused pure expression or super */ null && (HumanMessage)); -/** - * @deprecated - * Use {@link AIMessage} instead. - */ -const AIChatMessage = (/* unused pure expression or super */ null && (AIMessage)); -/** - * @deprecated - * Use {@link SystemMessage} instead. - */ -const SystemChatMessage = (/* unused pure expression or super */ null && (SystemMessage)); -/** - * Represents a function message in a conversation. - */ -class FunctionMessage extends (/* unused pure expression or super */ null && (BaseMessage)) { - static lc_name() { - return "FunctionMessage"; + for (const line of lineDecoder.flush()) { + const sse = this.decoder.decode(line); + if (sse) yield sse; } - constructor(fields, - /** @deprecated */ - name) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, name: name }; + } + async *[Symbol.asyncIterator]() { + let done = false; + try { + for await (const sse of this.iterMessages()) { + if (done) continue; + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; } - super(fields); - } - _getType() { - return "function"; + if (sse.event === null) { + try { + yield JSON.parse(sse.data); + } catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + } + } + done = true; + } catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (e instanceof Error && e.name === 'AbortError') return; + throw e; + } finally { + // If the user `break`s, abort the ongoing request. + if (!done) this.controller.abort(); } + } } -/** - * Represents a chunk of a function message, which can be concatenated - * with other function message chunks. - */ -class FunctionMessageChunk extends BaseMessageChunk { - static lc_name() { - return "FunctionMessageChunk"; +exports.Stream = Stream; +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); } - _getType() { - return "function"; + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; } - concat(chunk) { - return new FunctionMessageChunk({ - content: this.content + chunk.content, - additional_kwargs: FunctionMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), - name: this.name ?? "", - }); + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } else if (fieldname === 'data') { + this.data.push(value); } + return null; + } } /** - * Represents a chat message in a conversation. + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 */ -class ChatMessage extends BaseMessage { - static lc_name() { - return "ChatMessage"; - } - constructor(fields, role) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, role: role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; +class LineDecoder { + constructor() { + this.buffer = []; + this.trailingCR = false; + } + decode(chunk) { + let text = this.decodeText(chunk); + if (this.trailingCR) { + text = '\r' + text; + this.trailingCR = false; } - _getType() { - return "generic"; + if (text.endsWith('\r')) { + this.trailingCR = true; + text = text.slice(0, -1); } - static isInstance(message) { - return message._getType() === "generic"; + if (!text) { + return []; } -} -function isBaseMessage(messageLike) { - return typeof messageLike._getType === "function"; -} -function coerceMessageLikeToMessage(messageLike) { - if (typeof messageLike === "string") { - return new HumanMessage(messageLike); + const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ''); + let lines = text.split(LineDecoder.NEWLINE_REGEXP); + if (lines.length === 1 && !trailingNewline) { + this.buffer.push(lines[0]); + return []; } - else if (isBaseMessage(messageLike)) { - return messageLike; + if (this.buffer.length > 0) { + lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; + this.buffer = []; } - const [type, content] = messageLike; - if (type === "human" || type === "user") { - return new HumanMessage({ content }); + if (!trailingNewline) { + this.buffer = [lines.pop() || '']; } - else if (type === "ai" || type === "assistant") { - return new AIMessage({ content }); + return lines; + } + decodeText(bytes) { + var _a; + if (bytes == null) return ''; + if (typeof bytes === 'string') return bytes; + // Node: + if (typeof Buffer !== 'undefined') { + if (bytes instanceof Buffer) { + return bytes.toString(); + } + if (bytes instanceof Uint8Array) { + return Buffer.from(bytes).toString(); + } + throw new Error( + `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`, + ); } - else if (type === "system") { - return new SystemMessage({ content }); + // Browser + if (typeof TextDecoder !== 'undefined') { + if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { + (_a = this.textDecoder) !== null && _a !== void 0 ? _a : (this.textDecoder = new TextDecoder('utf8')); + return this.textDecoder.decode(bytes); + } + throw new Error( + `Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`, + ); } - else { - throw new Error(`Unable to coerce message from array: only human, AI, or system message coercion is currently supported.`); + throw new Error( + `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`, + ); + } + flush() { + if (!this.buffer.length && !this.trailingCR) { + return []; } + const lines = [this.buffer.join('')]; + this.buffer = []; + this.trailingCR = false; + return lines; + } +} +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\x85', '\u2028', '\u2029']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; } /** - * Represents a chunk of a chat message, which can be concatenated with - * other chat message chunks. + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 */ -class ChatMessageChunk extends BaseMessageChunk { - static lc_name() { - return "ChatMessageChunk"; - } - constructor(fields, role) { - if (typeof fields === "string") { - // eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion - fields = { content: fields, role: role }; - } - super(fields); - Object.defineProperty(this, "role", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.role = fields.role; - } - _getType() { - return "generic"; - } - concat(chunk) { - return new ChatMessageChunk({ - content: this.content + chunk.content, - additional_kwargs: ChatMessageChunk._mergeAdditionalKwargs(this.additional_kwargs, chunk.additional_kwargs), - role: this.role, - }); - } -} -class ChatGenerationChunk extends GenerationChunk { - constructor(fields) { - super(fields); - Object.defineProperty(this, "message", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.message = fields.message; - } - concat(chunk) { - return new ChatGenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo, - }, - message: this.message.concat(chunk.message), - }); - } +function readableStreamAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result === null || result === void 0 ? void 0 : result.done) reader.releaseLock(); // release lock when stream becomes closed + return result; + } catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; } +//# sourceMappingURL=streaming.js.map + + +/***/ }), + +/***/ 6800: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createForm = + exports.multipartFormRequestOptions = + exports.maybeMultipartFormRequestOptions = + exports.isMultipartBody = + exports.MultipartBody = + exports.toFile = + exports.isUploadable = + exports.isBlobLike = + exports.isFileLike = + exports.isResponseLike = + exports.fileFromPath = + void 0; +const formdata_1 = __nccwpck_require__(7744); +const getMultipartRequestOptions_1 = __nccwpck_require__(8462); +const fileFromPath_1 = __nccwpck_require__(8244); +Object.defineProperty(exports, "fileFromPath", ({ + enumerable: true, + get: function () { + return fileFromPath_1.fileFromPath; + }, +})); +const node_readable_1 = __nccwpck_require__(9104); +const isResponseLike = (value) => + value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +exports.isResponseLike = isResponseLike; +const isFileLike = (value) => + value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + (0, exports.isBlobLike)(value); +exports.isFileLike = isFileLike; /** - * Maps messages from an older format (V1) to the current `StoredMessage` - * format. If the message is already in the `StoredMessage` format, it is - * returned as is. Otherwise, it transforms the V1 message into a - * `StoredMessage`. This function is important for maintaining - * compatibility with older message formats. + * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check + * adds the arrayBuffer() method type because it is available and used at runtime */ -function mapV1MessageToStoredMessage(message) { - // TODO: Remove this mapper when we deprecate the old message format. - if (message.data !== undefined) { - return message; - } - else { - const v1Message = message; - return { - type: v1Message.type, - data: { - content: v1Message.text, - role: v1Message.role, - name: undefined, - }, - }; +const isBlobLike = (value) => + value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +exports.isBlobLike = isBlobLike; +const isUploadable = (value) => { + return ( + (0, exports.isFileLike)(value) || + (0, exports.isResponseLike)(value) || + (0, node_readable_1.isFsReadStream)(value) + ); +}; +exports.isUploadable = isUploadable; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function toFile(value, name, options = {}) { + var _a, _b, _c; + // If it's a promise, resolve it. + value = await value; + if ((0, exports.isResponseLike)(value)) { + const blob = await value.blob(); + name || + (name = + (_a = new URL(value.url).pathname.split(/[\\/]/).pop()) !== null && _a !== void 0 ? + _a + : 'unknown_file'); + return new formdata_1.File([blob], name, options); + } + const bits = await getBytes(value); + name || (name = (_b = getName(value)) !== null && _b !== void 0 ? _b : 'unknown_file'); + if (!options.type) { + const type = (_c = bits[0]) === null || _c === void 0 ? void 0 : _c.type; + if (typeof type === 'string') { + options = { ...options, type }; } + } + return new formdata_1.File(bits, name, options); } -function mapStoredMessageToChatMessage(message) { - const storedMessage = mapV1MessageToStoredMessage(message); - switch (storedMessage.type) { - case "human": - return new HumanMessage(storedMessage.data); - case "ai": - return new AIMessage(storedMessage.data); - case "system": - return new SystemMessage(storedMessage.data); - case "function": - if (storedMessage.data.name === undefined) { - throw new Error("Name must be defined for function messages"); - } - return new FunctionMessage(storedMessage.data); - case "chat": { - if (storedMessage.data.role === undefined) { - throw new Error("Role must be defined for chat messages"); - } - return new ChatMessage(storedMessage.data); - } - default: - throw new Error(`Got unexpected type: ${storedMessage.type}`); +exports.toFile = toFile; +async function getBytes(value) { + var _a; + let parts = []; + if ( + typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer + ) { + parts.push(value); + } else if ((0, exports.isBlobLike)(value)) { + parts.push(await value.arrayBuffer()); + } else if ( + isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(chunk); // TODO, consider validating? } + } else { + throw new Error( + `Unexpected data type: ${typeof value}; constructor: ${ + (_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? + void 0 + : _a.name + }; props: ${propsForError(value)}`, + ); + } + return parts; } -/** - * Base PromptValue class. All prompt values should extend this class. - */ -class BasePromptValue extends _load_serializable_js__WEBPACK_IMPORTED_MODULE_0__/* .Serializable */ .i { +function propsForError(value) { + const props = Object.getOwnPropertyNames(value); + return `[${props.map((p) => `"${p}"`).join(', ')}]`; +} +function getName(value) { + var _a; + return ( + getStringFromMaybeBuffer(value.name) || + getStringFromMaybeBuffer(value.filename) || + // For fs.ReadStream + ((_a = getStringFromMaybeBuffer(value.path)) === null || _a === void 0 ? void 0 : _a.split(/[\\/]/).pop()) + ); } -/** - * Base class for all chat message histories. All chat message histories - * should extend this class. - */ -class BaseChatMessageHistory extends (/* unused pure expression or super */ null && (Serializable)) { +const getStringFromMaybeBuffer = (x) => { + if (typeof x === 'string') return x; + if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x); + return undefined; +}; +const isAsyncIterableIterator = (value) => + value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +class MultipartBody { + constructor(body) { + this.body = body; + } + get [Symbol.toStringTag]() { + return 'MultipartBody'; + } } +exports.MultipartBody = MultipartBody; +const isMultipartBody = (body) => + body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; +exports.isMultipartBody = isMultipartBody; /** - * Base class for all list chat message histories. All list chat message - * histories should extend this class. + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. */ -class BaseListChatMessageHistory extends (/* unused pure expression or super */ null && (Serializable)) { - addUserMessage(message) { - return this.addMessage(new HumanMessage(message)); - } - addAIChatMessage(message) { - return this.addMessage(new AIMessage(message)); +const maybeMultipartFormRequestOptions = async (opts) => { + if (!hasUploadableValue(opts.body)) return opts; + const form = await (0, exports.createForm)(opts.body); + return (0, getMultipartRequestOptions_1.getMultipartRequestOptions)(form, opts); +}; +exports.maybeMultipartFormRequestOptions = maybeMultipartFormRequestOptions; +const multipartFormRequestOptions = async (opts) => { + const form = await (0, exports.createForm)(opts.body); + return (0, getMultipartRequestOptions_1.getMultipartRequestOptions)(form, opts); +}; +exports.multipartFormRequestOptions = multipartFormRequestOptions; +const createForm = async (body) => { + const form = new formdata_1.FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +exports.createForm = createForm; +const hasUploadableValue = (value) => { + if ((0, exports.isUploadable)(value)) return true; + if (Array.isArray(value)) return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) return true; } + } + return false; +}; +const addFormValue = async (form, key, value) => { + if (value === undefined) return; + if (value == null) { + throw new TypeError( + `Received null for "${key}"; to pass null in FormData, you must use the string 'null'`, + ); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } else if ((0, exports.isUploadable)(value)) { + const file = await toFile(value); + form.append(key, file); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } else if (typeof value === 'object') { + await Promise.all( + Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)), + ); + } else { + throw new TypeError( + `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`, + ); + } +}; +//# sourceMappingURL=uploads.js.map + + +/***/ }), + +/***/ 6417: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VERSION = void 0; +exports.VERSION = '4.4.0'; // x-release-please-version +//# sourceMappingURL=version.js.map + + +/***/ }), + +/***/ 8757: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Axios v1.5.1 Copyright (c) 2023 Matt Zabriskie and contributors + + +const FormData$1 = __nccwpck_require__(4334); +const url = __nccwpck_require__(7310); +const proxyFromEnv = __nccwpck_require__(3329); +const http = __nccwpck_require__(3685); +const https = __nccwpck_require__(5687); +const util = __nccwpck_require__(3837); +const followRedirects = __nccwpck_require__(7707); +const zlib = __nccwpck_require__(9796); +const stream = __nccwpck_require__(2781); +const EventEmitter = __nccwpck_require__(2361); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1); +const url__default = /*#__PURE__*/_interopDefaultLegacy(url); +const http__default = /*#__PURE__*/_interopDefaultLegacy(http); +const https__default = /*#__PURE__*/_interopDefaultLegacy(https); +const util__default = /*#__PURE__*/_interopDefaultLegacy(util); +const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); +const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); +const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); +const EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter); + +function bind(fn, thisArg) { + return function wrap() { + return fn.apply(thisArg, arguments); + }; } + +// utils is a library of generic helper functions non-specific to axios + +const {toString} = Object.prototype; +const {getPrototypeOf} = Object; + +const kindOf = (cache => thing => { + const str = toString.call(thing); + return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); +})(Object.create(null)); + +const kindOfTest = (type) => { + type = type.toLowerCase(); + return (thing) => kindOf(thing) === type +}; + +const typeOfTest = type => thing => typeof thing === type; + /** - * Base class for all caches. All caches should extend this class. + * Determine if a value is an Array + * + * @param {Object} val The value to test + * + * @returns {boolean} True if value is an Array, otherwise false */ -class BaseCache { -} +const {isArray} = Array; + /** - * Base class for all file stores. All file stores should extend this - * class. + * Determine if a value is undefined + * + * @param {*} val The value to test + * + * @returns {boolean} True if the value is undefined, otherwise false */ -class BaseFileStore extends (/* unused pure expression or super */ null && (Serializable)) { -} +const isUndefined = typeOfTest('undefined'); + /** - * Base class for all entity stores. All entity stores should extend this - * class. + * Determine if a value is a Buffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Buffer, otherwise false */ -class BaseEntityStore extends (/* unused pure expression or super */ null && (Serializable)) { +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); } + /** - * Abstract class for a document store. All document stores should extend - * this class. + * Determine if a value is an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ -class Docstore { -} - - -/***/ }), - -/***/ 3175: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +const isArrayBuffer = kindOfTest('ArrayBuffer'); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "bI": () => (/* binding */ BaseOutputParser) -/* harmony export */ }); -/* unused harmony exports BaseLLMOutputParser, BaseTransformOutputParser, StringOutputParser, BytesOutputParser, OutputParserException */ -/* harmony import */ var _runnable_index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(1972); /** - * Abstract base class for parsing the output of a Large Language Model - * (LLM) call. It provides methods for parsing the result of an LLM call - * and invoking the parser with a given input. + * Determine if a value is a view on an ArrayBuffer + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ -class BaseLLMOutputParser extends _runnable_index_js__WEBPACK_IMPORTED_MODULE_0__/* .Runnable */ .eq { - /** - * Parses the result of an LLM call with a given prompt. By default, it - * simply calls `parseResult`. - * @param generations The generations from an LLM call. - * @param _prompt The prompt used in the LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - /** - * Calls the parser with a given input and optional configuration options. - * If the input is a string, it creates a generation with the input as - * text and calls `parseResult`. If the input is a `BaseMessage`, it - * creates a generation with the input as a message and the content of the - * input as text, and then calls `parseResult`. - * @param input The input to the parser, which can be a string or a `BaseMessage`. - * @param options Optional configuration options. - * @returns A promise of the parsed output. - */ - async invoke(input, options) { - if (typeof input === "string") { - return this._callWithConfig(async (input) => this.parseResult([{ text: input }]), input, { ...options, runType: "parser" }); - } - else { - return this._callWithConfig(async (input) => this.parseResult([{ message: input, text: input.content }]), input, { ...options, runType: "parser" }); - } - } +function isArrayBufferView(val) { + let result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); + } + return result; } + /** - * Class to parse the output of an LLM call. + * Determine if a value is a String + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a String, otherwise false */ -class BaseOutputParser extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); - } - /** - * Return the string type key uniquely identifying this class of parser - */ - _type() { - throw new Error("_type not implemented"); - } -} +const isString = typeOfTest('string'); + /** - * Class to parse the output of an LLM call that also allows streaming inputs. + * Determine if a value is a Function + * + * @param {*} val The value to test + * @returns {boolean} True if value is a Function, otherwise false */ -class BaseTransformOutputParser extends (/* unused pure expression or super */ null && (BaseOutputParser)) { - async *_transform(inputGenerator) { - for await (const chunk of inputGenerator) { - if (typeof chunk === "string") { - yield this.parseResult([{ text: chunk }]); - } - else { - yield this.parseResult([{ message: chunk, text: chunk.content }]); - } - } - } - /** - * Transforms an asynchronous generator of input into an asynchronous - * generator of parsed output. - * @param inputGenerator An asynchronous generator of input. - * @param options A configuration object. - * @returns An asynchronous generator of parsed output. - */ - async *transform(inputGenerator, options) { - yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { - ...options, - runType: "parser", - }); - } -} +const isFunction = typeOfTest('function'); + /** - * OutputParser that parses LLMResult into the top likely string. + * Determine if a value is a Number + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Number, otherwise false */ -class StringOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "output_parser"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - static lc_name() { - return "StrOutputParser"; - } - /** - * Parses a string output from an LLM call. This method is meant to be - * implemented by subclasses to define how a string output from an LLM - * should be parsed. - * @param text The string output from an LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parse(text) { - return Promise.resolve(text); - } - getFormatInstructions() { - return ""; - } -} +const isNumber = typeOfTest('number'); + /** - * OutputParser that parses LLMResult into the top likely string and - * encodes it into bytes. + * Determine if a value is an Object + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an Object, otherwise false */ -class BytesOutputParser extends (/* unused pure expression or super */ null && (BaseTransformOutputParser)) { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "output_parser"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "textEncoder", { - enumerable: true, - configurable: true, - writable: true, - value: new TextEncoder() - }); - } - static lc_name() { - return "BytesOutputParser"; - } - parse(text) { - return Promise.resolve(this.textEncoder.encode(text)); - } - getFormatInstructions() { - return ""; - } -} +const isObject = (thing) => thing !== null && typeof thing === 'object'; + /** - * Exception that output parsers should raise to signify a parsing error. - * - * This exists to differentiate parsing errors from other code or execution errors - * that also may arise inside the output parser. OutputParserExceptions will be - * available to catch and handle in ways to fix the parsing error, while other - * errors will be raised. + * Determine if a value is a Boolean * - * @param message - The error that's being re-raised or an error message. - * @param llmOutput - String model output which is error-ing. - * @param observation - String explanation of error which can be passed to a - * model to try and remediate the issue. - * @param sendToLLM - Whether to send the observation and llm_output back to an Agent - * after an OutputParserException has been raised. This gives the underlying - * model driving the agent the context that the previous output was improperly - * structured, in the hopes that it will update the output to the correct - * format. + * @param {*} thing The value to test + * @returns {boolean} True if value is a Boolean, otherwise false */ -class OutputParserException extends Error { - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - Object.defineProperty(this, "llmOutput", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "observation", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "sendToLLM", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === undefined || llmOutput === undefined) { - throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); - } - } - } -} +const isBoolean = thing => thing === true || thing === false; +/** + * Determine if a value is a plain Object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a plain Object, otherwise false + */ +const isPlainObject = (val) => { + if (kindOf(val) !== 'object') { + return false; + } -/***/ }), + const prototype = getPrototypeOf(val); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +}; -/***/ 1972: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/** + * Determine if a value is a Date + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Date, otherwise false + */ +const isDate = kindOfTest('Date'); +/** + * Determine if a value is a File + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFile = kindOfTest('File'); -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "eq": () => (/* reexport */ base_Runnable) -}); +/** + * Determine if a value is a Blob + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Blob, otherwise false + */ +const isBlob = kindOfTest('Blob'); -// UNUSED EXPORTS: RouterRunnable, RunnableBinding, RunnableBranch, RunnableEach, RunnableLambda, RunnableMap, RunnablePassthrough, RunnableRetry, RunnableSequence, RunnableWithFallbacks - -// NAMESPACE OBJECT: ./node_modules/langchain/dist/util/fast-json-patch/src/core.js -var core_namespaceObject = {}; -__nccwpck_require__.r(core_namespaceObject); -__nccwpck_require__.d(core_namespaceObject, { - "JsonPatchError": () => (JsonPatchError), - "_areEquals": () => (_areEquals), - "applyOperation": () => (applyOperation), - "applyPatch": () => (applyPatch), - "applyReducer": () => (applyReducer), - "deepClone": () => (deepClone), - "getValueByPointer": () => (getValueByPointer), - "validate": () => (validate), - "validator": () => (validator) -}); +/** + * Determine if a value is a FileList + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a File, otherwise false + */ +const isFileList = kindOfTest('FileList'); -// EXTERNAL MODULE: ./node_modules/p-retry/index.js -var p_retry = __nccwpck_require__(2548); -// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/manager.js + 13 modules -var manager = __nccwpck_require__(6009); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/fast-json-patch/src/helpers.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed +/** + * Determine if a value is a Stream + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a Stream, otherwise false */ -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function helpers_hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys = new Array(obj.length); - for (let k = 0; k < keys.length; k++) { - keys[k] = "" + k; - } - return keys; - } - if (Object.keys) { - return Object.keys(obj); - } - let keys = []; - for (let i in obj) { - if (helpers_hasOwnProperty(obj, i)) { - keys.push(i); - } - } - return keys; -} +const isStream = (val) => isObject(val) && isFunction(val.pipe); + /** - * Deeply clone the object. - * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) - * @param {any} obj value to clone - * @return {any} cloned obj + * Determine if a value is a FormData + * + * @param {*} thing The value to test + * + * @returns {boolean} True if value is an FormData, otherwise false */ -function _deepClone(obj) { - switch (typeof obj) { - case "object": - return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 - case "undefined": - return null; //this is how JSON.stringify behaves for array items - default: - return obj; //no need to clone primitives - } -} -//3x faster than cached /^\d+$/.test(str) -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; - } - return false; - } - return true; -} +const isFormData = (thing) => { + let kind; + return thing && ( + (typeof FormData === 'function' && thing instanceof FormData) || ( + isFunction(thing.append) && ( + (kind = kindOf(thing)) === 'formdata' || + // detect form-data instance + (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') + ) + ) + ) +}; + /** - * Escapes a json pointer path - * @param path The raw pointer - * @return the Escaped path + * Determine if a value is a URLSearchParams object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} +const isURLSearchParams = kindOfTest('URLSearchParams'); + /** - * Unescapes a json pointer path - * @param path The escaped pointer - * @return The unescaped path + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * + * @returns {String} The String freed of excess whitespace */ -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -function _getPathRecursive(root, obj) { - let found; - for (let key in root) { - if (helpers_hasOwnProperty(root, key)) { - if (root[key] === obj) { - return escapePathComponent(key) + "/"; - } - else if (typeof root[key] === "object") { - found = _getPathRecursive(root[key], obj); - if (found != "") { - return escapePathComponent(key) + "/" + found; - } - } - } - } - return ""; -} -function getPath(root, obj) { - if (root === obj) { - return "/"; - } - const path = _getPathRecursive(root, obj); - if (path === "") { - throw new Error("Object not found in root"); - } - return `/${path}`; -} +const trim = (str) => str.trim ? + str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + /** - * Recursively checks whether an object has any undefined values inside. + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + * + * @param {Boolean} [allOwnKeys = false] + * @returns {any} */ -function hasUndefined(obj) { - if (obj === undefined) { - return true; - } - if (obj) { - if (Array.isArray(obj)) { - for (let i = 0, len = obj.length; i < len; i++) { - if (hasUndefined(obj[i])) { - return true; - } - } - } - else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) { - if (hasUndefined(obj[objKeys[i]])) { - return true; - } - } - } +function forEach(obj, fn, {allOwnKeys = false} = {}) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + let i; + let l; + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" - ? JSON.stringify(args[key], null, 2) - : args[key]; // pretty print - if (typeof value !== "undefined") { - messageParts.push(`${key}: ${value}`); - } + } else { + // Iterate over object keys + const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); + const len = keys.length; + let key; + + for (i = 0; i < len; i++) { + key = keys[i]; + fn.call(null, obj[key], key, obj); } - return messageParts.join("\n"); + } } -class PatchError extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { name, index, operation, tree })); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: name - }); - Object.defineProperty(this, "index", { - enumerable: true, - configurable: true, - writable: true, - value: index - }); - Object.defineProperty(this, "operation", { - enumerable: true, - configurable: true, - writable: true, - value: operation - }); - Object.defineProperty(this, "tree", { - enumerable: true, - configurable: true, - writable: true, - value: tree - }); - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree, - }); + +function findKey(obj, key) { + key = key.toLowerCase(); + const keys = Object.keys(obj); + let i = keys.length; + let _key; + while (i-- > 0) { + _key = keys[i]; + if (key === _key.toLowerCase()) { + return _key; } + } + return null; } -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/fast-json-patch/src/core.js -// @ts-nocheck +const _global = (() => { + /*eslint no-undef:0*/ + if (typeof globalThis !== "undefined") return globalThis; + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) +})(); + +const isContextDefined = (context) => !isUndefined(context) && context !== _global; -const JsonPatchError = PatchError; -const deepClone = _deepClone; -/* We use a Javascript hash to store each - function. Each hash entry (property) uses - the operation identifiers specified in rfc6902. - In this way, we can map each patch operation - to its dedicated function in efficient way. - */ -/* The operations applicable to an object */ -const objOps = { - add: function (obj, key, document) { - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function (obj, key, document) { - var removed = obj[key]; - delete obj[key]; - return { newDocument: document, removed }; - }, - replace: function (obj, key, document) { - var removed = obj[key]; - obj[key] = this.value; - return { newDocument: document, removed }; - }, - move: function (obj, key, document) { - /* in case move target overwrites an existing value, - return the removed value, this can be taxing performance-wise, - and is potentially unneeded */ - let removed = getValueByPointer(document, this.path); - if (removed) { - removed = _deepClone(removed); - } - const originalValue = applyOperation(document, { - op: "remove", - path: this.from, - }).removed; - applyOperation(document, { - op: "add", - path: this.path, - value: originalValue, - }); - return { newDocument: document, removed }; - }, - copy: function (obj, key, document) { - const valueToCopy = getValueByPointer(document, this.from); - // enforce copy by value so further operations don't affect source (see issue #177) - applyOperation(document, { - op: "add", - path: this.path, - value: _deepClone(valueToCopy), - }); - return { newDocument: document }; - }, - test: function (obj, key, document) { - return { newDocument: document, test: _areEquals(obj[key], this.value) }; - }, - _get: function (obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - }, -}; -/* The operations applicable to an array. Many are the same as for the object */ -var arrOps = { - add: function (arr, i, document) { - if (isInteger(i)) { - arr.splice(i, 0, this.value); - } - else { - // array props - arr[i] = this.value; - } - // this may be needed when using '-' in an array - return { newDocument: document, index: i }; - }, - remove: function (arr, i, document) { - var removedList = arr.splice(i, 1); - return { newDocument: document, removed: removedList[0] }; - }, - replace: function (arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { newDocument: document, removed }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get, -}; /** - * Retrieves a value from a JSON document by a JSON pointer. - * Returns the value. + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. * - * @param document The document to get the value from - * @param pointer an escaped JSON pointer - * @return The retrieved value + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * + * @returns {Object} Result of all merge properties */ -function getValueByPointer(document, pointer) { - if (pointer == "") { - return document; +function merge(/* obj1, obj2, obj3, ... */) { + const {caseless} = isContextDefined(this) && this || {}; + const result = {}; + const assignValue = (val, key) => { + const targetKey = caseless && findKey(result, key) || key; + if (isPlainObject(result[targetKey]) && isPlainObject(val)) { + result[targetKey] = merge(result[targetKey], val); + } else if (isPlainObject(val)) { + result[targetKey] = merge({}, val); + } else if (isArray(val)) { + result[targetKey] = val.slice(); + } else { + result[targetKey] = val; } - var getOriginalDestination = { op: "_get", path: pointer }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; + }; + + for (let i = 0, l = arguments.length; i < l; i++) { + arguments[i] && forEach(arguments[i], assignValue); + } + return result; } + /** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the {newDocument, result} of the operation. - * It modifies the `document` and `operation` objects - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. + * Extends object a by mutably adding to it the properties of object b. * - * @param document The document to patch - * @param operation The operation to apply - * @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. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return `{newDocument, result}` after the operation + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * + * @param {Boolean} [allOwnKeys] + * @returns {Object} The resulting value of object a */ -function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) { - if (typeof validateOperation == "function") { - validateOperation(operation, 0, document, operation.path); - } - else { - validator(operation, 0); - } - } - /* ROOT OPERATIONS */ - if (operation.path === "") { - let returnValue = { newDocument: document }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } - else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document; //document we removed - return returnValue; - } - else if (operation.op === "move" || operation.op === "copy") { - // it's a move or copy to root - returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field - if (operation.op === "move") { - // report removed item - returnValue.removed = document; - } - return returnValue; - } - else if (operation.op === "test") { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - returnValue.newDocument = document; - return returnValue; - } - else if (operation.op === "remove") { - // a remove on root - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; - } - else if (operation.op === "_get") { - operation.value = document; - return returnValue; - } - else { - /* bad operation */ - if (validateOperation) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else { - return returnValue; - } - } - } /* END ROOT OPERATIONS */ - else { - if (!mutateDocument) { - document = _deepClone(document); - } - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document; - let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift - let len = keys.length; - let existingPathFragment = undefined; - let key; - let validateFunction; - if (typeof validateOperation == "function") { - validateFunction = validateOperation; - } - else { - validateFunction = validator; - } - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) { - key = unescapePathComponent(key); - } - if (banPrototypeModifications && - (key == "__proto__" || - (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); - } - if (validateOperation) { - if (existingPathFragment === undefined) { - if (obj[key] === undefined) { - existingPathFragment = keys.slice(0, t).join("/"); - } - else if (t == len - 1) { - existingPathFragment = operation.path; - } - if (existingPathFragment !== undefined) { - validateFunction(operation, 0, document, existingPathFragment); - } - } - } - t++; - if (Array.isArray(obj)) { - if (key === "-") { - key = obj.length; - } - else { - if (validateOperation && !isInteger(key)) { - throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); - } // only parse key when it's an integer for `arr.prop` to work - else if (isInteger(key)) { - key = ~~key; - } - } - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) { - throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); - } - const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return returnValue; - } - } - else { - if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return returnValue; - } - } - obj = obj[key]; - // If we have more keys in the path, but the next value isn't a non-null object, - // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. - if (validateOperation && t < len && (!obj || typeof obj !== "object")) { - throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } - } +const extend = (a, b, thisArg, {allOwnKeys}= {}) => { + forEach(b, (val, key) => { + if (thisArg && isFunction(val)) { + a[key] = bind(val, thisArg); + } else { + a[key] = val; } -} + }, {allOwnKeys}); + return a; +}; + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * + * @returns {string} content value without BOM + */ +const stripBOM = (content) => { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +}; + +/** + * Inherit the prototype methods from one constructor into another + * @param {function} constructor + * @param {function} superConstructor + * @param {object} [props] + * @param {object} [descriptors] + * + * @returns {void} + */ +const inherits = (constructor, superConstructor, props, descriptors) => { + constructor.prototype = Object.create(superConstructor.prototype, descriptors); + constructor.prototype.constructor = constructor; + Object.defineProperty(constructor, 'super', { + value: superConstructor.prototype + }); + props && Object.assign(constructor.prototype, props); +}; + /** - * Apply a full JSON Patch array on a JSON document. - * Returns the {newDocument, result} of the patch. - * It modifies the `document` object and `patch` - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. + * Resolve object with deep prototype chain to a flat object + * @param {Object} sourceObj source object + * @param {Object} [destObj] + * @param {Function|Boolean} [filter] + * @param {Function} [propFilter] * - * @param document The document to patch - * @param patch The patch to apply - * @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. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return An array of `{newDocument, result}` after the patch + * @returns {Object} */ -function applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - } - if (!mutateDocument) { - document = _deepClone(document); - } - const results = new Array(patch.length); - for (let i = 0, length = patch.length; i < length; i++) { - // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; // in case root was replaced +const toFlatObject = (sourceObj, destObj, filter, propFilter) => { + let props; + let i; + let prop; + const merged = {}; + + destObj = destObj || {}; + // eslint-disable-next-line no-eq-null,eqeqeq + if (sourceObj == null) return destObj; + + do { + props = Object.getOwnPropertyNames(sourceObj); + i = props.length; + while (i-- > 0) { + prop = props[i]; + if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { + destObj[prop] = sourceObj[prop]; + merged[prop] = true; + } } - results.newDocument = document; - return results; -} + sourceObj = filter !== false && getPrototypeOf(sourceObj); + } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); + + return destObj; +}; + /** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the updated document. - * Suitable as a reducer. + * Determines whether a string ends with the characters of a specified string * - * @param document The document to patch - * @param operation The operation to apply - * @return The updated document + * @param {String} str + * @param {String} searchString + * @param {Number} [position= 0] + * + * @returns {boolean} */ -function applyReducer(document, operation, index) { - const operationResult = applyOperation(document, operation); - if (operationResult.test === false) { - // failed test - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return operationResult.newDocument; -} +const endsWith = (str, searchString, position) => { + str = String(str); + if (position === undefined || position > str.length) { + position = str.length; + } + position -= searchString.length; + const lastIndex = str.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; +}; + + /** - * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. - * @param {object} operation - operation object (patch) - * @param {number} index - index of operation in the sequence - * @param {object} [document] - object where the operation is supposed to be applied - * @param {string} [existingPathFragment] - comes along with `document` + * Returns new array from array like object or null if failed + * + * @param {*} [thing] + * + * @returns {?Array} */ -function validator(operation, index, document, existingPathFragment) { - if (typeof operation !== "object" || - operation === null || - Array.isArray(operation)) { - throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); - } - else if (!objOps[operation.op]) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else if (typeof operation.path !== "string") { - throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); - } - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { - // paths that aren't empty string should start with "/" - throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); +const toArray = (thing) => { + if (!thing) return null; + if (isArray(thing)) return thing; + let i = thing.length; + if (!isNumber(i)) return null; + const arr = new Array(i); + while (i-- > 0) { + arr[i] = thing[i]; + } + return arr; +}; + +/** + * Checking if the Uint8Array exists and if it does, it returns a function that checks if the + * thing passed in is an instance of Uint8Array + * + * @param {TypedArray} + * + * @returns {Array} + */ +// eslint-disable-next-line func-names +const isTypedArray = (TypedArray => { + // eslint-disable-next-line func-names + return thing => { + return TypedArray && thing instanceof TypedArray; + }; +})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); + +/** + * For each entry in the object, call the function with the key and value. + * + * @param {Object} obj - The object to iterate over. + * @param {Function} fn - The function to call for each entry. + * + * @returns {void} + */ +const forEachEntry = (obj, fn) => { + const generator = obj && obj[Symbol.iterator]; + + const iterator = generator.call(obj); + + let result; + + while ((result = iterator.next()) && !result.done) { + const pair = result.value; + fn.call(obj, pair[0], pair[1]); + } +}; + +/** + * It takes a regular expression and a string, and returns an array of all the matches + * + * @param {string} regExp - The regular expression to match against. + * @param {string} str - The string to search. + * + * @returns {Array} + */ +const matchAll = (regExp, str) => { + let matches; + const arr = []; + + while ((matches = regExp.exec(str)) !== null) { + arr.push(matches); + } + + return arr; +}; + +/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ +const isHTMLForm = kindOfTest('HTMLFormElement'); + +const toCamelCase = str => { + return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, + function replacer(m, p1, p2) { + return p1.toUpperCase() + p2; } - else if ((operation.op === "move" || operation.op === "copy") && - typeof operation.from !== "string") { - throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + ); +}; + +/* Creating a function that will check if an object has a property. */ +const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + +/** + * Determine if a value is a RegExp object + * + * @param {*} val The value to test + * + * @returns {boolean} True if value is a RegExp object, otherwise false + */ +const isRegExp = kindOfTest('RegExp'); + +const reduceDescriptors = (obj, reducer) => { + const descriptors = Object.getOwnPropertyDescriptors(obj); + const reducedDescriptors = {}; + + forEach(descriptors, (descriptor, name) => { + let ret; + if ((ret = reducer(descriptor, name, obj)) !== false) { + reducedDescriptors[name] = ret || descriptor; } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - operation.value === undefined) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + }); + + Object.defineProperties(obj, reducedDescriptors); +}; + +/** + * Makes all methods read-only + * @param {Object} obj + */ + +const freezeMethods = (obj) => { + reduceDescriptors(obj, (descriptor, name) => { + // skip restricted props in strict mode + if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { + return false; } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - hasUndefined(operation.value)) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + + const value = obj[name]; + + if (!isFunction(value)) return; + + descriptor.enumerable = false; + + if ('writable' in descriptor) { + descriptor.writable = false; + return; } - else if (document) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { - throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); - } - } - else if (operation.op === "replace" || - operation.op === "remove" || - operation.op === "_get") { - if (operation.path !== existingPathFragment) { - throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } - } - else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: undefined, - }; - var error = validate([existingValue], document); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { - throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); - } - } + + if (!descriptor.set) { + descriptor.set = () => { + throw Error('Can not rewrite read-only method \'' + name + '\''); + }; } -} + }); +}; + +const toObjectSet = (arrayOrString, delimiter) => { + const obj = {}; + + const define = (arr) => { + arr.forEach(value => { + obj[value] = true; + }); + }; + + isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + + return obj; +}; + +const noop = () => {}; + +const toFiniteNumber = (value, defaultValue) => { + value = +value; + return Number.isFinite(value) ? value : defaultValue; +}; + +const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; + +const DIGIT = '0123456789'; + +const ALPHABET = { + DIGIT, + ALPHA, + ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT +}; + +const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { + let str = ''; + const {length} = alphabet; + while (size--) { + str += alphabet[Math.random() * length|0]; + } + + return str; +}; + /** - * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. - * If error is encountered, returns a JsonPatchError object - * @param sequence - * @param document - * @returns {JsonPatchError|undefined} + * If the thing is a FormData object, return true, otherwise return false. + * + * @param {unknown} thing - The thing to check. + * + * @returns {boolean} */ -function validate(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (document) { - //clone document and sequence so that we can safely try applying operations - applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); - } - else { - externalValidator = externalValidator || validator; - for (var i = 0; i < sequence.length; i++) { - externalValidator(sequence[i], i, document, undefined); - } - } - } - catch (e) { - if (e instanceof JsonPatchError) { - return e; - } - else { - throw e; - } - } +function isSpecCompliantForm(thing) { + return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); } -// based on https://github.com/epoberezkin/fast-deep-equal -// MIT License -// Copyright (c) 2017 Evgeny Poberezkin -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -function _areEquals(a, b) { - if (a === b) - return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) - return false; - for (i = length; i-- !== 0;) - if (!_areEquals(a[i], b[i])) - return false; - return true; - } - if (arrA != arrB) - return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length; i-- !== 0;) - if (!b.hasOwnProperty(keys[i])) - return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) - return false; - } - return true; + +const toJSONObject = (obj) => { + const stack = new Array(10); + + const visit = (source, i) => { + + if (isObject(source)) { + if (stack.indexOf(source) >= 0) { + return; + } + + if(!('toJSON' in source)) { + stack[i] = source; + const target = isArray(source) ? [] : {}; + + forEach(source, (value, key) => { + const reducedValue = visit(value, i + 1); + !isUndefined(reducedValue) && (target[key] = reducedValue); + }); + + stack[i] = undefined; + + return target; + } } - return a !== a && b !== b; + + return source; + }; + + return visit(obj, 0); +}; + +const isAsyncFn = kindOfTest('AsyncFunction'); + +const isThenable = (thing) => + thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); + +const utils = { + isArray, + isArrayBuffer, + isBuffer, + isFormData, + isArrayBufferView, + isString, + isNumber, + isBoolean, + isObject, + isPlainObject, + isUndefined, + isDate, + isFile, + isBlob, + isRegExp, + isFunction, + isStream, + isURLSearchParams, + isTypedArray, + isFileList, + forEach, + merge, + extend, + trim, + stripBOM, + inherits, + toFlatObject, + kindOf, + kindOfTest, + endsWith, + toArray, + forEachEntry, + matchAll, + isHTMLForm, + hasOwnProperty, + hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection + reduceDescriptors, + freezeMethods, + toObjectSet, + toCamelCase, + noop, + toFiniteNumber, + findKey, + global: _global, + isContextDefined, + ALPHABET, + generateString, + isSpecCompliantForm, + toJSONObject, + isAsyncFn, + isThenable +}; + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [config] The config. + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * + * @returns {Error} The created error. + */ +function AxiosError(message, code, config, request, response) { + Error.call(this); + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = (new Error()).stack; + } + + this.message = message; + this.name = 'AxiosError'; + code && (this.code = code); + config && (this.config = config); + request && (this.request = request); + response && (this.response = response); } -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/fast-json-patch/index.js +utils.inherits(AxiosError, Error, { + toJSON: function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: utils.toJSONObject(this.config), + code: this.code, + status: this.response && this.response.status ? this.response.status : null + }; + } +}); + +const prototype$1 = AxiosError.prototype; +const descriptors = {}; +[ + 'ERR_BAD_OPTION_VALUE', + 'ERR_BAD_OPTION', + 'ECONNABORTED', + 'ETIMEDOUT', + 'ERR_NETWORK', + 'ERR_FR_TOO_MANY_REDIRECTS', + 'ERR_DEPRECATED', + 'ERR_BAD_RESPONSE', + 'ERR_BAD_REQUEST', + 'ERR_CANCELED', + 'ERR_NOT_SUPPORT', + 'ERR_INVALID_URL' +// eslint-disable-next-line func-names +].forEach(code => { + descriptors[code] = {value: code}; +}); -/** - * Default export for backwards compat - */ +Object.defineProperties(AxiosError, descriptors); +Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); +// eslint-disable-next-line func-names +AxiosError.from = (error, code, config, request, response, customProps) => { + const axiosError = Object.create(prototype$1); -/* harmony default export */ const fast_json_patch = ({ - ...core_namespaceObject, - // ...duplex, - JsonPatchError: PatchError, - deepClone: _deepClone, - escapePathComponent: escapePathComponent, - unescapePathComponent: unescapePathComponent, -}); + utils.toFlatObject(error, axiosError, function filter(obj) { + return obj !== Error.prototype; + }, prop => { + return prop !== 'isAxiosError'; + }); -// EXTERNAL MODULE: ./node_modules/langchain/dist/callbacks/handlers/tracer.js -var tracer = __nccwpck_require__(8763); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/stream.js -/* - * Support async iterator syntax for ReadableStreams in all environments. - * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -class IterableReadableStream extends ReadableStream { - constructor() { - super(...arguments); - Object.defineProperty(this, "reader", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - ensureReader() { - if (!this.reader) { - this.reader = this.getReader(); - } - } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) - this.reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - this.reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - } - async return() { - this.ensureReader(); - const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet - this.reader.releaseLock(); // release lock first - await cancelPromise; // now await it - return { done: true, value: undefined }; // This cast fixes TS typing, and convention is to ignore chunk value anyway - } - [Symbol.asyncIterator]() { - return this; - } - static fromReadableStream(stream) { - // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream - const reader = stream.getReader(); - return new IterableReadableStream({ - start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - // When no more data needs to be consumed, close the stream - if (done) { - controller.close(); - return; - } - // Enqueue the next data chunk into our target stream - controller.enqueue(value); - return pump(); - }); - } - }, - }); - } - static fromAsyncGenerator(generator) { - return new IterableReadableStream({ - async pull(controller) { - const { value, done } = await generator.next(); - if (done) { - controller.close(); - } - else if (value) { - controller.enqueue(value); - } - }, - }); - } -} + AxiosError.call(axiosError, error.message, code, config, request, response); + + axiosError.cause = error; -;// CONCATENATED MODULE: ./node_modules/langchain/dist/callbacks/handlers/log_stream.js + axiosError.name = error.name; + customProps && Object.assign(axiosError, customProps); + return axiosError; +}; /** - * List of jsonpatch JSONPatchOperations, which describe how to create the run state - * from an empty dict. This is the minimal representation of the log, designed to - * be serialized as JSON and sent over the wire to reconstruct the log on the other - * side. Reconstruction of the state can be done with any jsonpatch-compliant library, - * see https://jsonpatch.com for more information. + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} */ -class RunLogPatch { - constructor(fields) { - Object.defineProperty(this, "ops", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.ops = fields.ops; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch({}, ops); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunLog({ - ops, - state: states[states.length - 1].newDocument, - }); - } +function isVisitable(thing) { + return utils.isPlainObject(thing) || utils.isArray(thing); } -class RunLog extends RunLogPatch { - constructor(fields) { - super(fields); - Object.defineProperty(this, "state", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.state = fields.state; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch(this.state, other.ops); - return new RunLog({ ops, state: states[states.length - 1].newDocument }); - } + +/** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ +function removeBrackets(key) { + return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; } + /** - * Class that extends the `BaseTracer` class from the - * `langchain.callbacks.tracers.base` module. It represents a callback - * handler that logs the execution of runs and emits `RunLog` instances to a - * `RunLogStream`. + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. */ -class LogStreamCallbackHandler extends tracer/* BaseTracer */.Z { - constructor(fields) { - super(fields); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "indexMap", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "log_stream_tracer" - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) { - // This is a legacy method only called once for an entire run tree - // and is therefore not useful here - } - _includeRun(run) { - if (run.parent_run_id === undefined) { - return false; - } - const runTags = run.tags ?? []; - let include = this.includeNames === undefined && - this.includeTags === undefined && - this.includeTypes === undefined; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(run.name); - } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(run.run_type); - } - if (this.includeTags !== undefined) { - include = - include || - runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; - } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(run.name); - } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(run.run_type); - } - if (this.excludeTags !== undefined) { - include = - include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - } - return include; +function renderKey(path, key, dots) { + if (!path) return key; + return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign + token = removeBrackets(token); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); +} + +/** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ +function isFlatArray(arr) { + return utils.isArray(arr) && !arr.some(isVisitable); +} + +const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { + return /^is[A-Z]/.test(prop); +}); + +/** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + +/** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ +function toFormData(obj, formData, options) { + if (!utils.isObject(obj)) { + throw new TypeError('target must be an object'); + } + + // eslint-disable-next-line no-param-reassign + formData = formData || new (FormData__default["default"] || FormData)(); + + // eslint-disable-next-line no-param-reassign + options = utils.toFlatObject(options, { + metaTokens: true, + dots: false, + indexes: false + }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq + return !utils.isUndefined(source[option]); + }); + + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define + const visitor = options.visitor || defaultVisitor; + const dots = options.dots; + const indexes = options.indexes; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; + const useBlob = _Blob && utils.isSpecCompliantForm(formData); + + if (!utils.isFunction(visitor)) { + throw new TypeError('visitor must be a function'); + } + + function convertValue(value) { + if (value === null) return ''; + + if (utils.isDate(value)) { + return value.toISOString(); } - async onRunCreate(run) { - if (run.parent_run_id === undefined) { - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "replace", - path: "", - value: { - id: run.id, - streamed_output: [], - final_output: undefined, - logs: [], - }, - }, - ], - })); - } - if (!this._includeRun(run)) { - return; - } - this.indexMap[run.id] = Math.max(...Object.values(this.indexMap), -1) + 1; - const logEntry = { - id: run.id, - name: run.name, - type: run.run_type, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - start_time: new Date(run.start_time).toISOString(), - streamed_output_str: [], - final_output: undefined, - end_time: undefined, - }; - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${this.indexMap[run.id]}`, - value: logEntry, - }, - ], - })); + + if (!useBlob && utils.isBlob(value)) { + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); } - async onRunUpdate(run) { - try { - const index = this.indexMap[run.id]; - if (index === undefined) { - return; - } - const ops = [ - { - op: "add", - path: `/logs/${index}/final_output`, - value: run.outputs, - }, - ]; - if (run.end_time !== undefined) { - ops.push({ - op: "add", - path: `/logs/${index}/end_time`, - value: new Date(run.end_time).toISOString(), - }); - } - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); - } - finally { - if (run.parent_run_id === undefined) { - const patch = new RunLogPatch({ - ops: [ - { - op: "replace", - path: "/final_output", - value: run.outputs, - }, - ], - }); - await this.writer.write(patch); - if (this.autoClose) { - await this.writer.close(); - } - } - } + + if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } - async onLLMNewToken(run, token) { - const index = this.indexMap[run.id]; - if (index === undefined) { - return; - } - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${index}/streamed_output_str/-`, - value: token, - }, - ], + + return value; + } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ + function defaultVisitor(value, key, path) { + let arr = value; + + if (value && !path && typeof value === 'object') { + if (utils.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign + key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign + value = JSON.stringify(value); + } else if ( + (utils.isArray(value) && isFlatArray(value)) || + ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign + key = removeBrackets(key); + + arr.forEach(function each(el, index) { + !(utils.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); }); - await this.writer.write(patch); + return false; + } } -} -// EXTERNAL MODULE: ./node_modules/langchain/dist/load/serializable.js + 1 modules -var serializable = __nccwpck_require__(4432); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/config.js + if (isVisitable(value)) { + return true; + } -async function getCallbackMangerForConfig(config) { - return manager/* CallbackManager.configure */.Ye.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); -} + formData.append(renderKey(path, key, dots), convertValue(value)); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/async_caller.js -var async_caller = __nccwpck_require__(2723); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/base.js + return false; + } + const stack = []; + const exposedHelpers = Object.assign(predicates, { + defaultVisitor, + convertValue, + isVisitable + }); + function build(value, path) { + if (utils.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { + throw Error('Circular reference detected in ' + path.join('.')); + } + stack.push(value); + utils.forEach(value, function each(el, key) { + const result = !(utils.isUndefined(el) || el === null) && visitor.call( + formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers + ); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" - ? value - : { [defaultKey]: value }; -} -/** - * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or - * transformed. - */ -class base_Runnable extends serializable/* Serializable */.i { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_runnable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - /** - * Bind arguments to a Runnable, returning a new Runnable. - * @param kwargs - * @returns A new RunnableBinding that, when invoked, will apply the bound args. - */ - bind(kwargs) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ bound: this, kwargs, config: {} }); - } - /** - * Return a new Runnable that maps a list of inputs to a list of outputs, - * by calling invoke() with each input. - */ - map() { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableEach({ bound: this }); - } - /** - * Add retry logic to an existing runnable. - * @param kwargs - * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. - */ - withRetry(fields) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields, - }); - } - /** - * Bind config to a Runnable, returning a new Runnable. - * @param config New configuration parameters to attach to the new runnable. - * @returns A new RunnableBinding with a config matching what's passed. - */ - withConfig(config) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ - bound: this, - config, - kwargs: {}, - }); - } - /** - * Create a new runnable from the current one that will try invoking - * other passed fallback runnables if the initial invocation fails. - * @param fields.fallbacks Other runnables to call if the runnable errors. - * @returns A new RunnableWithFallbacks. - */ - withFallbacks(fields) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableWithFallbacks({ - runnable: this, - fallbacks: fields.fallbacks, - }); - } - _getOptionsList(options, length = 0) { - if (Array.isArray(options)) { - if (options.length !== length) { - throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); - } - return options; - } - return Array.from({ length }, () => options); - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const caller = new async_caller/* AsyncCaller */.L({ - maxConcurrency: batchOptions?.maxConcurrency, - onFailedAttempt: (e) => { - throw e; - }, - }); - const batchCalls = inputs.map((input, i) => caller.call(async () => { - try { - const result = await this.invoke(input, configList[i]); - return result; - } - catch (e) { - if (batchOptions?.returnExceptions) { - return e; - } - throw e; - } - })); - return Promise.all(batchCalls); - } - /** - * Default streaming implementation. - * Subclasses should override this method if they support streaming output. - * @param input - * @param options - */ - async *_streamIterator(input, options) { - yield this.invoke(input, options); - } - /** - * Stream output in chunks. - * @param input - * @param options - * @returns A readable stream that is also an iterable. - */ - async stream(input, options) { - return IterableReadableStream.fromAsyncGenerator(this._streamIterator(input, options)); - } - _separateRunnableConfigFromCallOptions(options = {}) { - const runnableConfig = { - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - }; - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - return [runnableConfig, callOptions]; - } - async _callWithConfig(func, input, options) { - const callbackManager_ = await getCallbackMangerForConfig(options); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType); - let output; - try { - output = await func.bind(this)(input, options, runManager); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(_coerceToDict(output, "output")); - return output; - } - /** - * Internal method that handles batching and configuration for a runnable - * It takes a function, input values, and optional configuration, and - * returns a promise that resolves to the output values. - * @param func The function to be executed for each input value. - * @param input The input values to be processed. - * @param config Optional configuration for the function execution. - * @returns A promise that resolves to the output values. - */ - async _batchWithConfig(func, inputs, options, batchOptions) { - const configs = this._getOptionsList((options ?? {}), inputs.length); - const callbackManagers = await Promise.all(configs.map(getCallbackMangerForConfig)); - const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input")))); - let outputs; - try { - outputs = await func(inputs, configs, runManagers, batchOptions); - } - catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict(outputs, "output")))); - return outputs; - } - /** - * Helper method to transform an Iterator of Input values into an Iterator of - * Output values, with callbacks. - * Use this to implement `stream()` or `transform()` in Runnable subclasses. - */ - async *_transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const callbackManager_ = await getCallbackMangerForConfig(options); - let runManager; - const serializedRepresentation = this.toJSON(); - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (!runManager) { - // Start the run manager AFTER the iterator starts to preserve - // tracing order - runManager = await callbackManager_?.handleChainStart(serializedRepresentation, { input: "" }, undefined, options?.runType); - } - if (finalInputSupported) { - if (finalInput === undefined) { - finalInput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalInput = finalInput.concat(chunk); - } - catch { - finalInput = undefined; - finalInputSupported = false; - } - } - } - yield chunk; - } - } - const wrappedInputGenerator = wrapInputForTracing(); - try { - const outputIterator = transformer(wrappedInputGenerator, runManager, options); - for await (const chunk of outputIterator) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = finalOutput.concat(chunk); - } - catch { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } - } - } - catch (e) { - await runManager?.handleChainError(e, undefined, undefined, undefined, { - inputs: _coerceToDict(finalInput, "input"), - }); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict(finalInput, "input") }); - } - _patchConfig(config = {}, callbackManager = undefined) { - return { ...config, callbacks: callbackManager }; - } - /** - * Create a new runnable sequence that runs each individual runnable in series, - * piping the output of one runnable into another runnable or runnable-like. - * @param coerceable A runnable, function, or object whose values are functions or runnables. - * @returns A new runnable sequence. - */ - pipe(coerceable) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableSequence({ - first: this, - last: base_coerceToRunnable(coerceable), - }); - } - /** - * Default implementation of transform, which buffers input and then calls stream. - * Subclasses should override this method if they can start producing output while - * input is still being generated. - * @param generator - * @param options - */ - async *transform(generator, options) { - let finalChunk; - for await (const chunk of generator) { - if (finalChunk === undefined) { - finalChunk = chunk; - } - else { - // Make a best effort to gather, for any type that supports concat. - // This method should throw an error if gathering fails. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalChunk = finalChunk.concat(chunk); - } - } - yield* this._streamIterator(finalChunk, options); - } - /** - * Stream all output from a runnable, as reported to the callback system. - * This includes all inner runs of LLMs, Retrievers, Tools, etc. - * Output is streamed as Log objects, which include a list of - * jsonpatch ops that describe how the state of the run has changed in each - * step, and the final state of the run. - * The jsonpatch ops can be applied in order to construct state. - * @param input - * @param options - * @param streamOptions - */ - async *streamLog(input, options, streamOptions) { - const stream = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - }); - const config = options ?? {}; - const { callbacks } = config; - if (callbacks === undefined) { - config.callbacks = [stream]; - } - else if (Array.isArray(callbacks)) { - config.callbacks = callbacks.concat([stream]); - } - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.inheritableHandlers.push(stream); - config.callbacks = copiedCallbacks; - } - const runnableStream = await this.stream(input, config); - async function consumeRunnableStream() { - try { - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: "/streamed_output/-", - value: chunk, - }, - ], - }); - await stream.writer.write(patch); - } - } - finally { - await stream.writer.close(); - } - } - const runnableStreamPromise = consumeRunnableStream(); - try { - for await (const log of stream) { - yield log; - } - } - finally { - await runnableStreamPromise; - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnable(thing) { - return thing.lc_runnable; - } + if (result === true) { + build(el, path ? path.concat(key) : [key]); + } + }); + + stack.pop(); + } + + if (!utils.isObject(obj)) { + throw new TypeError('data must be an object'); + } + + build(obj); + + return formData; } + /** - * A runnable that delegates calls to another runnable with a set of kwargs. - */ -class RunnableBinding extends base_Runnable { - static lc_name() { - return "RunnableBinding"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _mergeConfig(options) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const copy = { ...this.config }; - if (options) { - for (const key of Object.keys(options)) { - if (key === "metadata") { - copy[key] = { ...copy[key], ...options[key] }; - } - else if (key === "tags") { - copy[key] = (copy[key] ?? []).concat(options[key] ?? []); - } - else { - copy[key] = options[key] ?? copy[key]; - } - } - } - return copy; - } - bind(kwargs) { - return this.constructor({ - bound: this.bound, - kwargs: { ...this.kwargs, ...kwargs }, - config: this.config, - }); - } - withConfig(config) { - return this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { ...this.config, ...config }, - }); - } - withRetry(fields) { - return this.constructor({ - bound: this.bound.withRetry(fields), - kwargs: this.kwargs, - config: this.config, - }); - } - async invoke(input, options) { - return this.bound.invoke(input, this._mergeConfig({ ...options, ...this.kwargs })); - } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) - ? options.map((individualOption) => this._mergeConfig({ - ...individualOption, - ...this.kwargs, - })) - : this._mergeConfig({ ...options, ...this.kwargs }); - return this.bound.batch(inputs, mergedOptions, batchOptions); - } - async *_streamIterator(input, options) { - yield* this.bound._streamIterator(input, this._mergeConfig({ ...options, ...this.kwargs })); - } - async stream(input, options) { - return this.bound.stream(input, this._mergeConfig({ ...options, ...this.kwargs })); - } - async *transform( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - generator, options) { - yield* this.bound.transform(generator, this._mergeConfig({ ...options, ...this.kwargs })); - } - static isRunnableBinding( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - thing - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ) { - return thing.bound && base_Runnable.isRunnable(thing.bound); - } + * It encodes a string by replacing all characters that are not in the unreserved set with + * their percent-encoded equivalents + * + * @param {string} str - The string to encode. + * + * @returns {string} The encoded string. + */ +function encode$1(str) { + const charMap = { + '!': '%21', + "'": '%27', + '(': '%28', + ')': '%29', + '~': '%7E', + '%20': '+', + '%00': '\x00' + }; + return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { + return charMap[match]; + }); } + /** - * A runnable that delegates calls to another runnable - * with each element of the input sequence. + * It takes a params object and converts it to a FormData object + * + * @param {Object} params - The parameters to be converted to a FormData object. + * @param {Object} options - The options object passed to the Axios constructor. + * + * @returns {void} */ -class RunnableEach extends base_Runnable { - static lc_name() { - return "RunnableEach"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - } - /** - * Binds the runnable with the specified arguments. - * @param args The arguments to bind the runnable with. - * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. - */ - bind(kwargs) { - return new RunnableEach({ - bound: this.bound.bind(kwargs), - }); - } - /** - * Invokes the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(inputs, config) { - return this._callWithConfig(this._invoke, inputs, config); - } - /** - * A helper method that is used to invoke the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async _invoke(inputs, config, runManager) { - return this.bound.batch(inputs, this._patchConfig(config, runManager?.getChild())); - } +function AxiosURLSearchParams(params, options) { + this._pairs = []; + + params && toFormData(params, this, options); } + +const prototype = AxiosURLSearchParams.prototype; + +prototype.append = function append(name, value) { + this._pairs.push([name, value]); +}; + +prototype.toString = function toString(encoder) { + const _encode = encoder ? function(value) { + return encoder.call(this, value, encode$1); + } : encode$1; + + return this._pairs.map(function each(pair) { + return _encode(pair[0]) + '=' + _encode(pair[1]); + }, '').join('&'); +}; + /** - * Base class for runnables that can be retried a - * specified number of times. + * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their + * URI encoded counterparts + * + * @param {string} val The value to be encoded. + * + * @returns {string} The encoded value. */ -class RunnableRetry extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "maxAttemptNumber", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: () => { } - }); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; - } - _patchConfigForRetry(attempt, config, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; - return this._patchConfig(config, runManager?.getChild(tag)); - } - async _invoke(input, config, runManager) { - return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { - onFailedAttempt: this.onFailedAttempt, - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true, - }); - } - /** - * Method that invokes the runnable with the specified input, run manager, - * and config. It handles the retry logic by catching any errors and - * recursively invoking itself with the updated config for the next retry - * attempt. - * @param input The input for the runnable. - * @param runManager The run manager for the runnable. - * @param config The config for the runnable. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(input, config) { - return this._callWithConfig(this._invoke, input, config); - } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; - try { - await p_retry(async (attemptNumber) => { - const remainingIndexes = inputs - .map((_, i) => i) - .filter((i) => resultsMap[i.toString()] === undefined || - // eslint-disable-next-line no-instanceof/no-instanceof - resultsMap[i.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i) => inputs[i]); - const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true, - }); - let firstException; - for (let i = 0; i < results.length; i += 1) { - const result = results[i]; - const resultMapIndex = remainingIndexes[i]; - // eslint-disable-next-line no-instanceof/no-instanceof - if (result instanceof Error) { - if (firstException === undefined) { - firstException = result; - } - } - resultsMap[resultMapIndex.toString()] = result; - } - if (firstException) { - throw firstException; - } - return results; - }, { - onFailedAttempt: this.onFailedAttempt, - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true, - }); - } - catch (e) { - if (batchOptions?.returnExceptions !== true) { - throw e; - } - } - return Object.keys(resultsMap) - .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) - .map((key) => resultsMap[parseInt(key, 10)]); - } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); - } +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); } + /** - * A sequence of runnables, where the output of each is the input of the next. + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @param {?object} options + * + * @returns {string} The formatted url */ -class RunnableSequence extends base_Runnable { - static lc_name() { - return "RunnableSequence"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "first", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "middle", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "last", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - } - get steps() { - return [this.first, ...this.middle, this.last]; - } - async invoke(input, options) { - const callbackManager_ = await getCallbackMangerForConfig(options); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input")); - let nextStepInput = input; - let finalOutput; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0; i < initialSteps.length; i += 1) { - const step = initialSteps[i]; - nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${i + 1}`))); - } - // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here - finalOutput = await this.last.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${this.steps.length}`))); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output")); - return finalOutput; - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackMangerForConfig)); - const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input")))); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let nextStepInputs = inputs; - let finalOutputs; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0; i < initialSteps.length; i += 1) { - const step = initialSteps[i]; - nextStepInputs = await step.batch(nextStepInputs, runManagers.map((runManager, j) => this._patchConfig(configList[j], runManager?.getChild(`seq:step:${i + 1}`))), batchOptions); - } - finalOutputs = await this.last.batch(nextStepInputs, runManagers.map((runManager) => this._patchConfig(configList[this.steps.length - 1], runManager?.getChild(`seq:step:${this.steps.length}`))), batchOptions); - } - catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(finalOutputs[i], "output")))); - return finalOutputs; - } - async *_streamIterator(input, options) { - const callbackManager_ = await getCallbackMangerForConfig(options); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input")); - let nextStepInput = input; - const steps = [this.first, ...this.middle, this.last]; - // Find the index of the last runnable in the sequence that doesn't have an overridden .transform() method - // and start streaming from there - const streamingStartStepIndex = Math.min(steps.length - 1, steps.length - - [...steps].reverse().findIndex((step) => { - const isDefaultImplementation = step.transform === base_Runnable.prototype.transform; - const boundRunnableIsDefaultImplementation = RunnableBinding.isRunnableBinding(step) && - step.bound?.transform === base_Runnable.prototype.transform; - return (isDefaultImplementation || boundRunnableIsDefaultImplementation); - }) - - 1); - try { - const invokeSteps = steps.slice(0, streamingStartStepIndex); - for (let i = 0; i < invokeSteps.length; i += 1) { - const step = invokeSteps[i]; - nextStepInput = await step.invoke(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${i + 1}`))); - } - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - let concatSupported = true; - let finalOutput; - try { - let finalGenerator = await steps[streamingStartStepIndex]._streamIterator(nextStepInput, this._patchConfig(options, runManager?.getChild(`seq:step:${streamingStartStepIndex + 1}`))); - const finalSteps = steps.slice(streamingStartStepIndex + 1); - for (let i = 0; i < finalSteps.length; i += 1) { - const step = finalSteps[i]; - finalGenerator = await step.transform(finalGenerator, this._patchConfig(options, runManager?.getChild(`seq:step:${streamingStartStepIndex + i + 2}`))); - } - for await (const chunk of finalGenerator) { - yield chunk; - if (concatSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = finalOutput.concat(chunk); - } - catch (e) { - finalOutput = undefined; - concatSupported = false; - } - } - } - } - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(_coerceToDict(finalOutput, "output")); +function buildURL(url, params, options) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + const _encode = options && options.encode || encode; + + const serializeFn = options && options.serialize; + + let serializedParams; + + if (serializeFn) { + serializedParams = serializeFn(params, options); + } else { + serializedParams = utils.isURLSearchParams(params) ? + params.toString() : + new AxiosURLSearchParams(params, options).toString(_encode); + } + + if (serializedParams) { + const hashmarkIndex = url.indexOf("#"); + + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); } - pipe(coerceable) { - if (RunnableSequence.isRunnableSequence(coerceable)) { - return new RunnableSequence({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle, - ]), - last: coerceable.last, - }); - } - else { - return new RunnableSequence({ - first: this.first, - middle: [...this.middle, this.last], - last: base_coerceToRunnable(coerceable), - }); - } + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +} + +class InterceptorManager { + constructor() { + this.handlers = []; + } + + /** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ + use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled, + rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; + } + + /** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + * + * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise + */ + eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && base_Runnable.isRunnable(thing); + } + + /** + * Clear all interceptors from the stack + * + * @returns {void} + */ + clear() { + if (this.handlers) { + this.handlers = []; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from([first, ...runnables]) { - return new RunnableSequence({ - first: base_coerceToRunnable(first), - middle: runnables.slice(0, -1).map(base_coerceToRunnable), - last: base_coerceToRunnable(runnables[runnables.length - 1]), - }); + } + + /** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + * + * @returns {void} + */ + forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); + } +} + +const InterceptorManager$1 = InterceptorManager; + +const transitionalDefaults = { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false +}; + +const URLSearchParams = url__default["default"].URLSearchParams; + +const platform = { + isNode: true, + classes: { + URLSearchParams, + FormData: FormData__default["default"], + Blob: typeof Blob !== 'undefined' && Blob || null + }, + protocols: [ 'http', 'https', 'file', 'data' ] +}; + +function toURLEncodedForm(data, options) { + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ + visitor: function(value, key, path, helpers) { + if (utils.isBuffer(value)) { + this.append(key, value.toString('base64')); + return false; + } + + return helpers.defaultVisitor.apply(this, arguments); } + }, options)); +} + +/** + * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] + * + * @param {string} name - The name of the property to get. + * + * @returns An array of strings. + */ +function parsePropPath(name) { + // foo[x][y][z] + // foo.x.y.z + // foo-x-y-z + // foo x y z + return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { + return match[0] === '[]' ? '' : match[1] || match[0]; + }); } + /** - * A runnable that runs a mapping of runnables in parallel, - * and returns a mapping of their outputs. + * Convert an array to an object. + * + * @param {Array} arr - The array to convert to an object. + * + * @returns An object with the same keys and values as the array. */ -class RunnableMap extends base_Runnable { - static lc_name() { - return "RunnableMap"; +function arrayToObject(arr) { + const obj = {}; + const keys = Object.keys(arr); + let i; + const len = keys.length; + let key; + for (i = 0; i < len; i++) { + key = keys[i]; + obj[key] = arr[key]; + } + return obj; +} + +/** + * It takes a FormData object and returns a JavaScript object + * + * @param {string} formData The FormData object to convert to JSON. + * + * @returns {Object | null} The converted object. + */ +function formDataToJSON(formData) { + function buildPath(path, value, target, index) { + let name = path[index++]; + const isNumericKey = Number.isFinite(+name); + const isLast = index >= path.length; + name = !name && utils.isArray(target) ? target.length : name; + + if (isLast) { + if (utils.hasOwnProp(target, name)) { + target[name] = [target[name], value]; + } else { + target[name] = value; + } + + return !isNumericKey; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "steps", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) { - this.steps[key] = base_coerceToRunnable(value); - } + + if (!target[name] || !utils.isObject(target[name])) { + target[name] = []; } - async invoke(input, options - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ) { - const callbackManager_ = await getCallbackMangerForConfig(options); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { - input, - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const output = {}; - try { - await Promise.all(Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, this._patchConfig(options, runManager?.getChild(key))); - })); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(output); - return output; + + const result = buildPath(path, value, target[name], index); + + if (result && utils.isArray(target[name])) { + target[name] = arrayToObject(target[name]); } + + return !isNumericKey; + } + + if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { + const obj = {}; + + utils.forEachEntry(formData, (name, value) => { + buildPath(parsePropPath(name), value, obj, 0); + }); + + return obj; + } + + return null; } + /** - * A runnable that runs a callable. + * It takes a string, tries to parse it, and if it fails, it returns the stringified version + * of the input + * + * @param {any} rawValue - The value to be stringified. + * @param {Function} parser - A function that parses a string into a JavaScript object. + * @param {Function} encoder - A function that takes a value and returns a string. + * + * @returns {string} A stringified version of the rawValue. */ -class RunnableLambda extends base_Runnable { - static lc_name() { - return "RunnableLambda"; +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.func = fields.func; + } + + return (encoder || JSON.stringify)(rawValue); +} + +const defaults = { + + transitional: transitionalDefaults, + + adapter: ['xhr', 'http'], + + transformRequest: [function transformRequest(data, headers) { + const contentType = headers.getContentType() || ''; + const hasJSONContentType = contentType.indexOf('application/json') > -1; + const isObjectPayload = utils.isObject(data); + + if (isObjectPayload && utils.isHTMLForm(data)) { + data = new FormData(data); } - async _invoke(input, config, runManager) { - let output = await this.func(input); - if (output && base_Runnable.isRunnable(output)) { - output = await output.invoke(input, this._patchConfig(config, runManager?.getChild())); - } - return output; + + const isFormData = utils.isFormData(data); + + if (isFormData) { + if (!hasJSONContentType) { + return data; + } + return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; } - async invoke(input, options) { - return this._callWithConfig(this._invoke, input, options); + + if (utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; } -} -/** - * A Runnable that can fallback to other Runnables if it fails. - */ -class RunnableWithFallbacks extends base_Runnable { - static lc_name() { - return "RunnableWithFallbacks"; + if (utils.isArrayBufferView(data)) { + return data.buffer; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "runnable", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fallbacks", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; + if (utils.isURLSearchParams(data)) { + headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); + return data.toString(); } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) { - yield fallback; - } + + let isFileList; + + if (isObjectPayload) { + if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { + return toURLEncodedForm(data, this.formSerializer).toString(); + } + + if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { + const _FormData = this.env && this.env.FormData; + + return toFormData( + isFileList ? {'files[]': data} : data, + _FormData && new _FormData(), + this.formSerializer + ); + } } - async invoke(input, options) { - const callbackManager_ = await manager/* CallbackManager.configure */.Ye.configure(options?.callbacks, undefined, options?.tags, undefined, options?.metadata); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input")); - let firstError; - for (const runnable of this.runnables()) { - try { - const output = await runnable.invoke(input, this._patchConfig(options, runManager?.getChild())); - await runManager?.handleChainEnd(_coerceToDict(output, "output")); - return output; - } - catch (e) { - if (firstError === undefined) { - firstError = e; - } - } - } - if (firstError === undefined) { - throw new Error("No error stored at end of fallback."); - } - await runManager?.handleChainError(firstError); - throw firstError; + + if (isObjectPayload || hasJSONContentType ) { + headers.setContentType('application/json', false); + return stringifySafely(data); } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) { - throw new Error("Not implemented."); - } - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config) => manager/* CallbackManager.configure */.Ye.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata))); - const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input")))); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let firstError; - for (const runnable of this.runnables()) { - try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => this._patchConfig(configList[j], runManager?.getChild())), batchOptions); - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict(outputs[i], "output")))); - return outputs; - } - catch (e) { - if (firstError === undefined) { - firstError = e; - } - } - } - if (!firstError) { - throw new Error("No error stored at end of fallbacks."); + + return data; + }], + + transformResponse: [function transformResponse(data) { + const transitional = this.transitional || defaults.transitional; + const forcedJSONParsing = transitional && transitional.forcedJSONParsing; + const JSONRequested = this.responseType === 'json'; + + if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { + const silentJSONParsing = transitional && transitional.silentJSONParsing; + const strictJSONParsing = !silentJSONParsing && JSONRequested; + + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); + } + throw e; } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; + } } -} -// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type -function base_coerceToRunnable(coerceable) { - if (typeof coerceable === "function") { - return new RunnableLambda({ func: coerceable }); + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + env: { + FormData: platform.classes.FormData, + Blob: platform.classes.Blob + }, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + }, + + headers: { + common: { + 'Accept': 'application/json, text/plain, */*', + 'Content-Type': undefined } - else if (base_Runnable.isRunnable(coerceable)) { - return coerceable; + } +}; + +utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { + defaults.headers[method] = {}; +}); + +const defaults$1 = defaults; + +// RawAxiosHeaders whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +const ignoreDuplicateOf = utils.toObjectSet([ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]); + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} rawHeaders Headers needing to be parsed + * + * @returns {Object} Headers parsed into an object + */ +const parseHeaders = rawHeaders => { + const parsed = {}; + let key; + let val; + let i; + + rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { + i = line.indexOf(':'); + key = line.substring(0, i).trim().toLowerCase(); + val = line.substring(i + 1).trim(); + + if (!key || (parsed[key] && ignoreDuplicateOf[key])) { + return; } - else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) { - runnables[key] = base_coerceToRunnable(value); - } - return new RunnableMap({ - steps: runnables, - }); + + if (key === 'set-cookie') { + if (parsed[key]) { + parsed[key].push(val); + } else { + parsed[key] = [val]; + } + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } - else { - throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); + }); + + return parsed; +}; + +const $internals = Symbol('internals'); + +function normalizeHeader(header) { + return header && String(header).trim().toLowerCase(); +} + +function normalizeValue(value) { + if (value === false || value == null) { + return value; + } + + return utils.isArray(value) ? value.map(normalizeValue) : String(value); +} + +function parseTokens(str) { + const tokens = Object.create(null); + const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; + let match; + + while ((match = tokensRE.exec(str))) { + tokens[match[1]] = match[2]; + } + + return tokens; +} + +const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); + +function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { + if (utils.isFunction(filter)) { + return filter.call(this, value, header); + } + + if (isHeaderNameFilter) { + value = header; + } + + if (!utils.isString(value)) return; + + if (utils.isString(filter)) { + return value.indexOf(filter) !== -1; + } + + if (utils.isRegExp(filter)) { + return filter.test(value); + } +} + +function formatHeader(header) { + return header.trim() + .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { + return char.toUpperCase() + str; + }); +} + +function buildAccessors(obj, header) { + const accessorName = utils.toCamelCase(' ' + header); + + ['get', 'set', 'has'].forEach(methodName => { + Object.defineProperty(obj, methodName + accessorName, { + value: function(arg1, arg2, arg3) { + return this[methodName].call(this, header, arg1, arg2, arg3); + }, + configurable: true + }); + }); +} + +class AxiosHeaders { + constructor(headers) { + headers && this.set(headers); + } + + set(header, valueOrRewrite, rewrite) { + const self = this; + + function setHeader(_value, _header, _rewrite) { + const lHeader = normalizeHeader(_header); + + if (!lHeader) { + throw new Error('header name must be a non-empty string'); + } + + const key = utils.findKey(self, lHeader); + + if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { + self[key || _header] = normalizeValue(_value); + } + } + + const setHeaders = (headers, _rewrite) => + utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + + if (utils.isPlainObject(header) || header instanceof this.constructor) { + setHeaders(header, valueOrRewrite); + } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { + setHeaders(parseHeaders(header), valueOrRewrite); + } else { + header != null && setHeader(valueOrRewrite, header, rewrite); } -} -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/passthrough.js + return this; + } -/** - * A runnable that passes through the input. - */ -class RunnablePassthrough extends (/* unused pure expression or super */ null && (Runnable)) { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - } - static lc_name() { - return "RunnablePassthrough"; - } - async invoke(input, options) { - return this._callWithConfig((input) => Promise.resolve(input), input, options); - } -} + get(header, parser) { + header = normalizeHeader(header); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/router.js + if (header) { + const key = utils.findKey(this, header); -/** - * A runnable that routes to a set of runnables based on Input['key']. - * Returns the output of the selected runnable. - */ -class RouterRunnable extends (/* unused pure expression or super */ null && (Runnable)) { - static lc_name() { - return "RouterRunnable"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "schema", "runnable"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "runnables", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.runnables = fields.runnables; - } - async invoke(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) { - throw new Error(`No runnable associated with key "${key}".`); + if (key) { + const value = this[key]; + + if (!parser) { + return value; } - return runnable.invoke(actualInput, options); - } - async batch(inputs, options, batchOptions) { - const keys = inputs.map((input) => input.key); - const actualInputs = inputs.map((input) => input.input); - const missingKey = keys.find((key) => this.runnables[key] === undefined); - if (missingKey !== undefined) { - throw new Error(`One or more keys do not have a corresponding runnable.`); + + if (parser === true) { + return parseTokens(value); } - const runnables = keys.map((key) => this.runnables[key]); - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const batchSize = batchOptions?.maxConcurrency && batchOptions.maxConcurrency > 0 - ? batchOptions?.maxConcurrency - : inputs.length; - const batchResults = []; - for (let i = 0; i < actualInputs.length; i += batchSize) { - const batchPromises = actualInputs - .slice(i, i + batchSize) - .map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); - const batchResult = await Promise.all(batchPromises); - batchResults.push(batchResult); + + if (utils.isFunction(parser)) { + return parser.call(this, value, key); } - return batchResults.flat(); - } - async stream(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) { - throw new Error(`No runnable associated with key "${key}".`); + + if (utils.isRegExp(parser)) { + return parser.exec(value); } - return runnable.stream(actualInput, options); + + throw new TypeError('parser must be boolean|regexp|function'); + } } -} + } -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/branch.js + has(header, matcher) { + header = normalizeHeader(header); -/** - * Class that represents a runnable branch. The RunnableBranch is - * initialized with an array of branches and a default branch. When invoked, - * it evaluates the condition of each branch in order and executes the - * corresponding branch if the condition is true. If none of the conditions - * are true, it executes the default branch. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -class RunnableBranch extends (/* unused pure expression or super */ null && (Runnable)) { - static lc_name() { - return "RunnableBranch"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "runnable", "branch"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "default", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "branches", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.branches = fields.branches; - this.default = fields.default; + if (header) { + const key = utils.findKey(this, header); + + return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); } - /** - * Convenience method for instantiating a RunnableBranch from - * RunnableLikes (objects, functions, or Runnables). - * - * Each item in the input except for the last one should be a - * tuple with two items. The first is a "condition" RunnableLike that - * returns "true" if the second RunnableLike in the tuple should run. - * - * The final item in the input should be a RunnableLike that acts as a - * default branch if no other branches match. - * - * @example - * ```ts - * import { RunnableBranch } from "langchain/schema/runnable"; - * - * const branch = RunnableBranch.from([ - * [(x: number) => x > 0, (x: number) => x + 1], - * [(x: number) => x < 0, (x: number) => x - 1], - * (x: number) => x - * ]); - * ``` - * @param branches An array where the every item except the last is a tuple of [condition, runnable] - * pairs. The last item is a default runnable which is invoked if no other condition matches. - * @returns A new RunnableBranch. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from(branches) { - if (branches.length < 1) { - throw new Error("RunnableBranch requires at least one branch"); + + return false; + } + + delete(header, matcher) { + const self = this; + let deleted = false; + + function deleteHeader(_header) { + _header = normalizeHeader(_header); + + if (_header) { + const key = utils.findKey(self, _header); + + if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { + delete self[key]; + + deleted = true; } - const branchLikes = branches.slice(0, -1); - const coercedBranches = branchLikes.map(([condition, runnable]) => [ - _coerceToRunnable(condition), - _coerceToRunnable(runnable), - ]); - const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); - return new this({ - branches: coercedBranches, - default: defaultBranch, - }); + } } - async _invoke(input, config, runManager) { - let result; - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, this._patchConfig(config, runManager?.getChild(`condition:${i + 1}`))); - if (conditionValue) { - result = await branchRunnable.invoke(input, this._patchConfig(config, runManager?.getChild(`branch:${i + 1}`))); - break; - } - } - if (!result) { - result = await this.default.invoke(input, this._patchConfig(config, runManager?.getChild("default"))); - } - return result; + + if (utils.isArray(header)) { + header.forEach(deleteHeader); + } else { + deleteHeader(header); } - async invoke(input, config = {}) { - return this._callWithConfig(this._invoke, input, config); + + return deleted; + } + + clear(matcher) { + const keys = Object.keys(this); + let i = keys.length; + let deleted = false; + + while (i--) { + const key = keys[i]; + if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { + delete this[key]; + deleted = true; + } } -} -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + return deleted; + } + + normalize(format) { + const self = this; + const headers = {}; + + utils.forEach(this, (value, header) => { + const key = utils.findKey(headers, header); + if (key) { + self[key] = normalizeValue(value); + delete self[header]; + return; + } + const normalized = format ? formatHeader(header) : String(header).trim(); + if (normalized !== header) { + delete self[header]; + } + self[normalized] = normalizeValue(value); + headers[normalized] = true; + }); -/***/ }), + return this; + } -/***/ 2723: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { + concat(...targets) { + return this.constructor.concat(this, ...targets); + } -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "L": () => (/* binding */ AsyncCaller) -/* harmony export */ }); -/* harmony import */ var p_retry__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(2548); -/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(8983); + toJSON(asStrings) { + const obj = Object.create(null); + utils.forEach(this, (value, header) => { + value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); + }); -const STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 408, - 409, // Conflict -]; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const defaultFailedAttemptHandler = (error) => { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.name === "TimeoutError" || - error.message.startsWith("AbortError") || - error.name === "AbortError") { - throw error; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; - } - const status = - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error?.response?.status ?? error?.status; - if (status && STATUS_NO_RETRY.includes(+status)) { - throw error; + return obj; + } + + [Symbol.iterator]() { + return Object.entries(this.toJSON())[Symbol.iterator](); + } + + toString() { + return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + } + + get [Symbol.toStringTag]() { + return 'AxiosHeaders'; + } + + static from(thing) { + return thing instanceof this ? thing : new this(thing); + } + + static concat(first, ...targets) { + const computed = new this(first); + + targets.forEach((target) => computed.set(target)); + + return computed; + } + + static accessor(header) { + const internals = this[$internals] = (this[$internals] = { + accessors: {} + }); + + const accessors = internals.accessors; + const prototype = this.prototype; + + function defineAccessor(_header) { + const lHeader = normalizeHeader(_header); + + if (!accessors[lHeader]) { + buildAccessors(prototype, _header); + accessors[lHeader] = true; + } } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.error?.code === "insufficient_quota") { - const err = new Error(error?.message); - err.name = "InsufficientQuotaError"; - throw err; + + utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); + + return this; + } +} + +AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + +// reserved names hotfix +utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { + let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` + return { + get: () => value, + set(headerValue) { + this[mapped] = headerValue; } -}; + } +}); + +utils.freezeMethods(AxiosHeaders); + +const AxiosHeaders$1 = AxiosHeaders; + /** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. + * Transform the data for a request or a response * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. + * @param {Array|Function} fns A single function or Array of functions + * @param {?Object} response The response object * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. + * @returns {*} The resulting transformed data */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = - params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = true ? p_queue__WEBPACK_IMPORTED_MODULE_1__["default"] : p_queue__WEBPACK_IMPORTED_MODULE_1__; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - return this.queue.add(() => p_retry__WEBPACK_IMPORTED_MODULE_0__(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; - } - else { - throw new Error(error); - } - }), { - onFailedAttempt: this.onFailedAttempt, - retries: this.maxRetries, - randomize: true, - // If needed we can change some of the defaults here, - // but they're quite sensible. - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); - } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); - } +function transformData(fns, response) { + const config = this || defaults$1; + const context = response || config; + const headers = AxiosHeaders$1.from(context.headers); + let data = context.data; + + utils.forEach(fns, function transform(fn) { + data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); + }); + + headers.normalize(); + + return data; } +function isCancel(value) { + return !!(value && value.__CANCEL__); +} -/***/ }), +/** + * A `CanceledError` is an object that is thrown when an operation is canceled. + * + * @param {string=} message The message. + * @param {Object=} config The config. + * @param {Object=} request The request. + * + * @returns {CanceledError} The created error. + */ +function CanceledError(message, config, request) { + // eslint-disable-next-line no-eq-null,eqeqeq + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); + this.name = 'CanceledError'; +} + +utils.inherits(CanceledError, AxiosError, { + __CANCEL__: true +}); -/***/ 113: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + * + * @returns {object} The response. + */ +function settle(resolve, reject, response) { + const validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(new AxiosError( + 'Request failed with status code ' + response.status, + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + response.config, + response.request, + response + )); + } +} -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "O": () => (/* binding */ getEndpoint) -/* harmony export */ }); /** - * This function generates an endpoint URL for (Azure) OpenAI - * based on the configuration parameters provided. + * Determines whether the specified URL is absolute * - * @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint. + * @param {string} url The URL to test * - * @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI. - * @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI. - * @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI. - * @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI. - * @property {string} config.baseURL - Some other custom base path URL. + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +} + +/** + * Creates a new URL by combining the specified URLs * - * The function operates as follows: - * - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`). - * - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters. - * - If none of the above conditions are met, return any custom `baseURL`. - * - The function returns the generated URL as a string, or undefined if no custom paths are specified. + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL * - * @throws Will throw an error if the necessary parameters for generating the URL are missing. + * @returns {string} The combined URL + */ +function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +} + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. * - * @returns {string | undefined} The generated (Azure) OpenAI endpoint URL. + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * + * @returns {string} The combined full path */ -function getEndpoint(config) { - const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, } = config; - if (azureOpenAIApiKey && - azureOpenAIBasePath && - azureOpenAIApiDeploymentName) { - return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; - } - if (azureOpenAIApiKey) { - if (!azureOpenAIApiInstanceName) { - throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); - } - if (!azureOpenAIApiDeploymentName) { - throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); - } - return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; - } - return baseURL; +function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; } +const VERSION = "1.5.1"; -/***/ }), +function parseProtocol(url) { + const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); + return match && match[1] || ''; +} -/***/ 5785: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { +const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "lS": () => (/* binding */ getEnvironmentVariable), -/* harmony export */ "sA": () => (/* binding */ getRuntimeEnvironment) -/* harmony export */ }); -/* unused harmony exports isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv */ -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && - (navigator.userAgent.includes("Node.js") || - navigator.userAgent.includes("jsdom"))); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !isDeno(); -const getEnv = () => { - let env; - if (isBrowser()) { - env = "browser"; - } - else if (isNode()) { - env = "node"; - } - else if (isWebWorker()) { - env = "webworker"; - } - else if (isJsDom()) { - env = "jsdom"; - } - else if (isDeno()) { - env = "deno"; - } - else { - env = "other"; +/** + * Parse data uri to a Buffer or Blob + * + * @param {String} uri + * @param {?Boolean} asBlob + * @param {?Object} options + * @param {?Function} options.Blob + * + * @returns {Buffer|Blob} + */ +function fromDataURI(uri, asBlob, options) { + const _Blob = options && options.Blob || platform.classes.Blob; + const protocol = parseProtocol(uri); + + if (asBlob === undefined && _Blob) { + asBlob = true; + } + + if (protocol === 'data') { + uri = protocol.length ? uri.slice(protocol.length + 1) : uri; + + const match = DATA_URL_PATTERN.exec(uri); + + if (!match) { + throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); } - return env; -}; -let runtimeEnvironment; -async function getRuntimeEnvironment() { - if (runtimeEnvironment === undefined) { - const env = getEnv(); - runtimeEnvironment = { - library: "langchain-js", - runtime: env, - }; + + const mime = match[1]; + const isBase64 = match[2]; + const body = match[3]; + const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); + + if (asBlob) { + if (!_Blob) { + throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); + } + + return new _Blob([buffer], {type: mime}); } - return runtimeEnvironment; + + return buffer; + } + + throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); } -function getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; + +/** + * Throttle decorator + * @param {Function} fn + * @param {Number} freq + * @return {Function} + */ +function throttle(fn, freq) { + let timestamp = 0; + const threshold = 1000 / freq; + let timer = null; + return function throttled(force, args) { + const now = Date.now(); + if (force || now - timestamp > threshold) { + if (timer) { + clearTimeout(timer); + timer = null; + } + timestamp = now; + return fn.apply(null, args); } - catch (e) { - return undefined; + if (!timer) { + timer = setTimeout(() => { + timer = null; + timestamp = Date.now(); + return fn.apply(null, args); + }, threshold - (now - timestamp)); } + }; } +/** + * Calculate data maxRate + * @param {Number} [samplesCount= 10] + * @param {Number} [min= 1000] + * @returns {Function} + */ +function speedometer(samplesCount, min) { + samplesCount = samplesCount || 10; + const bytes = new Array(samplesCount); + const timestamps = new Array(samplesCount); + let head = 0; + let tail = 0; + let firstSampleTS; -/***/ }), + min = min !== undefined ? min : 1000; -/***/ 8311: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { + return function push(chunkLength) { + const now = Date.now(); -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "K": () => (/* binding */ wrapOpenAIClientError) -/* harmony export */ }); -/* harmony import */ var openai__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(1053); + const startedAt = timestamps[tail]; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function wrapOpenAIClientError(e) { - let error; - if (e.constructor.name === openai__WEBPACK_IMPORTED_MODULE_0__/* .APIConnectionTimeoutError.name */ .zo.name) { - error = new Error(e.message); - error.name = "TimeoutError"; - } - else if (e.constructor.name === openai__WEBPACK_IMPORTED_MODULE_0__/* .APIUserAbortError.name */ .Qr.name) { - error = new Error(e.message); - error.name = "AbortError"; - } - else { - error = e; + if (!firstSampleTS) { + firstSampleTS = now; } - return error; -} - - -/***/ }), -/***/ 2306: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { + bytes[head] = chunkLength; + timestamps[head] = now; -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "r": () => (/* binding */ promptLayerTrackRequest) -/* harmony export */ }); -const promptLayerTrackRequest = async (callerFunc, functionName, kwargs, plTags, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -requestResponse, startTime, endTime, apiKey) => { - // https://github.com/MagnivOrg/promptlayer-js-helper - const promptLayerResp = await callerFunc.call(fetch, "https://api.promptlayer.com/track-request", { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - }, - body: JSON.stringify({ - function_name: functionName, - provider: "langchain", - kwargs, - tags: plTags, - request_response: requestResponse, - request_start_time: Math.floor(startTime / 1000), - request_end_time: Math.floor(endTime / 1000), - api_key: apiKey, - }), - }); - return promptLayerResp.json(); -}; + let i = tail; + let bytesCount = 0; + while (i !== head) { + bytesCount += bytes[i++]; + i = i % samplesCount; + } -/***/ }), + head = (head + 1) % samplesCount; -/***/ 7573: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { + if (head === tail) { + tail = (tail + 1) % samplesCount; + } + if (now - firstSampleTS < min) { + return; + } -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "b": () => (/* binding */ encodingForModel) -}); + const passed = startedAt && now - startedAt; -// UNUSED EXPORTS: getEncoding + return passed ? Math.round(bytesCount * 1000 / passed) : undefined; + }; +} -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-XXPGZHWZ.js -var __defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; +const kInternals = Symbol('internals'); +class AxiosTransformStream extends stream__default["default"].Transform{ + constructor(options) { + options = utils.toFlatObject(options, { + maxRate: 0, + chunkSize: 64 * 1024, + minChunkSize: 100, + timeWindow: 500, + ticksRate: 2, + samplesCount: 15 + }, null, (prop, source) => { + return !utils.isUndefined(source[prop]); + }); + super({ + readableHighWaterMark: options.chunkSize + }); -// EXTERNAL MODULE: ./node_modules/base64-js/index.js -var base64_js = __nccwpck_require__(6463); -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-THGZSONF.js + const self = this; + const internals = this[kInternals] = { + length: options.length, + timeWindow: options.timeWindow, + ticksRate: options.ticksRate, + chunkSize: options.chunkSize, + maxRate: options.maxRate, + minChunkSize: options.minChunkSize, + bytesSeen: 0, + isCaptured: false, + notifiedBytesLoaded: 0, + ts: Date.now(), + bytes: 0, + onReadCallback: null + }; + const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow); -// src/utils.ts -function never(_) { -} -function bytePairMerge(piece, ranks) { - let parts = Array.from( - { length: piece.length }, - (_, i) => ({ start: i, end: i + 1 }) - ); - while (parts.length > 1) { - let minRank = null; - for (let i = 0; i < parts.length - 1; i++) { - const slice = piece.slice(parts[i].start, parts[i + 1].end); - const rank = ranks.get(slice.join(",")); - if (rank == null) - continue; - if (minRank == null || rank < minRank[0]) { - minRank = [rank, i]; - } - } - if (minRank != null) { - const i = minRank[1]; - parts[i] = { start: parts[i].start, end: parts[i + 1].end }; - parts.splice(i + 1, 1); - } else { - break; - } - } - return parts; -} -function bytePairEncode(piece, ranks) { - if (piece.length === 1) - return [ranks.get(piece.join(","))]; - return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); -} -function escapeRegex(str) { - return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); -} -var _Tiktoken = class { - /** @internal */ - specialTokens; - /** @internal */ - inverseSpecialTokens; - /** @internal */ - patStr; - /** @internal */ - textEncoder = new TextEncoder(); - /** @internal */ - textDecoder = new TextDecoder("utf-8"); - /** @internal */ - rankMap = /* @__PURE__ */ new Map(); - /** @internal */ - textMap = /* @__PURE__ */ new Map(); - constructor(ranks, extendedSpecialTokens) { - this.patStr = ranks.pat_str; - const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { - const [_, offsetStr, ...tokens] = x.split(" "); - const offset = Number.parseInt(offsetStr, 10); - tokens.forEach((token, i) => memo[token] = offset + i); - return memo; - }, {}); - for (const [token, rank] of Object.entries(uncompressed)) { - const bytes = base64_js.toByteArray(token); - this.rankMap.set(bytes.join(","), rank); - this.textMap.set(rank, bytes); - } - this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; - this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { - memo[rank] = this.textEncoder.encode(text); - return memo; - }, {}); - } - encode(text, allowedSpecial = [], disallowedSpecial = "all") { - const regexes = new RegExp(this.patStr, "ug"); - const specialRegex = _Tiktoken.specialTokenRegex( - Object.keys(this.specialTokens) - ); - const ret = []; - const allowedSpecialSet = new Set( - allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial - ); - const disallowedSpecialSet = new Set( - disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( - (x) => !allowedSpecialSet.has(x) - ) : disallowedSpecial - ); - if (disallowedSpecialSet.size > 0) { - const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ - ...disallowedSpecialSet - ]); - const specialMatch = text.match(disallowedSpecialRegex); - if (specialMatch != null) { - throw new Error( - `The text contains a special token that is not allowed: ${specialMatch[0]}` - ); - } - } - let start = 0; - while (true) { - let nextSpecial = null; - let startFind = start; - while (true) { - specialRegex.lastIndex = startFind; - nextSpecial = specialRegex.exec(text); - if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) - break; - startFind = nextSpecial.index + 1; - } - const end = nextSpecial?.index ?? text.length; - for (const match of text.substring(start, end).matchAll(regexes)) { - const piece = this.textEncoder.encode(match[0]); - const token2 = this.rankMap.get(piece.join(",")); - if (token2 != null) { - ret.push(token2); - continue; - } - ret.push(...bytePairEncode(piece, this.rankMap)); - } - if (nextSpecial == null) - break; - let token = this.specialTokens[nextSpecial[0]]; - ret.push(token); - start = nextSpecial.index + nextSpecial[0].length; - } - return ret; - } - decode(tokens) { - const res = []; - let length = 0; - for (let i2 = 0; i2 < tokens.length; ++i2) { - const token = tokens[i2]; - const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; - if (bytes != null) { - res.push(bytes); - length += bytes.length; - } - } - const mergedArray = new Uint8Array(length); - let i = 0; - for (const bytes of res) { - mergedArray.set(bytes, i); - i += bytes.length; - } - return this.textDecoder.decode(mergedArray); - } -}; -var Tiktoken = _Tiktoken; -__publicField(Tiktoken, "specialTokenRegex", (tokens) => { - return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g"); -}); -function getEncodingNameForModel(model) { - switch (model) { - case "gpt2": { - return "gpt2"; - } - case "code-cushman-001": - case "code-cushman-002": - case "code-davinci-001": - case "code-davinci-002": - case "cushman-codex": - case "davinci-codex": - case "text-davinci-002": - case "text-davinci-003": { - return "p50k_base"; - } - case "code-davinci-edit-001": - case "text-davinci-edit-001": { - return "p50k_edit"; - } - case "ada": - case "babbage": - case "code-search-ada-code-001": - case "code-search-babbage-code-001": - case "curie": - case "davinci": - case "text-ada-001": - case "text-babbage-001": - case "text-curie-001": - case "text-davinci-001": - case "text-search-ada-doc-001": - case "text-search-babbage-doc-001": - case "text-search-curie-doc-001": - case "text-search-davinci-doc-001": - case "text-similarity-ada-001": - case "text-similarity-babbage-001": - case "text-similarity-curie-001": - case "text-similarity-davinci-001": { - return "r50k_base"; - } - case "gpt-3.5-turbo-16k-0613": - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo": - case "gpt-4-32k-0613": - case "gpt-4-32k-0314": - case "gpt-4-32k": - case "gpt-4-0613": - case "gpt-4-0314": - case "gpt-4": - case "text-embedding-ada-002": { - return "cl100k_base"; - } - default: - throw new Error("Unknown model"); - } -} + this.on('newListener', event => { + if (event === 'progress') { + if (!internals.isCaptured) { + internals.isCaptured = true; + } + } + }); + let bytesNotified = 0; + internals.updateProgress = throttle(function throttledHandler() { + const totalBytes = internals.length; + const bytesTransferred = internals.bytesSeen; + const progressBytes = bytesTransferred - bytesNotified; + if (!progressBytes || self.destroyed) return; -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js + const rate = _speedometer(progressBytes); + bytesNotified = bytesTransferred; + process.nextTick(() => { + self.emit('progress', { + 'loaded': bytesTransferred, + 'total': totalBytes, + 'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined, + 'bytes': progressBytes, + 'rate': rate ? rate : undefined, + 'estimated': rate && totalBytes && bytesTransferred <= totalBytes ? + (totalBytes - bytesTransferred) / rate : undefined + }); + }); + }, internals.ticksRate); -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/async_caller.js -var async_caller = __nccwpck_require__(2723); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/util/tiktoken.js + const onFinish = () => { + internals.updateProgress(true); + }; + this.once('end', onFinish); + this.once('error', onFinish); + } -const cache = {}; -const caller = /* #__PURE__ */ new async_caller/* AsyncCaller */.L({}); -async function getEncoding(encoding, options) { - if (!(encoding in cache)) { - cache[encoding] = caller - .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`, { - signal: options?.signal, - }) - .then((res) => res.json()) - .catch((e) => { - delete cache[encoding]; - throw e; - }); - } - return new Tiktoken(await cache[encoding], options?.extendedSpecialTokens); -} -async function encodingForModel(model, options) { - return getEncoding(getEncodingNameForModel(model), options); -} + _read(size) { + const internals = this[kInternals]; + if (internals.onReadCallback) { + internals.onReadCallback(); + } -/***/ }), + return super._read(size); + } -/***/ 1273: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { + _transform(chunk, encoding, callback) { + const self = this; + const internals = this[kInternals]; + const maxRate = internals.maxRate; -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ "v4": () => (/* binding */ v4) -/* harmony export */ }); -/* unused harmony exports v1, v3, v5, NIL, version, validate, stringify, parse */ -/* harmony import */ var _dist_index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(8655); + const readableHighWaterMark = this.readableHighWaterMark; -const v1 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v1; -const v3 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v3; -const v4 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v4; -const v5 = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__.v5; -const NIL = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__/* .NIL */ .zR; -const version = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__/* .version */ .i8; -const validate = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__/* .validate */ .Gu; -const stringify = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__/* .stringify */ .Pz; -const parse = _dist_index_js__WEBPACK_IMPORTED_MODULE_0__/* .parse */ .Qc; + const timeWindow = internals.timeWindow; + const divider = 1000 / timeWindow; + const bytesThreshold = (maxRate / divider); + const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; -/***/ }), + function pushChunk(_chunk, _callback) { + const bytes = Buffer.byteLength(_chunk); + internals.bytesSeen += bytes; + internals.bytes += bytes; -/***/ 1053: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { + if (internals.isCaptured) { + internals.updateProgress(); + } + if (self.push(_chunk)) { + process.nextTick(_callback); + } else { + internals.onReadCallback = () => { + internals.onReadCallback = null; + process.nextTick(_callback); + }; + } + } -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "zo": () => (/* binding */ openai_APIConnectionTimeoutError), - "Qr": () => (/* binding */ openai_APIUserAbortError), - "Pp": () => (/* binding */ OpenAI) -}); + const transformChunk = (_chunk, _callback) => { + const chunkSize = Buffer.byteLength(_chunk); + let chunkRemainder = null; + let maxChunkSize = readableHighWaterMark; + let bytesLeft; + let passed = 0; -// UNUSED EXPORTS: APIConnectionError, APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, default, fileFromPath, toFile - -// NAMESPACE OBJECT: ./node_modules/openai/error.mjs -var error_namespaceObject = {}; -__nccwpck_require__.r(error_namespaceObject); -__nccwpck_require__.d(error_namespaceObject, { - "APIConnectionError": () => (APIConnectionError), - "APIConnectionTimeoutError": () => (APIConnectionTimeoutError), - "APIError": () => (APIError), - "APIUserAbortError": () => (APIUserAbortError), - "AuthenticationError": () => (AuthenticationError), - "BadRequestError": () => (BadRequestError), - "ConflictError": () => (ConflictError), - "InternalServerError": () => (InternalServerError), - "NotFoundError": () => (NotFoundError), - "PermissionDeniedError": () => (PermissionDeniedError), - "RateLimitError": () => (RateLimitError), - "UnprocessableEntityError": () => (UnprocessableEntityError) -}); + if (maxRate) { + const now = Date.now(); -;// CONCATENATED MODULE: ./node_modules/openai/version.mjs -const VERSION = '4.4.0'; // x-release-please-version -//# sourceMappingURL=version.mjs.map + if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { + internals.ts = now; + bytesLeft = bytesThreshold - internals.bytes; + internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; + passed = 0; + } -;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs -class Stream { - constructor(response, controller) { - this.response = response; - this.controller = controller; - this.decoder = new SSEDecoder(); - } - async *iterMessages() { - if (!this.response.body) { - this.controller.abort(); - throw new Error(`Attempted to iterate over a response with no body`); - } - const lineDecoder = new LineDecoder(); - const iter = readableStreamAsyncIterable(this.response.body); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - const sse = this.decoder.decode(line); - if (sse) yield sse; + bytesLeft = bytesThreshold - internals.bytes; } - } - for (const line of lineDecoder.flush()) { - const sse = this.decoder.decode(line); - if (sse) yield sse; - } - } - async *[Symbol.asyncIterator]() { - let done = false; - try { - for await (const sse of this.iterMessages()) { - if (done) continue; - if (sse.data.startsWith('[DONE]')) { - done = true; - continue; + + if (maxRate) { + if (bytesLeft <= 0) { + // next time window + return setTimeout(() => { + _callback(null, _chunk); + }, timeWindow - passed); } - if (sse.event === null) { - try { - yield JSON.parse(sse.data); - } catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } + + if (bytesLeft < maxChunkSize) { + maxChunkSize = bytesLeft; } } - done = true; - } catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (e instanceof Error && e.name === 'AbortError') return; - throw e; - } finally { - // If the user `break`s, abort the ongoing request. - if (!done) this.controller.abort(); - } - } -} -class SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } -} -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class LineDecoder { - constructor() { - this.buffer = []; - this.trailingCR = false; - } - decode(chunk) { - let text = this.decodeText(chunk); - if (this.trailingCR) { - text = '\r' + text; - this.trailingCR = false; - } - if (text.endsWith('\r')) { - this.trailingCR = true; - text = text.slice(0, -1); - } - if (!text) { - return []; - } - const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ''); - let lines = text.split(LineDecoder.NEWLINE_REGEXP); - if (lines.length === 1 && !trailingNewline) { - this.buffer.push(lines[0]); - return []; - } - if (this.buffer.length > 0) { - lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; - this.buffer = []; - } - if (!trailingNewline) { - this.buffer = [lines.pop() || '']; - } - return lines; - } - decodeText(bytes) { - var _a; - if (bytes == null) return ''; - if (typeof bytes === 'string') return bytes; - // Node: - if (typeof Buffer !== 'undefined') { - if (bytes instanceof Buffer) { - return bytes.toString(); + + if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { + chunkRemainder = _chunk.subarray(maxChunkSize); + _chunk = _chunk.subarray(0, maxChunkSize); } - if (bytes instanceof Uint8Array) { - return Buffer.from(bytes).toString(); + + pushChunk(_chunk, chunkRemainder ? () => { + process.nextTick(_callback, null, chunkRemainder); + } : _callback); + }; + + transformChunk(chunk, function transformNextChunk(err, _chunk) { + if (err) { + return callback(err); } - throw new Error( - `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`, - ); - } - // Browser - if (typeof TextDecoder !== 'undefined') { - if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { - (_a = this.textDecoder) !== null && _a !== void 0 ? _a : (this.textDecoder = new TextDecoder('utf8')); - return this.textDecoder.decode(bytes); + + if (_chunk) { + transformChunk(_chunk, transformNextChunk); + } else { + callback(null); } - throw new Error( - `Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`, - ); - } - throw new Error( - `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`, - ); - } - flush() { - if (!this.buffer.length && !this.trailingCR) { - return []; - } - const lines = [this.buffer.join('')]; - this.buffer = []; - this.trailingCR = false; - return lines; + }); } -} -// prettier-ignore -LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\x85', '\u2028', '\u2029']); -LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; -function partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + + setLength(length) { + this[kInternals].length = +length; + return this; } - return [str, '', '']; -} -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function readableStreamAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result === null || result === void 0 ? void 0 : result.done) reader.releaseLock(); // release lock when stream becomes closed - return result; - } catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; } -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/error.mjs -// File generated from our OpenAPI spec by Stainless. +const AxiosTransformStream$1 = AxiosTransformStream; -class APIError extends Error { - constructor(status, error, message, headers) { - super(APIError.makeMessage(error, message)); - this.status = status; - this.headers = headers; - const data = error; - this.error = data; - this.code = data === null || data === void 0 ? void 0 : data['code']; - this.param = data === null || data === void 0 ? void 0 : data['param']; - this.type = data === null || data === void 0 ? void 0 : data['type']; - } - static makeMessage(error, message) { - return ( - ( - error === null || error === void 0 ? void 0 : error.message - ) ? - typeof error.message === 'string' ? error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message || 'Unknown error occurred' - ); +const {asyncIterator} = Symbol; + +const readBlob = async function* (blob) { + if (blob.stream) { + yield* blob.stream(); + } else if (blob.arrayBuffer) { + yield await blob.arrayBuffer(); + } else if (blob[asyncIterator]) { + yield* blob[asyncIterator](); + } else { + yield blob; } - static generate(status, errorResponse, message, headers) { - if (!status) { - return new APIConnectionError({ cause: castToError(errorResponse) }); - } - const error = errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse['error']; - if (status === 400) { - return new BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new PermissionDeniedError(status, error, message, headers); - } - if (status === 404) { - return new NotFoundError(status, error, message, headers); - } - if (status === 409) { - return new ConflictError(status, error, message, headers); - } - if (status === 422) { - return new UnprocessableEntityError(status, error, message, headers); - } - if (status === 429) { - return new RateLimitError(status, error, message, headers); - } - if (status >= 500) { - return new InternalServerError(status, error, message, headers); +}; + +const readBlob$1 = readBlob; + +const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_'; + +const textEncoder = new util.TextEncoder(); + +const CRLF = '\r\n'; +const CRLF_BYTES = textEncoder.encode(CRLF); +const CRLF_BYTES_COUNT = 2; + +class FormDataPart { + constructor(name, value) { + const {escapeName} = this.constructor; + const isStringValue = utils.isString(value); + + let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ + !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' + }${CRLF}`; + + if (isStringValue) { + value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + } else { + headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; } - return new APIError(status, error, message, headers); - } -} -class APIUserAbortError extends APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); - this.status = undefined; - } -} -class APIConnectionError extends APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - this.status = undefined; - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) this.cause = cause; - } -} -class APIConnectionTimeoutError extends APIConnectionError { - constructor() { - super({ message: 'Request timed out.' }); - } -} -class BadRequestError extends APIError { - constructor() { - super(...arguments); - this.status = 400; + + this.headers = textEncoder.encode(headers + CRLF); + + this.contentLength = isStringValue ? value.byteLength : value.size; + + this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + + this.name = name; + this.value = value; } -} -class AuthenticationError extends APIError { - constructor() { - super(...arguments); - this.status = 401; + + async *encode(){ + yield this.headers; + + const {value} = this; + + if(utils.isTypedArray(value)) { + yield value; + } else { + yield* readBlob$1(value); + } + + yield CRLF_BYTES; } -} -class PermissionDeniedError extends APIError { - constructor() { - super(...arguments); - this.status = 403; + + static escapeName(name) { + return String(name).replace(/[\r\n"]/g, (match) => ({ + '\r' : '%0D', + '\n' : '%0A', + '"' : '%22', + }[match])); } } -class NotFoundError extends APIError { - constructor() { - super(...arguments); - this.status = 404; + +const formDataToStream = (form, headersHandler, options) => { + const { + tag = 'form-data-boundary', + size = 25, + boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET) + } = options || {}; + + if(!utils.isFormData(form)) { + throw TypeError('FormData instance required'); } -} -class ConflictError extends APIError { - constructor() { - super(...arguments); - this.status = 409; + + if (boundary.length < 1 || boundary.length > 70) { + throw Error('boundary must be 10-70 characters long') } -} -class UnprocessableEntityError extends APIError { - constructor() { - super(...arguments); - this.status = 422; + + const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); + const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF); + let contentLength = footerBytes.byteLength; + + const parts = Array.from(form.entries()).map(([name, value]) => { + const part = new FormDataPart(name, value); + contentLength += part.size; + return part; + }); + + contentLength += boundaryBytes.byteLength * parts.length; + + contentLength = utils.toFiniteNumber(contentLength); + + const computedHeaders = { + 'Content-Type': `multipart/form-data; boundary=${boundary}` + }; + + if (Number.isFinite(contentLength)) { + computedHeaders['Content-Length'] = contentLength; } -} -class RateLimitError extends APIError { - constructor() { - super(...arguments); - this.status = 429; + + headersHandler && headersHandler(computedHeaders); + + return stream.Readable.from((async function *() { + for(const part of parts) { + yield boundaryBytes; + yield* part.encode(); + } + + yield footerBytes; + })()); +}; + +const formDataToStream$1 = formDataToStream; + +class ZlibHeaderTransformStream extends stream__default["default"].Transform { + __transform(chunk, encoding, callback) { + this.push(chunk); + callback(); } -} -class InternalServerError extends APIError {} -//# sourceMappingURL=error.mjs.map -// EXTERNAL MODULE: ./node_modules/agentkeepalive/index.js -var agentkeepalive = __nccwpck_require__(4623); -// EXTERNAL MODULE: ./node_modules/abort-controller/dist/abort-controller.js -var abort_controller = __nccwpck_require__(1659); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/agent.node.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ + _transform(chunk, encoding, callback) { + if (chunk.length !== 0) { + this._transform = this.__transform; + // Add Default Compression headers if no zlib headers are present + if (chunk[0] !== 120) { // Hex: 78 + const header = Buffer.alloc(2); + header[0] = 120; // Hex: 78 + header[1] = 156; // Hex: 9C + this.push(header, encoding); + } + } -const defaultHttpAgent = new agentkeepalive({ keepAlive: true, timeout: 5 * 60 * 1000 }); -const defaultHttpsAgent = new agentkeepalive.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); -// Polyfill global object if needed. -if (typeof AbortController === 'undefined') { - AbortController = abort_controller.AbortController; + this.__transform(chunk, encoding, callback); + } } -const getDefaultAgent = (url) => { - if (defaultHttpsAgent && url.startsWith('https')) return defaultHttpsAgent; - return defaultHttpAgent; + +const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; + +const callbackify = (fn, reducer) => { + return utils.isAsyncFn(fn) ? function (...args) { + const cb = args.pop(); + fn.apply(this, args).then((value) => { + try { + reducer ? cb(null, ...reducer(value)) : cb(null, value); + } catch (err) { + cb(err); + } + }, cb); + } : fn; }; -//# sourceMappingURL=agent.node.mjs.map -// EXTERNAL MODULE: ./node_modules/node-fetch/lib/index.js -var lib = __nccwpck_require__(467); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/fetch.node.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ +const callbackify$1 = callbackify; +const zlibOptions = { + flush: zlib__default["default"].constants.Z_SYNC_FLUSH, + finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH +}; +const brotliOptions = { + flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, + finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH +}; -const _fetch = lib; -const _Request = lib.Request; -const _Response = lib.Response; -const _Headers = lib.Headers; +const isBrotliSupported = utils.isFunction(zlib__default["default"].createBrotliDecompress); +const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; +const isHttps = /https:?/; -const isPolyfilled = true; +const supportedProtocols = platform.protocols.map(protocol => { + return protocol + ':'; +}); -// EXTERNAL MODULE: external "util" -var external_util_ = __nccwpck_require__(3837); -;// CONCATENATED MODULE: ./node_modules/web-streams-polyfill/dist/ponyfill.mjs /** - * @license - * web-streams-polyfill v4.0.0-beta.3 - * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. - * This code is released under the MIT license. - * SPDX-License-Identifier: MIT + * If the proxy or config beforeRedirects functions are defined, call them with the options + * object. + * + * @param {Object} options - The options object that was passed to the request. + * + * @returns {Object} */ -const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d(e){return s(e)}function f(e,t,r){return i.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,o)}function h(e,t){b(e,t)}function _(e,t){b(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,o)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class S{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),j(e)}(e):B(e,t._storedError)}function P(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function k(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function B(e,t){O(e),A(e,t)}function A(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function D(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function x(e){if(!r(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t)}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S}get closed(){return K(this)?this._closedPromise:d(ee("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(ee("cancel"))}read(){if(!K(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(k("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function K(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z(e,t){const r=e._readRequests;e._readRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d(k("iterate")):f(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function ce(e){e._queue=new S,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=r.buffer,qe(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!fe(this))throw Be("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");e.buffer,function(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=t.buffer,qe(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return ke(this)}close(){if(!de(this))throw Ae("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Pe(e,t),t}}Ee(e),Xt(t)}(this)}enqueue(e){if(!de(this))throw Ae("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t)}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift())}}(e),0===X(r))me(e,i,n,a);else{e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1)}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e)}(this,e)}error(e){if(!de(this))throw Ae("error");Pe(this,e)}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}U(t,e),be(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S,this._pendingPullIntos.push(e)}}}function de(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(J(t)&&X(t)>0)return!0;if(Le(t)&&ze(t)>0)return!0;if(ke(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,be(e)),null)),(t=>(Pe(e,t),null)))}function he(e){Re(e),e._pendingPullIntos=new S}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw Pe(e,t),t}me(e,n,0,o)}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Se(e,o,t),l-=o}return s}function Se(e,t,r){r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Xt(e._controlledReadableByteStream)):be(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t))}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e))}(e,r):function(e,t,r){if(Se(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o)}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e)}(e,t,r),be(e)}function Ce(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Pe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Ee(e),Jt(r,t))}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Oe(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");!function(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new S,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Pe(t,e),null)))}(e,o,n,a,i,r,l)}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t)}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S}get closed(){return Fe(this)?this._closedPromise:d(De("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(De("cancel"))}read(e){if(!Fe(this))return d(De("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(e.buffer,void 0===this._ownerReadableStream)return d(k("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Pe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw De("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function Fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function De(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return I(e,t),t=>Y(e(t))}function Ne(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function xe(e,t,r){return I(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new S,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,$e(r,1),a)}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d(_t("abort"))}close(){return Ge(this)?Xe(this)?d(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d(new TypeError("Cannot close an already-closing stream")):Ke(this):d(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||et(e,t),a}function Ke(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Et(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t)}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&tt(e)}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new S,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)))}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&St(t,e._storedError)}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else{const t=e._storedError;Tt(this,t),wt(this,t)}var r}get closed(){return at(this)?this._closedPromise:d(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d(mt("abort"))}close(){if(!at(this))return d(mt("close"));const e=this._ownerWritableStream;return void 0===e?d(yt("close")):rt(e)?d(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?St(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return at(this)?void 0===this._ownerWritableStream?d(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(yt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(rt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ue(e,t,r)}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e))}dt(e)}(o,t,n),i}(this,e):d(mt("write"))}}function at(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t)}(e,t)}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e)}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this)}}function st(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();ut(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&vt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Ze(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t)}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t)}(r,t),null)))}(e,r)}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t)}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t)}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function wt(e,t){gt(e),St(e,t)}function St(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Tt(e,t){Rt(e),Ct(e,t)}function qt(e){Rt(e),Et(e)}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Pt="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Pt)?Pt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,w=!1,S=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e}));let E=Promise.resolve(void 0);return u(((P,W)=>{let k;function O(){if(w)return;const e=u(((e,t)=>{!function r(o){o?e():f(function(){if(w)return c(!0);return f(l.ready,(()=>f(i.read(),(e=>!!e.done||(E=l.write(e.value),m(E),!1)))))}(),r,t)}(!1)}));m(e)}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return w||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return S||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(k=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?k():a.addEventListener("abort",k)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==E)return e=E,p(E,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}w||(w=!0,q?o():h(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return S=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",k),e?W(t):P(void 0),null}w||(b(i.closed,B,A),b(l.closed,(function(){return S||(R="closed"),null}),j)),q?O():y((()=>{q=!0,g(),O()}))}))}function Ot(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function w(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else{let e;try{e=le(l)}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e)}return s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function S(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():w(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():w(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:S,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t)}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return p}const w=new ReadableStream({start(e){a=e},pull:m,cancel:y}),S=new ReadableStream({start(e){i=e},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[w,S]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw Dt("desiredSize");return Lt(this)}close(){if(!Bt(this))throw Dt("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t))}(this)}enqueue(e){if(!Bt(this))throw Dt("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw zt(e,t),t}try{ue(e,t,r)}catch(t){throw zt(e,t),t}}At(e)}(this,e)}error(e){if(!Bt(this))throw Dt("error");zt(this,e)}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r)}else U(t,e),At(this)}[C](){}}function Bt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return!1;if(!e._started)return!1;if(Ut(t)&&X(t)>0)return!0;if(Lt(e)>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,At(e)),null)),(t=>(zt(e,t),null)))}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t))}function Lt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,At(t),null)),(e=>(zt(t,e),null)))}(e,n,a,i,l,r,o)}function Dt(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return I(e,r),r=>w(e,t,[r])}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}function xt(e,t){F(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Oe(this,o,$e(r,0))}else{const e=Me(r);It(this,o,$e(r,1),e)}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d(Kt("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Ot(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){F(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Vt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new S,e.forEach((e=>{e._closeSteps(void 0)}))}return p(e._readableStreamController[T](r),t)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new S,e.forEach((e=>{e._closeSteps()}))}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A(r,t),K(r)?Z(r,t):Ie(r,t))}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Zt(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream.prototype,e.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Zt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!rr(this))throw tr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rr(this))throw tr("size");return er}}function tr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function rr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const or=()=>1;n(or,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Zt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ar(this))throw nr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ar(this))throw nr("size");return or}}function nr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function ir(e,t,r){return I(e,r),r=>w(e,t,[r])}function lr(e,t,r){return I(e,r),r=>g(e,t,[r])}function sr(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ye(t,"Second parameter"),n=Ye(r,"Third parameter"),a=function(e,t){F(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ir(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:lr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:sr(a,e,`${t} has member 'transform' that`),writableType:i}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=$e(n,0),l=Me(n),s=$e(o,1),f=Me(o);let b;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return p(e._backpressureChangePromise,(()=>{if("erroring"===(Ge(e._writable)?e._writable._state:e._writableState))throw Ge(e._writable)?e._writable._storedError:e._writableStoredError;return pr(r,t)}))}return pr(r,t)}(e,t)}function s(t){return function(e,t){return cr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return hr(t),p(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;gr(e)&&wr(e)}),(t=>{throw cr(e,t),e._readableStoredError}))}(e)}function d(){return function(e){return fr(e,!1),e._backpressureChangePromise}(e)}function f(t){return dr(e,t),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return p(t(),(()=>(e._writableStarted=!0,Cr(e),null)),(t=>{throw e._writableStarted=!0,Rr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),p(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Cr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Rr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),p(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Rr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{Sr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{Sr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fr(e,!0),e._transformStreamController=void 0}(this,u((e=>{b=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return _r(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!ur(this))throw yr("readable");return this._readable}get writable(){if(!ur(this))throw yr("writable");return this._writable}}function ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function cr(e,t){Sr(e,t),dr(e,t)}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t)}(e,t),e._backpressure&&fr(e,!1)}function fr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStream.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e)}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t)}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&wr(t);const r=new TypeError("TransformStream terminated");dr(t,r)}(this)}}function br(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw Sr(e,t),t}}(r,t)}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!gr(e))return!1;if(e._readablePulling)return!0;if(vr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&fr(r,!0)}function pr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw cr(e._controlledTransformStream,t),t}))}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function yr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function gr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Sr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function vr(e){return e._readableController.desiredSize}function Rr(e,t){"writable"!==e._writableState?qr(e):Tr(e,t)}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e)}function qr(e){e._writableState="errored"}function Cr(e){"erroring"===e._writableState&&qr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}); - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js -const isFunction = (value) => (typeof value === "function"); - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/blobHelpers.js -/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ +function dispatchBeforeRedirect(options) { + if (options.beforeRedirects.proxy) { + options.beforeRedirects.proxy(options); + } + if (options.beforeRedirects.config) { + options.beforeRedirects.config(options); + } +} -const CHUNK_SIZE = 65536; -async function* clonePart(part) { - const end = part.byteOffset + part.byteLength; - let position = part.byteOffset; - while (position !== end) { - const size = Math.min(end - position, CHUNK_SIZE); - const chunk = part.buffer.slice(position, position + size); - position += chunk.byteLength; - yield new Uint8Array(chunk); +/** + * If the proxy or config afterRedirects functions are defined, call them with the options + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} configProxy configuration from Axios options object + * @param {string} location + * + * @returns {http.ClientRequestArgs} + */ +function setProxy(options, configProxy, location) { + let proxy = configProxy; + if (!proxy && proxy !== false) { + const proxyUrl = proxyFromEnv.getProxyForUrl(location); + if (proxyUrl) { + proxy = new URL(proxyUrl); } -} -async function* consumeNodeBlob(blob) { - let position = 0; - while (position !== blob.size) { - const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE)); - const buffer = await chunk.arrayBuffer(); - position += buffer.byteLength; - yield new Uint8Array(buffer); + } + if (proxy) { + // Basic proxy authorization + if (proxy.username) { + proxy.auth = (proxy.username || '') + ':' + (proxy.password || ''); } -} -async function* consumeBlobParts(parts, clone = false) { - for (const part of parts) { - if (ArrayBuffer.isView(part)) { - if (clone) { - yield* clonePart(part); - } - else { - yield part; - } - } - else if (isFunction(part.stream)) { - yield* part.stream(); - } - else { - yield* consumeNodeBlob(part); - } + + if (proxy.auth) { + // Support proxy auth object form + if (proxy.auth.username || proxy.auth.password) { + proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); + } + const base64 = Buffer + .from(proxy.auth, 'utf8') + .toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; } -} -function* sliceBlob(blobParts, blobSize, start = 0, end) { - end !== null && end !== void 0 ? end : (end = blobSize); - let relativeStart = start < 0 - ? Math.max(blobSize + start, 0) - : Math.min(start, blobSize); - let relativeEnd = end < 0 - ? Math.max(blobSize + end, 0) - : Math.min(end, blobSize); - const span = Math.max(relativeEnd - relativeStart, 0); - let added = 0; - for (const part of blobParts) { - if (added >= span) { - break; - } - const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size; - if (relativeStart && partSize <= relativeStart) { - relativeStart -= partSize; - relativeEnd -= partSize; - } - else { - let chunk; - if (ArrayBuffer.isView(part)) { - chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd)); - added += chunk.byteLength; - } - else { - chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd)); - added += chunk.size; - } - relativeEnd -= partSize; - relativeStart = 0; - yield chunk; - } + + options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); + const proxyHost = proxy.hostname || proxy.host; + options.hostname = proxyHost; + // Replace 'host' since options is not a URL object + options.host = proxyHost; + options.port = proxy.port; + options.path = location; + if (proxy.protocol) { + options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`; } + } + + options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { + // Configure proxy for redirected request, passing the original config proxy to apply + // the exact same logic as if the redirected request was performed by axios directly. + setProxy(redirectOptions, configProxy, redirectOptions.href); + }; } -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/Blob.js -/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ -var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - 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"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - 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"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _Blob_parts, _Blob_type, _Blob_size; +const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; +// temporary hotfix +const wrapAsync = (asyncExecutor) => { + return new Promise((resolve, reject) => { + let onDone; + let isDone; -class Blob { - constructor(blobParts = [], options = {}) { - _Blob_parts.set(this, []); - _Blob_type.set(this, ""); - _Blob_size.set(this, 0); - options !== null && options !== void 0 ? options : (options = {}); - if (typeof blobParts !== "object" || blobParts === null) { - throw new TypeError("Failed to construct 'Blob': " - + "The provided value cannot be converted to a sequence."); - } - if (!isFunction(blobParts[Symbol.iterator])) { - throw new TypeError("Failed to construct 'Blob': " - + "The object must have a callable @@iterator property."); - } - if (typeof options !== "object" && !isFunction(options)) { - throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); - } - const encoder = new TextEncoder(); - for (const raw of blobParts) { - let part; - if (ArrayBuffer.isView(raw)) { - part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); - } - else if (raw instanceof ArrayBuffer) { - part = new Uint8Array(raw.slice(0)); - } - else if (raw instanceof Blob) { - part = raw; - } - else { - part = encoder.encode(String(raw)); - } - __classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f"); - __classPrivateFieldGet(this, _Blob_parts, "f").push(part); + const done = (value, isRejected) => { + if (isDone) return; + isDone = true; + onDone && onDone(value, isRejected); + }; + + const _resolve = (value) => { + done(value); + resolve(value); + }; + + const _reject = (reason) => { + done(reason, true); + reject(reason); + }; + + asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); + }) +}; + +/*eslint consistent-return:0*/ +const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { + return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { + let {data, lookup, family} = config; + const {responseType, responseEncoding} = config; + const method = config.method.toUpperCase(); + let isDone; + let rejected = false; + let req; + + if (lookup && utils.isAsyncFn(lookup)) { + lookup = callbackify$1(lookup, (entry) => { + if(utils.isString(entry)) { + entry = [entry, entry.indexOf('.') < 0 ? 6 : 4]; + } else if (!utils.isArray(entry)) { + throw new TypeError('lookup async function must return an array [ip: string, family: number]]') } - const type = options.type === undefined ? "" : String(options.type); - __classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f"); - } - static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) { - return Boolean(value - && typeof value === "object" - && isFunction(value.constructor) - && (isFunction(value.stream) - || isFunction(value.arrayBuffer)) - && /^(Blob|File)$/.test(value[Symbol.toStringTag])); + return entry; + }); } - get type() { - return __classPrivateFieldGet(this, _Blob_type, "f"); + + // temporary internal emitter until the AxiosRequest class will be implemented + const emitter = new EventEmitter__default["default"](); + + const onFinished = () => { + if (config.cancelToken) { + config.cancelToken.unsubscribe(abort); + } + + if (config.signal) { + config.signal.removeEventListener('abort', abort); + } + + emitter.removeAllListeners(); + }; + + onDone((value, isRejected) => { + isDone = true; + if (isRejected) { + rejected = true; + onFinished(); + } + }); + + function abort(reason) { + emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); } - get size() { - return __classPrivateFieldGet(this, _Blob_size, "f"); + + emitter.once('abort', reject); + + if (config.cancelToken || config.signal) { + config.cancelToken && config.cancelToken.subscribe(abort); + if (config.signal) { + config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + } } - slice(start, end, contentType) { - return new Blob(sliceBlob(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), { - type: contentType + + // Parse url + const fullPath = buildFullPath(config.baseURL, config.url); + const parsed = new URL(fullPath, 'http://localhost'); + const protocol = parsed.protocol || supportedProtocols[0]; + + if (protocol === 'data:') { + let convertedData; + + if (method !== 'GET') { + return settle(resolve, reject, { + status: 405, + statusText: 'method not allowed', + headers: {}, + config }); - } - async text() { - const decoder = new TextDecoder(); - let result = ""; - for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { - result += decoder.decode(chunk, { stream: true }); - } - result += decoder.decode(); - return result; - } - async arrayBuffer() { - const view = new Uint8Array(this.size); - let offset = 0; - for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { - view.set(chunk, offset); - offset += chunk.length; - } - return view.buffer; - } - stream() { - const iterator = consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"), true); - return new ReadableStream({ - async pull(controller) { - const { value, done } = await iterator.next(); - if (done) { - return queueMicrotask(() => controller.close()); - } - controller.enqueue(value); - }, - async cancel() { - await iterator.return(); - } + } + + try { + convertedData = fromDataURI(config.url, responseType === 'blob', { + Blob: config.env && config.env.Blob }); - } - get [Symbol.toStringTag]() { - return "Blob"; - } -} -Object.defineProperties(Blob.prototype, { - type: { enumerable: true }, - size: { enumerable: true }, - slice: { enumerable: true }, - stream: { enumerable: true }, - text: { enumerable: true }, - arrayBuffer: { enumerable: true } -}); + } catch (err) { + throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + } -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/File.js -var File_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - 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"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var File_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - 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"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _File_name, _File_lastModified; + if (responseType === 'text') { + convertedData = convertedData.toString(responseEncoding); -class File extends Blob { - constructor(fileBits, name, options = {}) { - super(fileBits, options); - _File_name.set(this, void 0); - _File_lastModified.set(this, 0); - if (arguments.length < 2) { - throw new TypeError("Failed to construct 'File': 2 arguments required, " - + `but only ${arguments.length} present.`); - } - File_classPrivateFieldSet(this, _File_name, String(name), "f"); - const lastModified = options.lastModified === undefined - ? Date.now() - : Number(options.lastModified); - if (!Number.isNaN(lastModified)) { - File_classPrivateFieldSet(this, _File_lastModified, lastModified, "f"); + if (!responseEncoding || responseEncoding === 'utf8') { + convertedData = utils.stripBOM(convertedData); } + } else if (responseType === 'stream') { + convertedData = stream__default["default"].Readable.from(convertedData); + } + + return settle(resolve, reject, { + data: convertedData, + status: 200, + statusText: 'OK', + headers: new AxiosHeaders$1(), + config + }); } - static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) { - return value instanceof Blob - && value[Symbol.toStringTag] === "File" - && typeof value.name === "string"; - } - get name() { - return File_classPrivateFieldGet(this, _File_name, "f"); - } - get lastModified() { - return File_classPrivateFieldGet(this, _File_lastModified, "f"); - } - get webkitRelativePath() { - return ""; + + if (supportedProtocols.indexOf(protocol) === -1) { + return reject(new AxiosError( + 'Unsupported protocol ' + protocol, + AxiosError.ERR_BAD_REQUEST, + config + )); } - get [Symbol.toStringTag]() { - return "File"; + + const headers = AxiosHeaders$1.from(config.headers).normalize(); + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + // User-Agent is specified; handle case where no UA header is desired + // Only set header if it hasn't been set in config + headers.set('User-Agent', 'axios/' + VERSION, false); + + const onDownloadProgress = config.onDownloadProgress; + const onUploadProgress = config.onUploadProgress; + const maxRate = config.maxRate; + let maxUploadRate = undefined; + let maxDownloadRate = undefined; + + // support for spec compliant FormData objects + if (utils.isSpecCompliantForm(data)) { + const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + + data = formDataToStream$1(data, (formHeaders) => { + headers.set(formHeaders); + }, { + tag: `axios-${VERSION}-boundary`, + boundary: userBoundary && userBoundary[1] || undefined + }); + // support for https://www.npmjs.com/package/form-data api + } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { + headers.set(data.getHeaders()); + + if (!headers.hasContentLength()) { + try { + const knownLength = await util__default["default"].promisify(data.getLength).call(data); + Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); + /*eslint no-empty:0*/ + } catch (e) { + } + } + } else if (utils.isBlob(data)) { + data.size && headers.setContentType(data.type || 'application/octet-stream'); + headers.setContentLength(data.size || 0); + data = stream__default["default"].Readable.from(readBlob$1(data)); + } else if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) ; else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(new AxiosError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + AxiosError.ERR_BAD_REQUEST, + config + )); + } + + // Add Content-Length header if data exists + headers.setContentLength(data.length, false); + + if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { + return reject(new AxiosError( + 'Request body larger than maxBodyLength limit', + AxiosError.ERR_BAD_REQUEST, + config + )); + } } -} -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isFile.js + const contentLength = utils.toFiniteNumber(headers.getContentLength()); -const isFile = (value) => value instanceof File; + if (utils.isArray(maxRate)) { + maxUploadRate = maxRate[0]; + maxDownloadRate = maxRate[1]; + } else { + maxUploadRate = maxDownloadRate = maxRate; + } -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isBlob.js + if (data && (onUploadProgress || maxUploadRate)) { + if (!utils.isStream(data)) { + data = stream__default["default"].Readable.from(data, {objectMode: false}); + } -const isBlob = (value) => value instanceof Blob; + data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ + length: contentLength, + maxRate: utils.toFiniteNumber(maxUploadRate) + })], utils.noop); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js + onUploadProgress && data.on('progress', progress => { + onUploadProgress(Object.assign(progress, { + upload: true + })); + }); + } -const deprecateConstructorEntries = (0,external_util_.deprecate)(() => { }, "Constructor \"entries\" argument is not spec-compliant " - + "and will be removed in next major release."); + // HTTP basic authentication + let auth = undefined; + if (config.auth) { + const username = config.auth.username || ''; + const password = config.auth.password || ''; + auth = username + ':' + password; + } -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/FormData.js -var FormData_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - 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"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _FormData_instances, _FormData_entries, _FormData_setEntry; + if (!auth && parsed.username) { + const urlUsername = parsed.username; + const urlPassword = parsed.password; + auth = urlUsername + ':' + urlPassword; + } + auth && headers.delete('authorization'); + let path; + try { + path = buildURL( + parsed.pathname + parsed.search, + config.params, + config.paramsSerializer + ).replace(/^\?/, ''); + } catch (err) { + const customErr = new Error(err.message); + customErr.config = config; + customErr.url = config.url; + customErr.exists = true; + return reject(customErr); + } + headers.set( + 'Accept-Encoding', + 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false + ); + const options = { + path, + method: method, + headers: headers.toJSON(), + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth, + protocol, + family, + beforeRedirect: dispatchBeforeRedirect, + beforeRedirects: {} + }; -class FormData { - constructor(entries) { - _FormData_instances.add(this); - _FormData_entries.set(this, new Map()); - if (entries) { - deprecateConstructorEntries(); - entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName)); - } - } - static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) { - return Boolean(value - && isFunction(value.constructor) - && value[Symbol.toStringTag] === "FormData" - && isFunction(value.append) - && isFunction(value.set) - && isFunction(value.get) - && isFunction(value.getAll) - && isFunction(value.has) - && isFunction(value.delete) - && isFunction(value.entries) - && isFunction(value.values) - && isFunction(value.keys) - && isFunction(value[Symbol.iterator]) - && isFunction(value.forEach)); - } - append(name, value, fileName) { - FormData_classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { - name, - fileName, - append: true, - rawValue: value, - argsLength: arguments.length - }); - } - set(name, value, fileName) { - FormData_classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { - name, - fileName, - append: false, - rawValue: value, - argsLength: arguments.length - }); - } - get(name) { - const field = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); - if (!field) { - return null; - } - return field[0]; - } - getAll(name) { - const field = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); - if (!field) { - return []; - } - return field.slice(); - } - has(name) { - return FormData_classPrivateFieldGet(this, _FormData_entries, "f").has(String(name)); - } - delete(name) { - FormData_classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name)); - } - *keys() { - for (const key of FormData_classPrivateFieldGet(this, _FormData_entries, "f").keys()) { - yield key; - } - } - *entries() { - for (const name of this.keys()) { - const values = this.getAll(name); - for (const value of values) { - yield [name, value]; - } - } - } - *values() { - for (const [, value] of this) { - yield value; - } - } - [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) { - const methodName = append ? "append" : "set"; - if (argsLength < 2) { - throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` - + `2 arguments required, but only ${argsLength} present.`); - } - name = String(name); - let value; - if (isFile(rawValue)) { - value = fileName === undefined - ? rawValue - : new File([rawValue], fileName, { - type: rawValue.type, - lastModified: rawValue.lastModified - }); - } - else if (isBlob(rawValue)) { - value = new File([rawValue], fileName === undefined ? "blob" : fileName, { - type: rawValue.type - }); - } - else if (fileName) { - throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` - + "parameter 2 is not of type 'Blob'."); - } - else { - value = String(rawValue); - } - const values = FormData_classPrivateFieldGet(this, _FormData_entries, "f").get(name); - if (!values) { - return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); - } - if (!append) { - return void FormData_classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); - } - values.push(value); - }, Symbol.iterator)]() { - return this.entries(); - } - forEach(callback, thisArg) { - for (const [name, value] of this) { - callback.call(thisArg, value, name, this); - } - } - get [Symbol.toStringTag]() { - return "FormData"; - } - [external_util_.inspect.custom]() { - return this[Symbol.toStringTag]; - } -} + // cacheable-lookup integration hotfix + !utils.isUndefined(lookup) && (options.lookup = lookup); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/index.js + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } + let transport; + const isHttpsRequest = isHttps.test(options.protocol); + options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsRequest ? https__default["default"] : http__default["default"]; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + if (config.beforeRedirect) { + options.beforeRedirects.config = config.beforeRedirect; + } + transport = isHttpsRequest ? httpsFollow : httpFollow; + } + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } else { + // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited + options.maxBodyLength = Infinity; + } + if (config.insecureHTTPParser) { + options.insecureHTTPParser = config.insecureHTTPParser; + } -;// CONCATENATED MODULE: ./node_modules/openai/_shims/formdata.node.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ + // Create the request + req = transport.request(options, function handleResponse(res) { + if (req.destroyed) return; + const streams = [res]; + const responseLength = +res.headers['content-length']; + if (onDownloadProgress) { + const transformStream = new AxiosTransformStream$1({ + length: utils.toFiniteNumber(responseLength), + maxRate: utils.toFiniteNumber(maxDownloadRate) + }); + onDownloadProgress && transformStream.on('progress', progress => { + onDownloadProgress(Object.assign(progress, { + download: true + })); + }); -const formdata_node_isPolyfilled = true; + streams.push(transformStream); + } -;// CONCATENATED MODULE: external "node:stream" -const external_node_stream_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/createBoundary.js -const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; -function createBoundary() { - let size = 16; - let res = ""; - while (size--) { - res += alphabet[(Math.random() * alphabet.length) << 0]; - } - return res; -} -/* harmony default export */ const util_createBoundary = (createBoundary); + // decompress the response body transparently if required + let responseStream = res; -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isPlainObject.js -const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); -function isPlainObject(value) { - if (getType(value) !== "object") { - return false; - } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === undefined) { - return true; - } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); -} -/* harmony default export */ const util_isPlainObject = (isPlainObject); + // return the last request in case of redirects + const lastRequest = res.req || req; -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/normalizeValue.js -const normalizeValue = (value) => String(value) - .replace(/\r|\n/g, (match, i, str) => { - if ((match === "\r" && str[i + 1] !== "\n") - || (match === "\n" && str[i - 1] !== "\r")) { - return "\r\n"; - } - return match; -}); -/* harmony default export */ const util_normalizeValue = (normalizeValue); + // if decompress disabled we should not decompress + if (config.decompress !== false && res.headers['content-encoding']) { + // if no content, but headers still say that it is encoded, + // remove the header not confuse downstream operations + if (method === 'HEAD' || res.statusCode === 204) { + delete res.headers['content-encoding']; + } -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/escapeName.js -const escapeName = (name) => String(name) - .replace(/\r/g, "%0D") - .replace(/\n/g, "%0A") - .replace(/"/g, "%22"); -/* harmony default export */ const util_escapeName = (escapeName); + switch ((res.headers['content-encoding'] || '').toLowerCase()) { + /*eslint default-case:0*/ + case 'gzip': + case 'x-gzip': + case 'compress': + case 'x-compress': + // add the unzipper to the body stream processing pipeline + streams.push(zlib__default["default"].createUnzip(zlibOptions)); -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFunction.js -const isFunction_isFunction = (value) => (typeof value === "function"); -/* harmony default export */ const util_isFunction = (isFunction_isFunction); + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'deflate': + streams.push(new ZlibHeaderTransformStream$1()); -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFileLike.js + // add the unzipper to the body stream processing pipeline + streams.push(zlib__default["default"].createUnzip(zlibOptions)); -const isFileLike = (value) => Boolean(value - && typeof value === "object" - && util_isFunction(value.constructor) - && value[Symbol.toStringTag] === "File" - && util_isFunction(value.stream) - && value.name != null - && value.size != null - && value.lastModified != null); + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + case 'br': + if (isBrotliSupported) { + streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions)); + delete res.headers['content-encoding']; + } + } + } -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFormData.js + responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils.noop) : streams[0]; -const isFormData = (value) => Boolean(value - && util_isFunction(value.constructor) - && value[Symbol.toStringTag] === "FormData" - && util_isFunction(value.append) - && util_isFunction(value.getAll) - && util_isFunction(value.entries) - && util_isFunction(value[Symbol.iterator])); -const isFormDataLike = (/* unused pure expression or super */ null && (isFormData)); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/FormDataEncoder.js -var FormDataEncoder_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - 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"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var FormDataEncoder_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - 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"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader; + const offListeners = stream__default["default"].finished(responseStream, () => { + offListeners(); + onFinished(); + }); + const response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: new AxiosHeaders$1(res.headers), + config, + request: lastRequest + }; + if (responseType === 'stream') { + response.data = responseStream; + settle(resolve, reject, response); + } else { + const responseBuffer = []; + let totalResponseBytes = 0; + responseStream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + // stream.destroy() emit aborted event before calling reject() on Node.js v16 + rejected = true; + responseStream.destroy(); + reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); + } + }); + responseStream.on('aborted', function handlerStreamAborted() { + if (rejected) { + return; + } -const defaultOptions = { - enableAdditionalHeaders: false -}; -class FormDataEncoder { - constructor(form, boundaryOrOptions, options) { - _FormDataEncoder_instances.add(this); - _FormDataEncoder_CRLF.set(this, "\r\n"); - _FormDataEncoder_CRLF_BYTES.set(this, void 0); - _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0); - _FormDataEncoder_DASHES.set(this, "-".repeat(2)); - _FormDataEncoder_encoder.set(this, new TextEncoder()); - _FormDataEncoder_footer.set(this, void 0); - _FormDataEncoder_form.set(this, void 0); - _FormDataEncoder_options.set(this, void 0); - if (!isFormData(form)) { - throw new TypeError("Expected first argument to be a FormData instance."); - } - let boundary; - if (util_isPlainObject(boundaryOrOptions)) { - options = boundaryOrOptions; - } - else { - boundary = boundaryOrOptions; - } - if (!boundary) { - boundary = util_createBoundary(); - } - if (typeof boundary !== "string") { - throw new TypeError("Expected boundary argument to be a string."); - } - if (options && !util_isPlainObject(options)) { - throw new TypeError("Expected options argument to be an object."); - } - FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_form, form, "f"); - FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f"); - FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")), "f"); - FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f"); - this.boundary = `form-data-boundary-${boundary}`; - this.contentType = `multipart/form-data; boundary=${this.boundary}`; - FormDataEncoder_classPrivateFieldSet(this, _FormDataEncoder_footer, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f"); - this.contentLength = String(this.getContentLength()); - this.headers = Object.freeze({ - "Content-Type": this.contentType, - "Content-Length": this.contentLength - }); - Object.defineProperties(this, { - boundary: { writable: false, configurable: false }, - contentType: { writable: false, configurable: false }, - contentLength: { writable: false, configurable: false }, - headers: { writable: false, configurable: false } + const err = new AxiosError( + 'maxContentLength size of ' + config.maxContentLength + ' exceeded', + AxiosError.ERR_BAD_RESPONSE, + config, + lastRequest + ); + responseStream.destroy(err); + reject(err); }); - } - getContentLength() { - let length = 0; - for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f")) { - const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); - length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength; - length += isFileLike(value) ? value.size : value.byteLength; - length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f"); - } - return length + FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f").byteLength; - } - *values() { - for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f").entries()) { - const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value); - yield value; - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f"); - } - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f"); - } - async *encode() { - for (const part of this.values()) { - if (isFileLike(part)) { - yield* part.stream(); - } - else { - yield part; - } - } - } - [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) { - let header = ""; - header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; - header += `Content-Disposition: form-data; name="${util_escapeName(name)}"`; - if (isFileLike(value)) { - header += `; filename="${util_escapeName(value.name)}"${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; - header += `Content-Type: ${value.type || "application/octet-stream"}`; - } - if (FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) { - header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike(value) ? value.size : value.byteLength}`; - } - return FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${header}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`); - }, Symbol.iterator)]() { - return this.values(); - } - [Symbol.asyncIterator]() { - return this.encode(); - } -} -const Encoder = (/* unused pure expression or super */ null && (FormDataEncoder)); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/index.js + responseStream.on('error', function handleStreamError(err) { + if (req.destroyed) return; + reject(AxiosError.from(err, null, config, lastRequest)); + }); + responseStream.on('end', function handleStreamEnd() { + try { + let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); + if (responseType !== 'arraybuffer') { + responseData = responseData.toString(responseEncoding); + if (!responseEncoding || responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + response.data = responseData; + } catch (err) { + reject(AxiosError.from(err, null, config, response.request, response)); + } + settle(resolve, reject, response); + }); + } + emitter.once('abort', err => { + if (!responseStream.destroyed) { + responseStream.emit('error', err); + responseStream.destroy(); + } + }); + }); + emitter.once('abort', err => { + reject(err); + req.destroy(err); + }); + // Handle errors + req.on('error', function handleRequestError(err) { + // @todo remove + // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; + reject(AxiosError.from(err, null, config, req)); + }); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/getMultipartRequestOptions.node.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ + // set tcp keep alive to prevent drop connection by peer + req.on('socket', function handleRequestSocket(socket) { + // default interval of sending ack packet is 1 minute + socket.setKeepAlive(true, 1000 * 60); + }); + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + const timeout = parseInt(config.timeout, 10); + if (Number.isNaN(timeout)) { + reject(new AxiosError( + 'error trying to parse `config.timeout` to int', + AxiosError.ERR_BAD_OPTION_VALUE, + config, + req + )); -async function getMultipartRequestOptions_node_getMultipartRequestOptions(form, opts) { - const encoder = new FormDataEncoder(form); - const readable = external_node_stream_namespaceObject.Readable.from(encoder); - const body = new MultipartBody(readable); - const headers = { - ...opts.headers, - ...encoder.headers, - 'Content-Length': encoder.contentLength, - }; - return { ...opts, body: body, headers }; -} -//# sourceMappingURL=getMultipartRequestOptions.node.mjs.map - -// EXTERNAL MODULE: external "fs" -var external_fs_ = __nccwpck_require__(7147); -// EXTERNAL MODULE: external "path" -var external_path_ = __nccwpck_require__(1017); -// EXTERNAL MODULE: ./node_modules/node-domexception/index.js -var node_domexception = __nccwpck_require__(7760); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isPlainObject.js -const isPlainObject_getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); -function isPlainObject_isPlainObject(value) { - if (isPlainObject_getType(value) !== "object") { - return false; - } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === undefined) { - return true; - } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); -} -/* harmony default export */ const esm_isPlainObject = (isPlainObject_isPlainObject); + return; + } -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/fileFromPath.js -var fileFromPath_classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - 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"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var fileFromPath_classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - 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"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _FileFromPath_path, _FileFromPath_start; + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devouring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + if (isDone) return; + let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + req + )); + abort(); + }); + } + // Send the request + if (utils.isStream(data)) { + let ended = false; + let errored = false; + data.on('end', () => { + ended = true; + }); + data.once('error', err => { + errored = true; + req.destroy(err); + }); + data.on('close', () => { + if (!ended && !errored) { + abort(new CanceledError('Request stream has been aborted', config, req)); + } + }); -const MESSAGE = "The requested file could not be read, " - + "typically due to permission problems that have occurred after a reference " - + "to a file was acquired."; -class FileFromPath { - constructor(input) { - _FileFromPath_path.set(this, void 0); - _FileFromPath_start.set(this, void 0); - fileFromPath_classPrivateFieldSet(this, _FileFromPath_path, input.path, "f"); - fileFromPath_classPrivateFieldSet(this, _FileFromPath_start, input.start || 0, "f"); - this.name = (0,external_path_.basename)(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f")); - this.size = input.size; - this.lastModified = input.lastModified; - } - slice(start, end) { - return new FileFromPath({ - path: fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"), - lastModified: this.lastModified, - size: end - start, - start - }); + data.pipe(req); + } else { + req.end(data); } - async *stream() { - const { mtimeMs } = await external_fs_.promises.stat(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f")); - if (mtimeMs > this.lastModified) { - throw new node_domexception(MESSAGE, "NotReadableError"); + }); +}; + +const cookies = platform.isStandardBrowserEnv ? + +// Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + const cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); } - if (this.size) { - yield* (0,external_fs_.createReadStream)(fileFromPath_classPrivateFieldGet(this, _FileFromPath_path, "f"), { - start: fileFromPath_classPrivateFieldGet(this, _FileFromPath_start, "f"), - end: fileFromPath_classPrivateFieldGet(this, _FileFromPath_start, "f") + this.size - 1 - }); + + if (utils.isString(path)) { + cookie.push('path=' + path); } - } - get [(_FileFromPath_path = new WeakMap(), _FileFromPath_start = new WeakMap(), Symbol.toStringTag)]() { - return "File"; - } -} -function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) { - let filename; - if (esm_isPlainObject(filenameOrOptions)) { - [options, filename] = [filenameOrOptions, undefined]; - } - else { - filename = filenameOrOptions; - } - const file = new FileFromPath({ path, size, lastModified: mtimeMs }); - if (!filename) { - filename = file.name; - } - return new File([file], filename, { - ...options, lastModified: file.lastModified - }); -} -function fileFromPathSync(path, filenameOrOptions, options = {}) { - const stats = statSync(path); - return createFileFromPath(path, stats, filenameOrOptions, options); -} -async function fileFromPath(path, filenameOrOptions, options) { - const stats = await external_fs_.promises.stat(path); - return createFileFromPath(path, stats, filenameOrOptions, options); -} -;// CONCATENATED MODULE: ./node_modules/openai/_shims/fileFromPath.node.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } -let warned = false; -async function fileFromPath_node_fileFromPath(path, ...args) { - if (!warned) { - console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); - warned = true; - } - return await fileFromPath(path, ...args); -} -//# sourceMappingURL=fileFromPath.node.mjs.map + if (secure === true) { + cookie.push('secure'); + } -;// CONCATENATED MODULE: external "node:fs" -const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/node-readable.node.mjs + document.cookie = cookie.join('; '); + }, -function isFsReadStream(value) { - return value instanceof external_node_fs_namespaceObject.ReadStream; -} -//# sourceMappingURL=node-readable.node.mjs.map + read: function read(name) { + const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, -;// CONCATENATED MODULE: ./node_modules/openai/uploads.mjs + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : +// Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })(); +const isURLSameOrigin = platform.isStandardBrowserEnv ? +// Standard browser envs have full support of the APIs needed to test +// whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + const msie = /(msie|trident)/i.test(navigator.userAgent); + const urlParsingNode = document.createElement('a'); + let originURL; + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + let href = url; -const isResponseLike = (value) => - value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -const uploads_isFileLike = (value) => - value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - isBlobLike(value); -/** - * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check - * adds the arrayBuffer() method type because it is available and used at runtime - */ -const isBlobLike = (value) => - value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -const isUploadable = (value) => { - return uploads_isFileLike(value) || isResponseLike(value) || isFsReadStream(value); -}; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function toFile(value, name, options = {}) { - var _a, _b, _c; - // If it's a promise, resolve it. - value = await value; - if (isResponseLike(value)) { - const blob = await value.blob(); - name || - (name = - (_a = new URL(value.url).pathname.split(/[\\/]/).pop()) !== null && _a !== void 0 ? - _a - : 'unknown_file'); - return new File([blob], name, options); - } - const bits = await getBytes(value); - name || (name = (_b = getName(value)) !== null && _b !== void 0 ? _b : 'unknown_file'); - if (!options.type) { - const type = (_c = bits[0]) === null || _c === void 0 ? void 0 : _c.type; - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return new File(bits, name, options); -} -async function getBytes(value) { - var _a; - let parts = []; - if ( - typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer - ) { - parts.push(value); - } else if (isBlobLike(value)) { - parts.push(await value.arrayBuffer()); - } else if ( - isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(chunk); // TODO, consider validating? - } - } else { - throw new Error( - `Unexpected data type: ${typeof value}; constructor: ${ - (_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? - void 0 - : _a.name - }; props: ${propsForError(value)}`, - ); - } - return parts; -} -function propsForError(value) { - const props = Object.getOwnPropertyNames(value); - return `[${props.map((p) => `"${p}"`).join(', ')}]`; -} -function getName(value) { - var _a; - return ( - getStringFromMaybeBuffer(value.name) || - getStringFromMaybeBuffer(value.filename) || - // For fs.ReadStream - ((_a = getStringFromMaybeBuffer(value.path)) === null || _a === void 0 ? void 0 : _a.split(/[\\/]/).pop()) - ); -} -const getStringFromMaybeBuffer = (x) => { - if (typeof x === 'string') return x; - if (typeof Buffer !== 'undefined' && x instanceof Buffer) return String(x); - return undefined; -}; -const isAsyncIterableIterator = (value) => - value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -class MultipartBody { - constructor(body) { - this.body = body; - } - get [Symbol.toStringTag]() { - return 'MultipartBody'; - } -} -const isMultipartBody = (body) => - body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const maybeMultipartFormRequestOptions = async (opts) => { - if (!hasUploadableValue(opts.body)) return opts; - const form = await createForm(opts.body); - return getMultipartRequestOptions(form, opts); -}; -const multipartFormRequestOptions = async (opts) => { - const form = await createForm(opts.body); - return getMultipartRequestOptions_node_getMultipartRequestOptions(form, opts); -}; -const createForm = async (body) => { - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; -}; -const hasUploadableValue = (value) => { - if (isUploadable(value)) return true; - if (Array.isArray(value)) return value.some(hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (hasUploadableValue(value[k])) return true; + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; } - } - return false; -}; -const addFormValue = async (form, key, value) => { - if (value === undefined) return; - if (value == null) { - throw new TypeError( - `Received null for "${key}"; to pass null in FormData, you must use the string 'null'`, - ); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } else if (isUploadable(value)) { - const file = await toFile(value); - form.append(key, file); - } else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); - } else if (typeof value === 'object') { - await Promise.all( - Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)), - ); - } else { - throw new TypeError( - `Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`, - ); - } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core.mjs -var core_classPrivateFieldSet = - (undefined && undefined.__classPrivateFieldSet) || - function (receiver, state, value, kind, f) { - if (kind === 'm') throw new TypeError('Private method is not writable'); - if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a setter'); - 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'); - return ( - kind === 'a' ? f.call(receiver, value) - : f ? (f.value = value) - : state.set(receiver, value), - value - ); - }; -var core_classPrivateFieldGet = - (undefined && undefined.__classPrivateFieldGet) || - function (receiver, state, kind, f) { - if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter'); - 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'); - return ( - kind === 'm' ? f - : kind === 'a' ? f.call(receiver) - : f ? f.value - : state.get(receiver) - ); - }; -var _AbstractPage_client; + originURL = resolveURL(window.location.href); + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })(); +function progressEventReducer(listener, isDownloadStream) { + let bytesNotified = 0; + const _speedometer = speedometer(50, 250); + return e => { + const loaded = e.loaded; + const total = e.lengthComputable ? e.total : undefined; + const progressBytes = loaded - bytesNotified; + const rate = _speedometer(progressBytes); + const inRange = loaded <= total; + bytesNotified = loaded; + const data = { + loaded, + total, + progress: total ? (loaded / total) : undefined, + bytes: progressBytes, + rate: rate ? rate : undefined, + estimated: rate && total && inRange ? (total - loaded) / rate : undefined, + event: e + }; -const MAX_RETRIES = 2; -async function defaultParseResponse(props) { - const { response } = props; - if (props.options.stream) { - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - return new Stream(response, props.controller); - } - const contentType = response.headers.get('content-type'); - if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { - const json = await response.json(); - debug('response', response.status, response.url, response.headers, json); - return json; - } - // TODO handle blob, arraybuffer, other content types, etc. - const text = await response.text(); - debug('response', response.status, response.url, response.headers, text); - return text; -} -/** - * A subclass of `Promise` providing additional helper methods - * for interacting with the SDK. - */ -class APIPromise extends Promise { - constructor(responsePromise, parseResponse = defaultParseResponse) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - } - _thenUnwrap(transform) { - return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data and the raw `Response` instance. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then(this.parseResponse); - } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); - } + data[isDownloadStream ? 'download' : 'upload'] = true; + + listener(data); + }; } -class APIClient { - constructor({ - baseURL, - maxRetries, - timeout = 600000, // 10 minutes - httpAgent, - fetch: overridenFetch, - }) { - this.baseURL = baseURL; - this.maxRetries = validatePositiveInteger( - 'maxRetries', - maxRetries !== null && maxRetries !== void 0 ? maxRetries : MAX_RETRIES, - ); - this.timeout = validatePositiveInteger('timeout', timeout); - this.httpAgent = httpAgent; - this.fetch = overridenFetch !== null && overridenFetch !== void 0 ? overridenFetch : _fetch; - } - authHeaders(opts) { - return {}; - } - /** - * Override this to add your own default headers, for example: - * - * { - * ...super.defaultHeaders(), - * Authorization: 'Bearer 123', - * } - */ - defaultHeaders(opts) { - return { - Accept: 'application/json', - 'Content-Type': 'application/json', - 'User-Agent': this.getUserAgent(), - ...getPlatformHeaders(), - ...this.authHeaders(opts), - }; - } - /** - * Override this to add your own headers validation: - */ - validateHeaders(headers, customHeaders) {} - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid4()}`; - } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); - } - calculateContentLength(body) { - if (typeof body === 'string') { - if (typeof Buffer !== 'undefined') { - return Buffer.byteLength(body, 'utf8').toString(); + +const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + +const xhrAdapter = isXHRAdapterSupported && function (config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + let requestData = config.data; + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); + const responseType = config.responseType; + let onCanceled; + function done() { + if (config.cancelToken) { + config.cancelToken.unsubscribe(onCanceled); } - if (typeof TextEncoder !== 'undefined') { - const encoder = new TextEncoder(); - const encoded = encoder.encode(body); - return encoded.length.toString(); + + if (config.signal) { + config.signal.removeEventListener('abort', onCanceled); } } - return null; - } - buildRequest(options) { - var _a, _b, _c, _d, _e, _f; - const { method, path, query, headers: headers = {} } = options; - const body = - isMultipartBody(options.body) ? options.body.body - : options.body ? JSON.stringify(options.body, null, 2) - : null; - const contentLength = this.calculateContentLength(body); - const url = this.buildURL(path, query); - if ('timeout' in options) validatePositiveInteger('timeout', options.timeout); - const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.timeout; - const httpAgent = - ( - (_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null && - _c !== void 0 - ) ? - _c - : getDefaultAgent(url); - const minAgentTimeout = timeout + 1000; - if ( - typeof (( - (_d = httpAgent === null || httpAgent === void 0 ? void 0 : httpAgent.options) === null || - _d === void 0 - ) ? - void 0 - : _d.timeout) === 'number' && - minAgentTimeout > ((_e = httpAgent.options.timeout) !== null && _e !== void 0 ? _e : 0) - ) { - // Allow any given request to bump our agent active socket timeout. - // This may seem strange, but leaking active sockets should be rare and not particularly problematic, - // and without mutating agent we would need to create more of them. - // This tradeoff optimizes for performance. - httpAgent.options.timeout = minAgentTimeout; - } - if (this.idempotencyHeader && method !== 'get') { - if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); - headers[this.idempotencyHeader] = options.idempotencyKey; + + let contentType; + + if (utils.isFormData(requestData)) { + if (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv) { + requestHeaders.setContentType(false); // Let the browser set it + } else if(!requestHeaders.getContentType(/^\s*multipart\/form-data/)){ + requestHeaders.setContentType('multipart/form-data'); // mobile/desktop app frameworks + } else if(utils.isString(contentType = requestHeaders.getContentType())){ + // fix semicolon duplication issue for ReactNative FormData implementation + requestHeaders.setContentType(contentType.replace(/^\s*(multipart\/form-data);+/, '$1')); + } } - const reqHeaders = { - ...(contentLength && { 'Content-Length': contentLength }), - ...this.defaultHeaders(options), - ...headers, - }; - // let builtin fetch set the Content-Type for multipart bodies - if (isMultipartBody(options.body) && !isPolyfilled) { - delete reqHeaders['Content-Type']; + + let request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + const username = config.auth.username || ''; + const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password)); } - // Strip any headers being explicitly omitted with null - Object.keys(reqHeaders).forEach((key) => reqHeaders[key] === null && delete reqHeaders[key]); - const req = { - method, - ...(body && { body: body }), - headers: reqHeaders, - ...(httpAgent && { agent: httpAgent }), - // @ts-ignore node-fetch uses a custom AbortSignal type that is - // not compatible with standard web types - signal: (_f = options.signal) !== null && _f !== void 0 ? _f : null, - }; - this.validateHeaders(reqHeaders, headers); - return { req, url, timeout }; - } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) {} - parseHeaders(headers) { - return ( - !headers ? {} - : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) - : { ...headers } - ); - } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); - } - request(options, remainingRetries = null) { - return new APIPromise(this.makeRequest(options, remainingRetries)); - } - async makeRequest(optionsInput, retriesRemaining) { - var _a, _b, _c; - const options = await optionsInput; - if (retriesRemaining == null) { - retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries; + + const fullPath = buildFullPath(config.baseURL, config.url); + + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + const responseHeaders = AxiosHeaders$1.from( + 'getAllResponseHeaders' in request && request.getAllResponseHeaders() + ); + const responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + const response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config, + request + }; + + settle(function _resolve(value) { + resolve(value); + done(); + }, function _reject(err) { + reject(err); + done(); + }, response); + + // Clean up request + request = null; } - const { req, url, timeout } = this.buildRequest(options); - await this.prepareRequest(req, { url, options }); - debug('request', url, options, req.headers); - if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) { - throw new APIUserAbortError(); + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); - if (response instanceof Error) { - if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) { - throw new APIUserAbortError(); + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; } - if (retriesRemaining) { - return this.retryRequest(options, retriesRemaining); + + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; + const transitional = config.transitional || transitionalDefaults; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; } - if (response.name === 'AbortError') { - throw new APIConnectionTimeoutError(); + reject(new AxiosError( + timeoutErrorMessage, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, + config, + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (platform.isStandardBrowserEnv) { + // Add xsrf header + const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) + && config.xsrfCookieName && cookies.read(config.xsrfCookieName); + + if (xsrfValue) { + requestHeaders.set(config.xsrfHeaderName, xsrfValue); } - throw new APIConnectionError({ cause: response }); } - const responseHeaders = createResponseHeaders(response.headers); - if (!response.ok) { - if (retriesRemaining && this.shouldRetry(response)) { - return this.retryRequest(options, retriesRemaining, responseHeaders); + + // Remove Content-Type if data is undefined + requestData === undefined && requestHeaders.setContentType(null); + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { + request.setRequestHeader(key, val); + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); + } + + if (config.cancelToken || config.signal) { + // Handle cancellation + // eslint-disable-next-line func-names + onCanceled = cancel => { + if (!request) { + return; + } + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); + request.abort(); + request = null; + }; + + config.cancelToken && config.cancelToken.subscribe(onCanceled); + if (config.signal) { + config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); } - const errText = await response.text().catch(() => 'Unknown'); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - debug('response', response.status, url, responseHeaders, errMessage); - const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); - throw err; } - return { response, options, controller }; - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null); - return new PagePromise(this, request, Page); - } - buildURL(path, query) { - const url = - isAbsoluteURL(path) ? - new URL(path) - : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; + + const protocol = parseProtocol(fullPath); + + if (protocol && platform.protocols.indexOf(protocol) === -1) { + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); + return; } - if (query) { - url.search = this.stringifyQuery(query); + + + // Send the request + request.send(requestData || null); + }); +}; + +const knownAdapters = { + http: httpAdapter, + xhr: xhrAdapter +}; + +utils.forEach(knownAdapters, (fn, value) => { + if (fn) { + try { + Object.defineProperty(fn, 'name', {value}); + } catch (e) { + // eslint-disable-next-line no-empty } - return url.toString(); + Object.defineProperty(fn, 'adapterName', {value}); } - stringifyQuery(query) { - return Object.entries(query) - .filter(([_, value]) => typeof value !== 'undefined') - .map(([key, value]) => { - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - } - if (value === null) { - return `${encodeURIComponent(key)}=`; +}); + +const renderReason = (reason) => `- ${reason}`; + +const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; + +const adapters = { + getAdapter: (adapters) => { + adapters = utils.isArray(adapters) ? adapters : [adapters]; + + const {length} = adapters; + let nameOrAdapter; + let adapter; + + const rejectedReasons = {}; + + for (let i = 0; i < length; i++) { + nameOrAdapter = adapters[i]; + let id; + + adapter = nameOrAdapter; + + if (!isResolvedHandle(nameOrAdapter)) { + adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + + if (adapter === undefined) { + throw new AxiosError(`Unknown adapter '${id}'`); } - throw new Error( - `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`, + } + + if (adapter) { + break; + } + + rejectedReasons[id || '#' + i] = adapter; + } + + if (!adapter) { + + const reasons = Object.entries(rejectedReasons) + .map(([id, state]) => `adapter ${id} ` + + (state === false ? 'is not supported by the environment' : 'is not available in the build') ); - }) - .join('&'); - } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, ...options } = init || {}; - if (signal) signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - return this.getRequestClient() - .fetch(url, { signal: controller.signal, ...options }) - .finally(() => { - clearTimeout(timeout); - }); + + let s = length ? + (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : + 'as no adapter specified'; + + throw new AxiosError( + `There is no suitable adapter to dispatch the request ` + s, + 'ERR_NOT_SUPPORT' + ); + } + + return adapter; + }, + adapters: knownAdapters +}; + +/** + * Throws a `CanceledError` if cancellation has been requested. + * + * @param {Object} config The config that is to be used for the request + * + * @returns {void} + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); } - getRequestClient() { - return { fetch: this.fetch }; + + if (config.signal && config.signal.aborted) { + throw new CanceledError(null, config); } - shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') return true; - if (shouldRetryHeader === 'false') return false; - // Retry on lock timeouts. - if (response.status === 409) return true; - // Retry on rate limits. - if (response.status === 429) return true; - // Retry internal errors. - if (response.status >= 500) return true; - return false; +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * + * @returns {Promise} The Promise to be fulfilled + */ +function dispatchRequest(config) { + throwIfCancellationRequested(config); + + config.headers = AxiosHeaders$1.from(config.headers); + + // Transform request data + config.data = transformData.call( + config, + config.transformRequest + ); + + if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { + config.headers.setContentType('application/x-www-form-urlencoded', false); } - async retryRequest(options, retriesRemaining, responseHeaders) { - var _a; - retriesRemaining -= 1; - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - // - // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: ". - // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details. - const retryAfter = parseInt( - (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) || - '', + + const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter); + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + config.transformResponse, + response ); - const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries; - const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000; - await sleep(timeout); - return this.makeRequest(options, retriesRemaining); + + response.headers = AxiosHeaders$1.from(response.headers); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + config.transformResponse, + reason.response + ); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); + } + } + + return Promise.reject(reason); + }); +} + +const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing; + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * + * @returns {Object} New object resulting from merging config2 to config1 + */ +function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + const config = {}; + + function getMergedValue(target, source, caseless) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge.call({caseless}, target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + // eslint-disable-next-line consistent-return + function mergeDeepProperties(a, b, caseless) { + if (!utils.isUndefined(b)) { + return getMergedValue(a, b, caseless); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a, caseless); + } } - calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 2; - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says. - if (Number.isInteger(retryAfter) && retryAfter <= 60) { - return retryAfter; + + // eslint-disable-next-line consistent-return + function valueFromConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); } - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay); - // Apply some jitter, plus-or-minus half a second. - const jitter = Math.random() - 0.5; - return sleepSeconds + jitter; } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; + + // eslint-disable-next-line consistent-return + function defaultToConfig2(a, b) { + if (!utils.isUndefined(b)) { + return getMergedValue(undefined, b); + } else if (!utils.isUndefined(a)) { + return getMergedValue(undefined, a); + } } -} -class APIResource { - constructor(client) { - this.client = client; - this.get = client.get.bind(client); - this.post = client.post.bind(client); - this.patch = client.patch.bind(client); - this.put = client.put.bind(client); - this.delete = client.delete.bind(client); - this.getAPIList = client.getAPIList.bind(client); + + // eslint-disable-next-line consistent-return + function mergeDirectKeys(a, b, prop) { + if (prop in config2) { + return getMergedValue(a, b); + } else if (prop in config1) { + return getMergedValue(undefined, a); + } } + + const mergeMap = { + url: valueFromConfig2, + method: valueFromConfig2, + data: valueFromConfig2, + baseURL: defaultToConfig2, + transformRequest: defaultToConfig2, + transformResponse: defaultToConfig2, + paramsSerializer: defaultToConfig2, + timeout: defaultToConfig2, + timeoutMessage: defaultToConfig2, + withCredentials: defaultToConfig2, + adapter: defaultToConfig2, + responseType: defaultToConfig2, + xsrfCookieName: defaultToConfig2, + xsrfHeaderName: defaultToConfig2, + onUploadProgress: defaultToConfig2, + onDownloadProgress: defaultToConfig2, + decompress: defaultToConfig2, + maxContentLength: defaultToConfig2, + maxBodyLength: defaultToConfig2, + beforeRedirect: defaultToConfig2, + transport: defaultToConfig2, + httpAgent: defaultToConfig2, + httpsAgent: defaultToConfig2, + cancelToken: defaultToConfig2, + socketPath: defaultToConfig2, + responseEncoding: defaultToConfig2, + validateStatus: mergeDirectKeys, + headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) + }; + + utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { + const merge = mergeMap[prop] || mergeDeepProperties; + const configValue = merge(config1[prop], config2[prop], prop); + (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); + }); + + return config; } -class AbstractPage { - constructor(client, response, body, options) { - _AbstractPage_client.set(this, void 0); - core_classPrivateFieldSet(this, _AbstractPage_client, client, 'f'); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) return false; - return this.nextPageInfo() != null; + +const validators$1 = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { + validators$1[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +const deprecatedWarnings = {}; + +/** + * Transitional option validator + * + * @param {function|boolean?} validator - set to false if the transitional option has been removed + * @param {string?} version - deprecated version / removed since version + * @param {string?} message - some message with additional info + * + * @returns {function} + */ +validators$1.transitional = function transitional(validator, version, message) { + function formatMessage(opt, desc) { + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } - async getNextPage() { - const nextInfo = this.nextPageInfo(); - if (!nextInfo) { - throw new Error( - 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.', + + // eslint-disable-next-line func-names + return (value, opt, opts) => { + if (validator === false) { + throw new AxiosError( + formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), + AxiosError.ERR_DEPRECATED ); } - const nextOptions = { ...this.options }; - if ('params' in nextInfo) { - nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; - } else if ('url' in nextInfo) { - const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; - for (const [key, value] of params) { - nextInfo.url.searchParams.set(key, value); - } - nextOptions.query = undefined; - nextOptions.path = nextInfo.url.toString(); - } - return await core_classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList( - this.constructor, - nextOptions, - ); - } - async *iterPages() { - // eslint-disable-next-line @typescript-eslint/no-this-alias - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; + + if (version && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +/** + * Assert object's properties type + * + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + * + * @returns {object} + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); } - async *[((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; + const keys = Object.keys(options); + let i = keys.length; + while (i-- > 0) { + const opt = keys[i]; + const validator = schema[opt]; + if (validator) { + const value = options[opt]; + const result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); } + continue; + } + if (allowUnknown !== true) { + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); } } } + +const validator = { + assertOptions, + validators: validators$1 +}; + +const validators = validator.validators; + /** - * This subclass of Promise will resolve to an instantiated Page once the request completes. + * Create a new instance of Axios * - * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * @param {Object} instanceConfig The default config for the instance * - * for await (const item of client.items.list()) { - * console.log(item) - * } + * @return {Axios} A new instance of Axios */ -class PagePromise extends APIPromise { - constructor(client, request, Page) { - super( - request, - async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options), - ); +class Axios { + constructor(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager$1(), + response: new InterceptorManager$1() + }; } + /** - * Allow auto-paginating iteration on an unawaited list call, eg: + * Dispatch a request * - * for await (const item of client.items.list()) { - * console.log(item) - * } + * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) + * @param {?Object} config + * + * @returns {Promise} The Promise to be fulfilled */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; + request(configOrUrl, config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof configOrUrl === 'string') { + config = config || {}; + config.url = configOrUrl; + } else { + config = configOrUrl || {}; } - } -} -const createResponseHeaders = (headers) => { - return new Proxy( - Object.fromEntries( - // @ts-ignore - headers.entries(), - ), - { - get(target, name) { - const key = name.toString(); - return target[key.toLowerCase()] || target[key]; - }, - }, - ); -}; -// This is required so that we can determine if a given object matches the RequestOptions -// type at runtime. While this requires duplication, it is enforced by the TypeScript -// compiler such that any missing / extraneous keys will cause an error. -const requestOptionsKeys = { - method: true, - path: true, - query: true, - body: true, - headers: true, - maxRetries: true, - stream: true, - timeout: true, - httpAgent: true, - signal: true, - idempotencyKey: true, -}; -const isRequestOptions = (obj) => { - return ( - typeof obj === 'object' && - obj !== null && - !isEmptyObj(obj) && - Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)) - ); -}; -const getPlatformProperties = () => { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': Deno.version, - }; - } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': process.version, - }; - } - // Check if Node.js - if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(process.platform), - 'X-Stainless-Arch': normalizeArch(process.arch), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': process.version, - }; - } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; - } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; - } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; + + config = mergeConfig(this.defaults, config); + + const {transitional, paramsSerializer, headers} = config; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean), + forcedJSONParsing: validators.transitional(validators.boolean), + clarifyTimeoutError: validators.transitional(validators.boolean) + }, false); } + + if (paramsSerializer != null) { + if (utils.isFunction(paramsSerializer)) { + config.paramsSerializer = { + serialize: paramsSerializer + }; + } else { + validator.assertOptions(paramsSerializer, { + encode: validators.function, + serialize: validators.function + }, true); + } + } + + // Set config.method + config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + + // Flatten headers + let contextHeaders = headers && utils.merge( + headers.common, + headers[config.method] + ); + + headers && utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + (method) => { + delete headers[method]; + } + ); + + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + + // filter out skipped interceptors + const requestInterceptorChain = []; + let synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + const responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + let promise; + let i = 0; + let len; + + if (!synchronousRequestInterceptors) { + const chain = [dispatchRequest.bind(this), undefined]; + chain.unshift.apply(chain, requestInterceptorChain); + chain.push.apply(chain, responseInterceptorChain); + len = chain.length; + + promise = Promise.resolve(config); + + while (i < len) { + promise = promise.then(chain[i++], chain[i++]); + } + + return promise; + } + + len = requestInterceptorChain.length; + + let newConfig = config; + + i = 0; + + while (i < len) { + const onFulfilled = requestInterceptorChain[i++]; + const onRejected = requestInterceptorChain[i++]; + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected.call(this, error); + break; + } + } + + try { + promise = dispatchRequest.call(this, newConfig); + } catch (error) { + return Promise.reject(error); + } + + i = 0; + len = responseInterceptorChain.length; + + while (i < len) { + promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + } + + return promise; } - return null; -} -const normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') return 'x32'; - if (arch === 'x86_64' || arch === 'x64') return 'x64'; - if (arch === 'arm') return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') return 'arm64'; - if (arch) return `other:${arch}`; - return 'unknown'; -}; -const normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) return 'iOS'; - if (platform === 'android') return 'Android'; - if (platform === 'darwin') return 'MacOS'; - if (platform === 'win32') return 'Windows'; - if (platform === 'freebsd') return 'FreeBSD'; - if (platform === 'openbsd') return 'OpenBSD'; - if (platform === 'linux') return 'Linux'; - if (platform) return `Other:${platform}`; - return 'Unknown'; -}; -let _platformHeaders; -const getPlatformHeaders = () => { - return _platformHeaders !== null && _platformHeaders !== void 0 ? - _platformHeaders - : (_platformHeaders = getPlatformProperties()); -}; -const safeJSON = (text) => { - try { - return JSON.parse(text); - } catch (err) { - return undefined; - } -}; -// https://stackoverflow.com/a/19709846 -const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); -const isAbsoluteURL = (url) => { - return startsWithSchemeRegexp.test(url); -}; -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -const validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new Error(`${name} must be an integer`); - } - if (n < 0) { - throw new Error(`${name} must be a positive integer`); + + getUri(config) { + config = mergeConfig(this.defaults, config); + const fullPath = buildFullPath(config.baseURL, config.url); + return buildURL(fullPath, config.params, config.paramsSerializer); } - return n; -}; -const castToError = (err) => { - if (err instanceof Error) return err; - return new Error(err); -}; -const ensurePresent = (value) => { - if (value == null) throw new Error(`Expected a value to be given but received ${value} instead.`); - return value; -}; +} + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method, + url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + + function generateHTTPMethod(isForm) { + return function httpMethod(url, data, config) { + return this.request(mergeConfig(config || {}, { + method, + headers: isForm ? { + 'Content-Type': 'multipart/form-data' + } : {}, + url, + data + })); + }; + } + + Axios.prototype[method] = generateHTTPMethod(); + + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); +}); + +const Axios$1 = Axios; + /** - * Read an environment variable. + * A `CancelToken` is an object that can be used to request cancellation of an operation. * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. + * @param {Function} executor The executor function. + * + * @returns {CancelToken} */ -const readEnv = (env) => { - var _a, _b, _c, _d; - if (typeof process !== 'undefined') { - return (_b = (_a = process.env) === null || _a === void 0 ? void 0 : _a[env]) !== null && _b !== void 0 ? - _b - : undefined; - } - if (typeof Deno !== 'undefined') { - return (_d = (_c = Deno.env) === null || _c === void 0 ? void 0 : _c.get) === null || _d === void 0 ? - void 0 - : _d.call(_c, env); +class CancelToken { + constructor(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + let resolvePromise; + + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + const token = this; + + // eslint-disable-next-line func-names + this.promise.then(cancel => { + if (!token._listeners) return; + + let i = token._listeners.length; + + while (i-- > 0) { + token._listeners[i](cancel); + } + token._listeners = null; + }); + + // eslint-disable-next-line func-names + this.promise.then = onfulfilled => { + let _resolve; + // eslint-disable-next-line func-names + const promise = new Promise(resolve => { + token.subscribe(resolve); + _resolve = resolve; + }).then(onfulfilled); + + promise.cancel = function reject() { + token.unsubscribe(_resolve); + }; + + return promise; + }; + + executor(function cancel(message, config, request) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new CanceledError(message, config, request); + resolvePromise(token.reason); + }); } - return undefined; -}; -const coerceInteger = (value) => { - if (typeof value === 'number') return Math.round(value); - if (typeof value === 'string') return parseInt(value, 10); - throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceFloat = (value) => { - if (typeof value === 'number') return value; - if (typeof value === 'string') return parseFloat(value); - throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceBoolean = (value) => { - if (typeof value === 'boolean') return value; - if (typeof value === 'string') return value === 'true'; - return Boolean(value); -}; -const maybeCoerceInteger = (value) => { - if (value === undefined) { - return undefined; + + /** + * Throws a `CanceledError` if cancellation has been requested. + */ + throwIfRequested() { + if (this.reason) { + throw this.reason; + } } - return coerceInteger(value); -}; -const maybeCoerceFloat = (value) => { - if (value === undefined) { - return undefined; + + /** + * Subscribe to the cancel signal + */ + + subscribe(listener) { + if (this.reason) { + listener(this.reason); + return; + } + + if (this._listeners) { + this._listeners.push(listener); + } else { + this._listeners = [listener]; + } } - return coerceFloat(value); -}; -const maybeCoerceBoolean = (value) => { - if (value === undefined) { - return undefined; + + /** + * Unsubscribe from the cancel signal + */ + + unsubscribe(listener) { + if (!this._listeners) { + return; + } + const index = this._listeners.indexOf(listener); + if (index !== -1) { + this._listeners.splice(index, 1); + } } - return coerceBoolean(value); -}; -// https://stackoverflow.com/a/34491287 -function isEmptyObj(obj) { - if (!obj) return true; - for (const _k in obj) return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function debug(action, ...args) { - if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') { - console.log(`OpenAI:DEBUG:${action}`, ...args); + + /** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ + static source() { + let cancel; + const token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token, + cancel + }; } } + +const CancelToken$1 = CancelToken; + /** - * https://stackoverflow.com/a/2117523 + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * + * @returns {Function} */ -const uuid4 = () => { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { - const r = (Math.random() * 16) | 0; - const v = c === 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -}; -const isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined' - ); -}; -const isHeadersProtocol = (headers) => { - return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function'; -}; -const getHeader = (headers, key) => { - const lowerKey = key.toLowerCase(); - if (isHeadersProtocol(headers)) return headers.get(key) || headers.get(lowerKey); - const value = headers[key] || headers[lowerKey]; - if (Array.isArray(value)) { - if (value.length <= 1) return value[0]; - console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`); - return value[0]; - } - return value; -}; +function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +} + /** - * Encodes a string to Base64 format. + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ -const toBase64 = (str) => { - if (!str) return ''; - if (typeof Buffer !== 'undefined') { - return Buffer.from(str).toString('base64'); - } - if (typeof btoa !== 'undefined') { - return btoa(str); - } - throw new Error('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +function isAxiosError(payload) { + return utils.isObject(payload) && (payload.isAxiosError === true); +} + +const HttpStatusCode = { + Continue: 100, + SwitchingProtocols: 101, + Processing: 102, + EarlyHints: 103, + Ok: 200, + Created: 201, + Accepted: 202, + NonAuthoritativeInformation: 203, + NoContent: 204, + ResetContent: 205, + PartialContent: 206, + MultiStatus: 207, + AlreadyReported: 208, + ImUsed: 226, + MultipleChoices: 300, + MovedPermanently: 301, + Found: 302, + SeeOther: 303, + NotModified: 304, + UseProxy: 305, + Unused: 306, + TemporaryRedirect: 307, + PermanentRedirect: 308, + BadRequest: 400, + Unauthorized: 401, + PaymentRequired: 402, + Forbidden: 403, + NotFound: 404, + MethodNotAllowed: 405, + NotAcceptable: 406, + ProxyAuthenticationRequired: 407, + RequestTimeout: 408, + Conflict: 409, + Gone: 410, + LengthRequired: 411, + PreconditionFailed: 412, + PayloadTooLarge: 413, + UriTooLong: 414, + UnsupportedMediaType: 415, + RangeNotSatisfiable: 416, + ExpectationFailed: 417, + ImATeapot: 418, + MisdirectedRequest: 421, + UnprocessableEntity: 422, + Locked: 423, + FailedDependency: 424, + TooEarly: 425, + UpgradeRequired: 426, + PreconditionRequired: 428, + TooManyRequests: 429, + RequestHeaderFieldsTooLarge: 431, + UnavailableForLegalReasons: 451, + InternalServerError: 500, + NotImplemented: 501, + BadGateway: 502, + ServiceUnavailable: 503, + GatewayTimeout: 504, + HttpVersionNotSupported: 505, + VariantAlsoNegotiates: 506, + InsufficientStorage: 507, + LoopDetected: 508, + NotExtended: 510, + NetworkAuthenticationRequired: 511, }; -//# sourceMappingURL=core.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/pagination.mjs -// File generated from our OpenAPI spec by Stainless. +Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; +}); + +const HttpStatusCode$1 = HttpStatusCode; /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * + * @returns {Axios} A new instance of Axios */ -class Page extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.object = body.object; - this.data = body.data; - } - getPaginatedItems() { - return this.data; - } - // @deprecated Please use `nextPageInfo()` instead - /** - * This page represents a response that isn't actually paginated at the API level - * so there will never be any next page params. - */ - nextPageParams() { - return null; - } - nextPageInfo() { - return null; - } +function createInstance(defaultConfig) { + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); + + // Copy context to instance + utils.extend(instance, context, null, {allOwnKeys: true}); + + // Factory for creating new instances + instance.create = function create(instanceConfig) { + return createInstance(mergeConfig(defaultConfig, instanceConfig)); + }; + + return instance; } -class CursorPage extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data; - } - getPaginatedItems() { - return this.data; + +// Create the default instance to be exported +const axios = createInstance(defaults$1); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios$1; + +// Expose Cancel & CancelToken +axios.CanceledError = CanceledError; +axios.CancelToken = CancelToken$1; +axios.isCancel = isCancel; +axios.VERSION = VERSION; +axios.toFormData = toFormData; + +// Expose AxiosError class +axios.AxiosError = AxiosError; + +// alias for CanceledError for backward compatibility +axios.Cancel = axios.CanceledError; + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; + +axios.spread = spread; + +// Expose isAxiosError +axios.isAxiosError = isAxiosError; + +// Expose mergeConfig +axios.mergeConfig = mergeConfig; + +axios.AxiosHeaders = AxiosHeaders$1; + +axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); + +axios.getAdapter = adapters.getAdapter; + +axios.HttpStatusCode = HttpStatusCode$1; + +axios.default = axios; + +module.exports = axios; +//# sourceMappingURL=axios.cjs.map + + +/***/ }), + +/***/ 3791: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +var base64 = __nccwpck_require__(6463); + +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } + +var base64__default = /*#__PURE__*/_interopDefault(base64); + +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/core.ts +function bytePairMerge(piece, ranks) { + let parts = Array.from( + { length: piece.length }, + (_, i) => ({ start: i, end: i + 1 }) + ); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; + } + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } } - // @deprecated Please use `nextPageInfo()` instead - nextPageParams() { - const info = this.nextPageInfo(); - if (!info) return null; - if ('params' in info) return info.params; - const params = Object.fromEntries(info.url.searchParams); - if (!Object.keys(params).length) return null; - return params; + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function escapeRegex(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = base64__default.default.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); + } + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); } - nextPageInfo() { - var _a, _b; - if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.length)) { - return null; + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex( + Object.keys(this.specialTokens) + ); + const ret = []; + const allowedSpecialSet = new Set( + allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial + ); + const disallowedSpecialSet = new Set( + disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( + (x) => !allowedSpecialSet.has(x) + ) : disallowedSpecial + ); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error( + `The text contains a special token that is not allowed: ${specialMatch[0]}` + ); + } } - const next = (_b = this.data[this.data.length - 1]) === null || _b === void 0 ? void 0 : _b.id; - if (!next) return null; - return { params: { after: next } }; + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) + break; + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); + continue; + } + ret.push(...bytePairEncode(piece, this.rankMap)); + } + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; + } + return ret; } -} -//# sourceMappingURL=pagination.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resource.mjs -// File generated from our OpenAPI spec by Stainless. -class resource_APIResource { - constructor(client) { - this.client = client; - this.get = client.get.bind(client); - this.post = client.post.bind(client); - this.patch = client.patch.bind(client); - this.put = client.put.bind(client); - this.delete = client.delete.bind(client); - this.getAPIList = client.getAPIList.bind(client); + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); } -} -//# sourceMappingURL=resource.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs -// File generated from our OpenAPI spec by Stainless. - - -class Transcriptions extends resource_APIResource { - /** - * Transcribes audio into the input language. - */ - create(body, options) { - return this.post('/audio/transcriptions', multipartFormRequestOptions({ body, ...options })); +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g"); +}); +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; + } + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; + } + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; + } + case "ada": + case "babbage": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; + } + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "text-embedding-ada-002": { + return "cl100k_base"; + } + default: + throw new Error("Unknown model"); } } -(function (Transcriptions) {})(Transcriptions || (Transcriptions = {})); -//# sourceMappingURL=transcriptions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs -// File generated from our OpenAPI spec by Stainless. +exports.Tiktoken = Tiktoken; +exports.getEncodingNameForModel = getEncodingNameForModel; -class Translations extends resource_APIResource { - /** - * Translates audio into English. - */ - create(body, options) { - return this.post('/audio/translations', multipartFormRequestOptions({ body, ...options })); - } -} -(function (Translations) {})(Translations || (Translations = {})); -//# sourceMappingURL=translations.mjs.map +/***/ }), -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/index.mjs -// File generated from our OpenAPI spec by Stainless. +/***/ 9248: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = __nccwpck_require__(2657); +/***/ }), -//# sourceMappingURL=index.mjs.map +/***/ 6092: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs -// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.calculateMaxTokens = exports.getModelContextSize = exports.getEmbeddingContextSize = exports.getModelNameForTiktoken = void 0; +const tiktoken_js_1 = __nccwpck_require__(5400); +// https://www.npmjs.com/package/js-tiktoken +const getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-3.5-turbo-16k")) { + return "gpt-3.5-turbo-16k"; + } + if (modelName.startsWith("gpt-3.5-turbo-")) { + return "gpt-3.5-turbo"; + } + if (modelName.startsWith("gpt-4-32k")) { + return "gpt-4-32k"; + } + if (modelName.startsWith("gpt-4-")) { + return "gpt-4"; + } + return modelName; +}; +exports.getModelNameForTiktoken = getModelNameForTiktoken; +const getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": + return 8191; + default: + return 2046; + } +}; +exports.getEmbeddingContextSize = getEmbeddingContextSize; +const getModelContextSize = (modelName) => { + switch ((0, exports.getModelNameForTiktoken)(modelName)) { + case "gpt-3.5-turbo-16k": + return 16384; + case "gpt-3.5-turbo": + return 4096; + case "gpt-4-32k": + return 32768; + case "gpt-4": + return 8192; + case "text-davinci-003": + return 4097; + case "text-curie-001": + return 2048; + case "text-babbage-001": + return 2048; + case "text-ada-001": + return 2048; + case "code-davinci-002": + return 8000; + case "code-cushman-001": + return 2048; + default: + return 4097; + } +}; +exports.getModelContextSize = getModelContextSize; +const calculateMaxTokens = async ({ prompt, modelName, }) => { + let numTokens; + try { + numTokens = (await (0, tiktoken_js_1.encodingForModel)((0, exports.getModelNameForTiktoken)(modelName))).encode(prompt).length; + } + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + // fallback to approximate calculation if tiktoken is not available + // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# + numTokens = Math.ceil(prompt.length / 4); + } + const maxTokens = (0, exports.getModelContextSize)(modelName); + return maxTokens - numTokens; +}; +exports.calculateMaxTokens = calculateMaxTokens; +/***/ }), -class Audio extends resource_APIResource { - constructor() { - super(...arguments); - this.transcriptions = new Transcriptions(this.client); - this.translations = new Translations(this.client); - } -} -(function (Audio) { - Audio.Transcriptions = Transcriptions; - Audio.Translations = Translations; -})(Audio || (Audio = {})); -//# sourceMappingURL=audio.mjs.map +/***/ 6691: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions.mjs -// File generated from our OpenAPI spec by Stainless. -class Completions extends resource_APIResource { - create(body, options) { - var _a; - return this.post('/chat/completions', { - body, - ...options, - stream: (_a = body.stream) !== null && _a !== void 0 ? _a : false, - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getModelContextSize = exports.calculateMaxTokens = exports.BaseLanguageModel = exports.BaseLangChain = void 0; +const index_js_1 = __nccwpck_require__(1445); +const async_caller_js_1 = __nccwpck_require__(3382); +const count_tokens_js_1 = __nccwpck_require__(6092); +const tiktoken_js_1 = __nccwpck_require__(5400); +const index_js_2 = __nccwpck_require__(1259); +const base_js_1 = __nccwpck_require__(7249); +const chat_js_1 = __nccwpck_require__(9568); +const index_js_3 = __nccwpck_require__(55); +const getVerbosity = () => false; +/** + * Base class for language models, chains, tools. + */ +class BaseLangChain extends index_js_2.Runnable { + get lc_attributes() { + return { + callbacks: undefined, + verbose: undefined, + }; + } + constructor(params) { + super(params); + /** + * Whether to print out response text. + */ + Object.defineProperty(this, "verbose", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "callbacks", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + } } -(function (Completions) {})(Completions || (Completions = {})); -//# sourceMappingURL=completions.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs -// File generated from our OpenAPI spec by Stainless. - - -//# sourceMappingURL=index.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs -// File generated from our OpenAPI spec by Stainless. - - - -class Chat extends resource_APIResource { - constructor() { - super(...arguments); - this.completions = new Completions(this.client); - } +exports.BaseLangChain = BaseLangChain; +/** + * Base class for language models. + */ +class BaseLanguageModel extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; + } + constructor({ callbacks, callbackManager, ...params }) { + super({ + callbacks: callbacks ?? callbackManager, + ...params, + }); + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_encoding", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (typeof params.cache === "object") { + this.cache = params.cache; + } + else if (params.cache) { + this.cache = index_js_3.InMemoryCache.global(); + } + else { + this.cache = undefined; + } + this.caller = new async_caller_js_1.AsyncCaller(params ?? {}); + } + async getNumTokens(text) { + // fallback to approximate calculation if tiktoken is not available + let numTokens = Math.ceil(text.length / 4); + if (!this._encoding) { + try { + this._encoding = await (0, tiktoken_js_1.encodingForModel)("modelName" in this + ? (0, count_tokens_js_1.getModelNameForTiktoken)(this.modelName) + : "gpt2"); + } + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + } + } + if (this._encoding) { + numTokens = this._encoding.encode(text).length; + } + return numTokens; + } + static _convertInputToPromptValue(input) { + if (typeof input === "string") { + return new base_js_1.StringPromptValue(input); + } + else if (Array.isArray(input)) { + return new chat_js_1.ChatPromptValue(input.map(index_js_1.coerceMessageLikeToMessage)); + } + else { + return input; + } + } + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. + */ + _getSerializedCacheKeyParametersForCall(callOptions) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType(), + }; + const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); + const serializedEntries = filteredEntries + .map(([key, value]) => `${key}:${JSON.stringify(value)}`) + .sort() + .join(","); + return serializedEntries; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(data) { + const { _type, _model, ...rest } = data; + if (_model && _model !== "base_chat_model") { + throw new Error(`Cannot load LLM with model ${_model}`); + } + const Cls = { + openai: (await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(366), __nccwpck_require__.e(27)]).then(__nccwpck_require__.bind(__nccwpck_require__, 27))).ChatOpenAI, + }[_type]; + if (Cls === undefined) { + throw new Error(`Cannot load LLM with type ${_type}`); + } + return new Cls(rest); + } } -(function (Chat) { - Chat.Completions = Completions; -})(Chat || (Chat = {})); -//# sourceMappingURL=chat.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. +exports.BaseLanguageModel = BaseLanguageModel; +/* + * Export utility functions for token calculations: + * - calculateMaxTokens: Calculate max tokens for a given model and prompt (the model context size - tokens in prompt). + * - getModelContextSize: Get the context size for a specific model. + */ +var count_tokens_js_2 = __nccwpck_require__(6092); +Object.defineProperty(exports, "calculateMaxTokens", ({ enumerable: true, get: function () { return count_tokens_js_2.calculateMaxTokens; } })); +Object.defineProperty(exports, "getModelContextSize", ({ enumerable: true, get: function () { return count_tokens_js_2.getModelContextSize; } })); -class completions_Completions extends resource_APIResource { - create(body, options) { - var _a; - return this.post('/completions', { - body, - ...options, - stream: (_a = body.stream) !== null && _a !== void 0 ? _a : false, - }); - } -} -(function (Completions) {})(completions_Completions || (completions_Completions = {})); -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs -// File generated from our OpenAPI spec by Stainless. +/***/ }), -class Embeddings extends resource_APIResource { - /** - * Creates an embedding vector representing the input text. - */ - create(body, options) { - return this.post('/embeddings', { body, ...options }); - } -} -(function (Embeddings) {})(Embeddings || (Embeddings = {})); -//# sourceMappingURL=embeddings.mjs.map +/***/ 7295: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -;// CONCATENATED MODULE: ./node_modules/openai/resources/edits.mjs -// File generated from our OpenAPI spec by Stainless. -class Edits extends resource_APIResource { - /** - * Creates a new edit for the provided input, instruction, and parameters. - * - * @deprecated The Edits API is deprecated; please use Chat Completions instead. - * - * https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api - */ - create(body, options) { - return this.post('/edits', { body, ...options }); - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.serializeGeneration = exports.deserializeStoredGeneration = exports.getCacheKey = void 0; +const object_hash_1 = __importDefault(__nccwpck_require__(4856)); +const index_js_1 = __nccwpck_require__(1445); +/** + * This cache key should be consistent across all versions of langchain. + * It is currently NOT consistent across versions of langchain. + * + * A huge benefit of having a remote cache (like redis) is that you can + * access the cache from different processes/machines. The allows you to + * seperate concerns and scale horizontally. + * + * TODO: Make cache key consistent across versions of langchain. + */ +const getCacheKey = (...strings) => (0, object_hash_1.default)(strings.join("_")); +exports.getCacheKey = getCacheKey; +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== undefined) { + return { + text: storedGeneration.text, + message: (0, index_js_1.mapStoredMessageToChatMessage)(storedGeneration.message), + }; + } + else { + return { text: storedGeneration.text }; + } } -(function (Edits) {})(Edits || (Edits = {})); -//# sourceMappingURL=edits.mjs.map +exports.deserializeStoredGeneration = deserializeStoredGeneration; +function serializeGeneration(generation) { + const serializedValue = { + text: generation.text, + }; + if (generation.message !== undefined) { + serializedValue.message = generation.message.toDict(); + } + return serializedValue; +} +exports.serializeGeneration = serializeGeneration; -;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs -// File generated from our OpenAPI spec by Stainless. +/***/ }), +/***/ 55: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -class Files extends resource_APIResource { - /** - * Upload a file that contains document(s) to be used across various - * endpoints/features. Currently, the size of all the files uploaded by one - * organization can be up to 1 GB. Please contact us if you need to increase the - * storage limit. - */ - create(body, options) { - return this.post('/files', multipartFormRequestOptions({ body, ...options })); - } - /** - * Returns information about a specific file. - */ - retrieve(fileId, options) { - return this.get(`/files/${fileId}`, options); - } - /** - * Returns a list of files that belong to the user's organization. - */ - list(options) { - return this.getAPIList('/files', FileObjectsPage, options); - } - /** - * Delete a file. - */ - del(fileId, options) { - return this.delete(`/files/${fileId}`, options); - } - /** - * Returns the contents of the specified file - */ - retrieveContent(fileId, options) { - return this.get(`/files/${fileId}/content`, { - ...options, - headers: { - Accept: 'application/json', - ...(options === null || options === void 0 ? void 0 : options.headers), - }, - }); - } -} + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.InMemoryCache = void 0; +const base_js_1 = __nccwpck_require__(7295); +const index_js_1 = __nccwpck_require__(1445); +const GLOBAL_MAP = new Map(); /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * A cache for storing LLM generations that stores data in memory. */ -class FileObjectsPage extends Page {} -(function (Files) {})(Files || (Files = {})); -//# sourceMappingURL=files.mjs.map +class InMemoryCache extends index_js_1.BaseCache { + constructor(map) { + super(); + Object.defineProperty(this, "cache", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.cache = map ?? new Map(); + } + /** + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. + */ + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get((0, base_js_1.getCacheKey)(prompt, llmKey)) ?? null); + } + /** + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. + */ + async update(prompt, llmKey, value) { + this.cache.set((0, base_js_1.getCacheKey)(prompt, llmKey), value); + } + /** + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. + */ + static global() { + return new InMemoryCache(GLOBAL_MAP); + } +} +exports.InMemoryCache = InMemoryCache; -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tunes.mjs -// File generated from our OpenAPI spec by Stainless. +/***/ }), -class FineTunes extends resource_APIResource { - /** - * Creates a job that fine-tunes a specified model from a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](/docs/guides/legacy-fine-tuning) - */ - create(body, options) { - return this.post('/fine-tunes', { body, ...options }); - } - /** - * Gets info about the fine-tune job. - * - * [Learn more about fine-tuning](/docs/guides/legacy-fine-tuning) - */ - retrieve(fineTuneId, options) { - return this.get(`/fine-tunes/${fineTuneId}`, options); - } - /** - * List your organization's fine-tuning jobs - */ - list(options) { - return this.getAPIList('/fine-tunes', FineTunesPage, options); - } - /** - * Immediately cancel a fine-tune job. - */ - cancel(fineTuneId, options) { - return this.post(`/fine-tunes/${fineTuneId}/cancel`, options); - } - listEvents(fineTuneId, query, options) { - var _a; - return this.get(`/fine-tunes/${fineTuneId}/events`, { - query, - timeout: 86400000, - ...options, - stream: - (_a = query === null || query === void 0 ? void 0 : query.stream) !== null && _a !== void 0 ? - _a - : false, - }); - } +/***/ 7656: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseCallbackHandler = void 0; +const uuid = __importStar(__nccwpck_require__(8655)); +const serializable_js_1 = __nccwpck_require__(5335); +/** + * Abstract class that provides a set of optional methods that can be + * overridden in derived classes to handle various events during the + * execution of a LangChain application. + */ +class BaseCallbackHandlerMethodsClass { } /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * Abstract base class for creating callback handlers in the LangChain + * framework. It provides a set of optional methods that can be overridden + * in derived classes to handle various events during the execution of a + * LangChain application. */ -class FineTunesPage extends Page {} -(function (FineTunes) {})(FineTunes || (FineTunes = {})); -//# sourceMappingURL=fine-tunes.mjs.map +class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { + get lc_namespace() { + return ["langchain", "callbacks", this.name]; + } + get lc_secrets() { + return undefined; + } + get lc_attributes() { + return undefined; + } + get lc_aliases() { + return undefined; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + (0, serializable_js_1.get_lc_unique_name)(this.constructor), + ]; + } + constructor(input) { + super(); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "ignoreLLM", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreChain", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreAgent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreRetriever", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "awaitHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.LANGCHAIN_CALLBACKS_BACKGROUND !== "true" + : true + }); + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return serializable_js_1.Serializable.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return serializable_js_1.Serializable.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: uuid.v4() + }); + Object.assign(this, methods); + } + } + return new Handler(); + } +} +exports.BaseCallbackHandler = BaseCallbackHandler; -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs.mjs -// File generated from our OpenAPI spec by Stainless. +/***/ }), +/***/ 2533: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -class Jobs extends resource_APIResource { - /** - * Creates a job that fine-tunes a specified model from a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](/docs/guides/fine-tuning) - */ - create(body, options) { - return this.post('/fine_tuning/jobs', { body, ...options }); - } - /** - * Get info about a fine-tuning job. - * - * [Learn more about fine-tuning](/docs/guides/fine-tuning) - */ - retrieve(fineTuningJobId, options) { - return this.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); - } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConsoleCallbackHandler = void 0; +const ansi_styles_1 = __importDefault(__nccwpck_require__(8964)); +const tracer_js_1 = __nccwpck_require__(4107); +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); } - return this.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); - } - /** - * Immediately cancel a fine-tune job. - */ - cancel(fineTuningJobId, options) { - return this.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); - } - listEvents(fineTuningJobId, query = {}, options) { - if (isRequestOptions(query)) { - return this.listEvents(fineTuningJobId, {}, query); + catch (err) { + return fallback; + } +} +function elapsed(run) { + if (!run.end_time) + return ""; + const elapsed = run.end_time - run.start_time; + if (elapsed < 1000) { + return `${elapsed}ms`; + } + return `${(elapsed / 1000).toFixed(2)}s`; +} +const { color } = ansi_styles_1.default; +/** + * A tracer that logs all events to the console. It extends from the + * `BaseTracer` class and overrides its methods to provide custom logging + * functionality. + */ +class ConsoleCallbackHandler extends tracer_js_1.BaseTracer { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "console_callback_handler" + }); + } + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + // utility methods + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; + } + else { + break; + } + } + return parents; + } + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string = [...parents, run] + .map((parent, i, arr) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr.length - 1 ? wrap(ansi_styles_1.default.bold, name) : name; + }) + .join(" > "); + return wrap(color.grey, string); + } + // logging methods + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs + ? { prompts: run.inputs.prompts.map((p) => p.trim()) } + : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); + } + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${run.inputs.input?.trim()}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${run.outputs?.output?.trim()}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); } - return this.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { - query, - ...options, - }); - } -} -class FineTuningJobsPage extends CursorPage {} -class FineTuningJobEventsPage extends CursorPage {} -(function (Jobs) {})(Jobs || (Jobs = {})); -//# sourceMappingURL=jobs.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/index.mjs -// File generated from our OpenAPI spec by Stainless. - - -//# sourceMappingURL=index.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs -// File generated from our OpenAPI spec by Stainless. - - - -class FineTuning extends resource_APIResource { - constructor() { - super(...arguments); - this.jobs = new Jobs(this.client); - } } -(function (FineTuning) { - FineTuning.Jobs = Jobs; - FineTuning.FineTuningJobsPage = FineTuningJobsPage; - FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage; -})(FineTuning || (FineTuning = {})); -//# sourceMappingURL=fine-tuning.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs -// File generated from our OpenAPI spec by Stainless. +exports.ConsoleCallbackHandler = ConsoleCallbackHandler; -class Images extends resource_APIResource { - /** - * Creates a variation of a given image. - */ - createVariation(body, options) { - return this.post('/images/variations', multipartFormRequestOptions({ body, ...options })); - } - /** - * Creates an edited or extended image given an original image and a prompt. - */ - edit(body, options) { - return this.post('/images/edits', multipartFormRequestOptions({ body, ...options })); - } - /** - * Creates an image given a prompt. - */ - generate(body, options) { - return this.post('/images/generations', { body, ...options }); - } -} -(function (Images) {})(Images || (Images = {})); -//# sourceMappingURL=images.mjs.map +/***/ }), -;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. +/***/ 5814: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -class Models extends resource_APIResource { - /** - * Retrieves a model instance, providing basic information about the model such as - * the owner and permissioning. - */ - retrieve(model, options) { - return this.get(`/models/${model}`, options); - } - /** - * Lists the currently available models, and provides basic information about each - * one such as the owner and availability. - */ - list(options) { - return this.getAPIList('/models', ModelsPage, options); - } - /** - * Delete a fine-tuned model. You must have the Owner role in your organization. - */ - del(model, options) { - return this.delete(`/models/${model}`, options); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getTracingV2CallbackHandler = exports.getTracingCallbackHandler = void 0; +const tracer_langchain_js_1 = __nccwpck_require__(521); +const tracer_langchain_v1_js_1 = __nccwpck_require__(9159); +/** + * Function that returns an instance of `LangChainTracerV1`. If a session + * is provided, it loads that session into the tracer; otherwise, it loads + * a default session. + * @param session Optional session to load into the tracer. + * @returns An instance of `LangChainTracerV1`. + */ +async function getTracingCallbackHandler(session) { + const tracer = new tracer_langchain_v1_js_1.LangChainTracerV1(); + if (session) { + await tracer.loadSession(session); + } + else { + await tracer.loadDefaultSession(); + } + return tracer; } +exports.getTracingCallbackHandler = getTracingCallbackHandler; /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * Function that returns an instance of `LangChainTracer`. It does not + * load any session data. + * @returns An instance of `LangChainTracer`. */ -class ModelsPage extends Page {} -(function (Models) {})(Models || (Models = {})); -//# sourceMappingURL=models.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs -// File generated from our OpenAPI spec by Stainless. - -class Moderations extends resource_APIResource { - /** - * Classifies if text violates OpenAI's Content Policy - */ - create(body, options) { - return this.post('/moderations', { body, ...options }); - } +async function getTracingV2CallbackHandler() { + return new tracer_langchain_js_1.LangChainTracer(); } -(function (Moderations) {})(Moderations || (Moderations = {})); -//# sourceMappingURL=moderations.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs -// File generated from our OpenAPI spec by Stainless. - - - - - - - - - - - -//# sourceMappingURL=index.mjs.map - -;// CONCATENATED MODULE: ./node_modules/openai/index.mjs -// File generated from our OpenAPI spec by Stainless. -var _a; +exports.getTracingV2CallbackHandler = getTracingV2CallbackHandler; +/***/ }), +/***/ 5877: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** API Client for interfacing with the OpenAI API. */ -class OpenAI extends APIClient { - /** - * API Client for interfacing with the OpenAI API. - * - * @param {string} [opts.apiKey=process.env['OPENAI_API_KEY']] - The API Key to send to the API. - * @param {string} [opts.baseURL] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - * @param {string | null} [opts.organization] - */ - constructor(_b) { - var _c, _d; - var { - apiKey = readEnv('OPENAI_API_KEY'), - organization = (_c = readEnv('OPENAI_ORG_ID')) !== null && _c !== void 0 ? _c : null, - ...opts - } = _b === void 0 ? {} : _b; - if (apiKey === undefined) { - throw new Error( - "The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'my apiKey' }).", - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LogStreamCallbackHandler = exports.RunLog = exports.RunLogPatch = void 0; +const index_js_1 = __nccwpck_require__(3529); +const tracer_js_1 = __nccwpck_require__(4107); +const stream_js_1 = __nccwpck_require__(4428); +/** + * List of jsonpatch JSONPatchOperations, which describe how to create the run state + * from an empty dict. This is the minimal representation of the log, designed to + * be serialized as JSON and sent over the wire to reconstruct the log on the other + * side. Reconstruction of the state can be done with any jsonpatch-compliant library, + * see https://jsonpatch.com for more information. + */ +class RunLogPatch { + constructor(fields) { + Object.defineProperty(this, "ops", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.ops = fields.ops; } - const options = { - apiKey, - organization, - baseURL: `https://api.openai.com/v1`, - ...opts, - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { - throw new Error( - "It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n", - ); + concat(other) { + const ops = this.ops.concat(other.ops); + const states = (0, index_js_1.applyPatch)({}, ops); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunLog({ + ops, + state: states[states.length - 1].newDocument, + }); } - super({ - baseURL: options.baseURL, - timeout: (_d = options.timeout) !== null && _d !== void 0 ? _d : 600000 /* 10 minutes */, - httpAgent: options.httpAgent, - maxRetries: options.maxRetries, - fetch: options.fetch, - }); - this.completions = new completions_Completions(this); - this.chat = new Chat(this); - this.edits = new Edits(this); - this.embeddings = new Embeddings(this); - this.files = new Files(this); - this.images = new Images(this); - this.audio = new Audio(this); - this.moderations = new Moderations(this); - this.models = new Models(this); - this.fineTuning = new FineTuning(this); - this.fineTunes = new FineTunes(this); - this._options = options; - this.apiKey = apiKey; - this.organization = organization; - } - defaultQuery() { - return this._options.defaultQuery; - } - defaultHeaders(opts) { - return { - ...super.defaultHeaders(opts), - 'OpenAI-Organization': this.organization, - ...this._options.defaultHeaders, - }; - } - authHeaders(opts) { - return { Authorization: `Bearer ${this.apiKey}` }; - } } -_a = OpenAI; -OpenAI.OpenAI = _a; -OpenAI.APIError = APIError; -OpenAI.APIConnectionError = APIConnectionError; -OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError; -OpenAI.APIUserAbortError = APIUserAbortError; -OpenAI.NotFoundError = NotFoundError; -OpenAI.ConflictError = ConflictError; -OpenAI.RateLimitError = RateLimitError; -OpenAI.BadRequestError = BadRequestError; -OpenAI.AuthenticationError = AuthenticationError; -OpenAI.InternalServerError = InternalServerError; -OpenAI.PermissionDeniedError = PermissionDeniedError; -OpenAI.UnprocessableEntityError = UnprocessableEntityError; -const { - APIError: openai_APIError, - APIConnectionError: openai_APIConnectionError, - APIConnectionTimeoutError: openai_APIConnectionTimeoutError, - APIUserAbortError: openai_APIUserAbortError, - NotFoundError: openai_NotFoundError, - ConflictError: openai_ConflictError, - RateLimitError: openai_RateLimitError, - BadRequestError: openai_BadRequestError, - AuthenticationError: openai_AuthenticationError, - InternalServerError: openai_InternalServerError, - PermissionDeniedError: openai_PermissionDeniedError, - UnprocessableEntityError: openai_UnprocessableEntityError, -} = error_namespaceObject; -var openai_toFile = toFile; -var openai_fileFromPath = fileFromPath_node_fileFromPath; -(function (OpenAI) { - // Helper functions - OpenAI.toFile = toFile; - OpenAI.fileFromPath = fileFromPath_node_fileFromPath; - OpenAI.Page = Page; - OpenAI.CursorPage = CursorPage; - OpenAI.Completions = completions_Completions; - OpenAI.Chat = Chat; - OpenAI.Edits = Edits; - OpenAI.Embeddings = Embeddings; - OpenAI.Files = Files; - OpenAI.FileObjectsPage = FileObjectsPage; - OpenAI.Images = Images; - OpenAI.Audio = Audio; - OpenAI.Moderations = Moderations; - OpenAI.Models = Models; - OpenAI.ModelsPage = ModelsPage; - OpenAI.FineTuning = FineTuning; - OpenAI.FineTunes = FineTunes; - OpenAI.FineTunesPage = FineTunesPage; -})(OpenAI || (OpenAI = {})); -/* harmony default export */ const openai = ((/* unused pure expression or super */ null && (OpenAI))); -//# sourceMappingURL=index.mjs.map - - -/***/ }), - -/***/ 9968: -/***/ ((module) => { - -module.exports = JSON.parse('{"name":"dotenv","version":"16.3.1","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","lint-readme":"standard-markdown","pretest":"npm run lint && npm run dts-check","test":"tap tests/*.js --100 -Rspec","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"funding":"https://github.com/motdotla/dotenv?sponsor=1","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@definitelytyped/dtslint":"^0.0.133","@types/node":"^18.11.3","decache":"^4.6.1","sinon":"^14.0.1","standard":"^17.0.0","standard-markdown":"^7.1.0","standard-version":"^9.5.0","tap":"^16.3.0","tar":"^6.1.11","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}'); - -/***/ }), - -/***/ 3765: -/***/ ((module) => { - -module.exports = JSON.parse('{"application/1d-interleaved-parityfec":{"source":"iana"},"application/3gpdash-qoe-report+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/3gpp-ims+xml":{"source":"iana","compressible":true},"application/3gpphal+json":{"source":"iana","compressible":true},"application/3gpphalforms+json":{"source":"iana","compressible":true},"application/a2l":{"source":"iana"},"application/ace+cbor":{"source":"iana"},"application/activemessage":{"source":"iana"},"application/activity+json":{"source":"iana","compressible":true},"application/alto-costmap+json":{"source":"iana","compressible":true},"application/alto-costmapfilter+json":{"source":"iana","compressible":true},"application/alto-directory+json":{"source":"iana","compressible":true},"application/alto-endpointcost+json":{"source":"iana","compressible":true},"application/alto-endpointcostparams+json":{"source":"iana","compressible":true},"application/alto-endpointprop+json":{"source":"iana","compressible":true},"application/alto-endpointpropparams+json":{"source":"iana","compressible":true},"application/alto-error+json":{"source":"iana","compressible":true},"application/alto-networkmap+json":{"source":"iana","compressible":true},"application/alto-networkmapfilter+json":{"source":"iana","compressible":true},"application/alto-updatestreamcontrol+json":{"source":"iana","compressible":true},"application/alto-updatestreamparams+json":{"source":"iana","compressible":true},"application/aml":{"source":"iana"},"application/andrew-inset":{"source":"iana","extensions":["ez"]},"application/applefile":{"source":"iana"},"application/applixware":{"source":"apache","extensions":["aw"]},"application/at+jwt":{"source":"iana"},"application/atf":{"source":"iana"},"application/atfx":{"source":"iana"},"application/atom+xml":{"source":"iana","compressible":true,"extensions":["atom"]},"application/atomcat+xml":{"source":"iana","compressible":true,"extensions":["atomcat"]},"application/atomdeleted+xml":{"source":"iana","compressible":true,"extensions":["atomdeleted"]},"application/atomicmail":{"source":"iana"},"application/atomsvc+xml":{"source":"iana","compressible":true,"extensions":["atomsvc"]},"application/atsc-dwd+xml":{"source":"iana","compressible":true,"extensions":["dwd"]},"application/atsc-dynamic-event-message":{"source":"iana"},"application/atsc-held+xml":{"source":"iana","compressible":true,"extensions":["held"]},"application/atsc-rdt+json":{"source":"iana","compressible":true},"application/atsc-rsat+xml":{"source":"iana","compressible":true,"extensions":["rsat"]},"application/atxml":{"source":"iana"},"application/auth-policy+xml":{"source":"iana","compressible":true},"application/bacnet-xdd+zip":{"source":"iana","compressible":false},"application/batch-smtp":{"source":"iana"},"application/bdoc":{"compressible":false,"extensions":["bdoc"]},"application/beep+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/calendar+json":{"source":"iana","compressible":true},"application/calendar+xml":{"source":"iana","compressible":true,"extensions":["xcs"]},"application/call-completion":{"source":"iana"},"application/cals-1840":{"source":"iana"},"application/captive+json":{"source":"iana","compressible":true},"application/cbor":{"source":"iana"},"application/cbor-seq":{"source":"iana"},"application/cccex":{"source":"iana"},"application/ccmp+xml":{"source":"iana","compressible":true},"application/ccxml+xml":{"source":"iana","compressible":true,"extensions":["ccxml"]},"application/cdfx+xml":{"source":"iana","compressible":true,"extensions":["cdfx"]},"application/cdmi-capability":{"source":"iana","extensions":["cdmia"]},"application/cdmi-container":{"source":"iana","extensions":["cdmic"]},"application/cdmi-domain":{"source":"iana","extensions":["cdmid"]},"application/cdmi-object":{"source":"iana","extensions":["cdmio"]},"application/cdmi-queue":{"source":"iana","extensions":["cdmiq"]},"application/cdni":{"source":"iana"},"application/cea":{"source":"iana"},"application/cea-2018+xml":{"source":"iana","compressible":true},"application/cellml+xml":{"source":"iana","compressible":true},"application/cfw":{"source":"iana"},"application/city+json":{"source":"iana","compressible":true},"application/clr":{"source":"iana"},"application/clue+xml":{"source":"iana","compressible":true},"application/clue_info+xml":{"source":"iana","compressible":true},"application/cms":{"source":"iana"},"application/cnrp+xml":{"source":"iana","compressible":true},"application/coap-group+json":{"source":"iana","compressible":true},"application/coap-payload":{"source":"iana"},"application/commonground":{"source":"iana"},"application/conference-info+xml":{"source":"iana","compressible":true},"application/cose":{"source":"iana"},"application/cose-key":{"source":"iana"},"application/cose-key-set":{"source":"iana"},"application/cpl+xml":{"source":"iana","compressible":true,"extensions":["cpl"]},"application/csrattrs":{"source":"iana"},"application/csta+xml":{"source":"iana","compressible":true},"application/cstadata+xml":{"source":"iana","compressible":true},"application/csvm+json":{"source":"iana","compressible":true},"application/cu-seeme":{"source":"apache","extensions":["cu"]},"application/cwt":{"source":"iana"},"application/cybercash":{"source":"iana"},"application/dart":{"compressible":true},"application/dash+xml":{"source":"iana","compressible":true,"extensions":["mpd"]},"application/dash-patch+xml":{"source":"iana","compressible":true,"extensions":["mpp"]},"application/dashdelta":{"source":"iana"},"application/davmount+xml":{"source":"iana","compressible":true,"extensions":["davmount"]},"application/dca-rft":{"source":"iana"},"application/dcd":{"source":"iana"},"application/dec-dx":{"source":"iana"},"application/dialog-info+xml":{"source":"iana","compressible":true},"application/dicom":{"source":"iana"},"application/dicom+json":{"source":"iana","compressible":true},"application/dicom+xml":{"source":"iana","compressible":true},"application/dii":{"source":"iana"},"application/dit":{"source":"iana"},"application/dns":{"source":"iana"},"application/dns+json":{"source":"iana","compressible":true},"application/dns-message":{"source":"iana"},"application/docbook+xml":{"source":"apache","compressible":true,"extensions":["dbk"]},"application/dots+cbor":{"source":"iana"},"application/dskpp+xml":{"source":"iana","compressible":true},"application/dssc+der":{"source":"iana","extensions":["dssc"]},"application/dssc+xml":{"source":"iana","compressible":true,"extensions":["xdssc"]},"application/dvcs":{"source":"iana"},"application/ecmascript":{"source":"iana","compressible":true,"extensions":["es","ecma"]},"application/edi-consent":{"source":"iana"},"application/edi-x12":{"source":"iana","compressible":false},"application/edifact":{"source":"iana","compressible":false},"application/efi":{"source":"iana"},"application/elm+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/elm+xml":{"source":"iana","compressible":true},"application/emergencycalldata.cap+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/emergencycalldata.comment+xml":{"source":"iana","compressible":true},"application/emergencycalldata.control+xml":{"source":"iana","compressible":true},"application/emergencycalldata.deviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.ecall.msd":{"source":"iana"},"application/emergencycalldata.providerinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.serviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.subscriberinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.veds+xml":{"source":"iana","compressible":true},"application/emma+xml":{"source":"iana","compressible":true,"extensions":["emma"]},"application/emotionml+xml":{"source":"iana","compressible":true,"extensions":["emotionml"]},"application/encaprtp":{"source":"iana"},"application/epp+xml":{"source":"iana","compressible":true},"application/epub+zip":{"source":"iana","compressible":false,"extensions":["epub"]},"application/eshop":{"source":"iana"},"application/exi":{"source":"iana","extensions":["exi"]},"application/expect-ct-report+json":{"source":"iana","compressible":true},"application/express":{"source":"iana","extensions":["exp"]},"application/fastinfoset":{"source":"iana"},"application/fastsoap":{"source":"iana"},"application/fdt+xml":{"source":"iana","compressible":true,"extensions":["fdt"]},"application/fhir+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/fhir+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/fido.trusted-apps+json":{"compressible":true},"application/fits":{"source":"iana"},"application/flexfec":{"source":"iana"},"application/font-sfnt":{"source":"iana"},"application/font-tdpfr":{"source":"iana","extensions":["pfr"]},"application/font-woff":{"source":"iana","compressible":false},"application/framework-attributes+xml":{"source":"iana","compressible":true},"application/geo+json":{"source":"iana","compressible":true,"extensions":["geojson"]},"application/geo+json-seq":{"source":"iana"},"application/geopackage+sqlite3":{"source":"iana"},"application/geoxacml+xml":{"source":"iana","compressible":true},"application/gltf-buffer":{"source":"iana"},"application/gml+xml":{"source":"iana","compressible":true,"extensions":["gml"]},"application/gpx+xml":{"source":"apache","compressible":true,"extensions":["gpx"]},"application/gxf":{"source":"apache","extensions":["gxf"]},"application/gzip":{"source":"iana","compressible":false,"extensions":["gz"]},"application/h224":{"source":"iana"},"application/held+xml":{"source":"iana","compressible":true},"application/hjson":{"extensions":["hjson"]},"application/http":{"source":"iana"},"application/hyperstudio":{"source":"iana","extensions":["stk"]},"application/ibe-key-request+xml":{"source":"iana","compressible":true},"application/ibe-pkg-reply+xml":{"source":"iana","compressible":true},"application/ibe-pp-data":{"source":"iana"},"application/iges":{"source":"iana"},"application/im-iscomposing+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/index":{"source":"iana"},"application/index.cmd":{"source":"iana"},"application/index.obj":{"source":"iana"},"application/index.response":{"source":"iana"},"application/index.vnd":{"source":"iana"},"application/inkml+xml":{"source":"iana","compressible":true,"extensions":["ink","inkml"]},"application/iotp":{"source":"iana"},"application/ipfix":{"source":"iana","extensions":["ipfix"]},"application/ipp":{"source":"iana"},"application/isup":{"source":"iana"},"application/its+xml":{"source":"iana","compressible":true,"extensions":["its"]},"application/java-archive":{"source":"apache","compressible":false,"extensions":["jar","war","ear"]},"application/java-serialized-object":{"source":"apache","compressible":false,"extensions":["ser"]},"application/java-vm":{"source":"apache","compressible":false,"extensions":["class"]},"application/javascript":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["js","mjs"]},"application/jf2feed+json":{"source":"iana","compressible":true},"application/jose":{"source":"iana"},"application/jose+json":{"source":"iana","compressible":true},"application/jrd+json":{"source":"iana","compressible":true},"application/jscalendar+json":{"source":"iana","compressible":true},"application/json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["json","map"]},"application/json-patch+json":{"source":"iana","compressible":true},"application/json-seq":{"source":"iana"},"application/json5":{"extensions":["json5"]},"application/jsonml+json":{"source":"apache","compressible":true,"extensions":["jsonml"]},"application/jwk+json":{"source":"iana","compressible":true},"application/jwk-set+json":{"source":"iana","compressible":true},"application/jwt":{"source":"iana"},"application/kpml-request+xml":{"source":"iana","compressible":true},"application/kpml-response+xml":{"source":"iana","compressible":true},"application/ld+json":{"source":"iana","compressible":true,"extensions":["jsonld"]},"application/lgr+xml":{"source":"iana","compressible":true,"extensions":["lgr"]},"application/link-format":{"source":"iana"},"application/load-control+xml":{"source":"iana","compressible":true},"application/lost+xml":{"source":"iana","compressible":true,"extensions":["lostxml"]},"application/lostsync+xml":{"source":"iana","compressible":true},"application/lpf+zip":{"source":"iana","compressible":false},"application/lxf":{"source":"iana"},"application/mac-binhex40":{"source":"iana","extensions":["hqx"]},"application/mac-compactpro":{"source":"apache","extensions":["cpt"]},"application/macwriteii":{"source":"iana"},"application/mads+xml":{"source":"iana","compressible":true,"extensions":["mads"]},"application/manifest+json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["webmanifest"]},"application/marc":{"source":"iana","extensions":["mrc"]},"application/marcxml+xml":{"source":"iana","compressible":true,"extensions":["mrcx"]},"application/mathematica":{"source":"iana","extensions":["ma","nb","mb"]},"application/mathml+xml":{"source":"iana","compressible":true,"extensions":["mathml"]},"application/mathml-content+xml":{"source":"iana","compressible":true},"application/mathml-presentation+xml":{"source":"iana","compressible":true},"application/mbms-associated-procedure-description+xml":{"source":"iana","compressible":true},"application/mbms-deregister+xml":{"source":"iana","compressible":true},"application/mbms-envelope+xml":{"source":"iana","compressible":true},"application/mbms-msk+xml":{"source":"iana","compressible":true},"application/mbms-msk-response+xml":{"source":"iana","compressible":true},"application/mbms-protection-description+xml":{"source":"iana","compressible":true},"application/mbms-reception-report+xml":{"source":"iana","compressible":true},"application/mbms-register+xml":{"source":"iana","compressible":true},"application/mbms-register-response+xml":{"source":"iana","compressible":true},"application/mbms-schedule+xml":{"source":"iana","compressible":true},"application/mbms-user-service-description+xml":{"source":"iana","compressible":true},"application/mbox":{"source":"iana","extensions":["mbox"]},"application/media-policy-dataset+xml":{"source":"iana","compressible":true,"extensions":["mpf"]},"application/media_control+xml":{"source":"iana","compressible":true},"application/mediaservercontrol+xml":{"source":"iana","compressible":true,"extensions":["mscml"]},"application/merge-patch+json":{"source":"iana","compressible":true},"application/metalink+xml":{"source":"apache","compressible":true,"extensions":["metalink"]},"application/metalink4+xml":{"source":"iana","compressible":true,"extensions":["meta4"]},"application/mets+xml":{"source":"iana","compressible":true,"extensions":["mets"]},"application/mf4":{"source":"iana"},"application/mikey":{"source":"iana"},"application/mipc":{"source":"iana"},"application/missing-blocks+cbor-seq":{"source":"iana"},"application/mmt-aei+xml":{"source":"iana","compressible":true,"extensions":["maei"]},"application/mmt-usd+xml":{"source":"iana","compressible":true,"extensions":["musd"]},"application/mods+xml":{"source":"iana","compressible":true,"extensions":["mods"]},"application/moss-keys":{"source":"iana"},"application/moss-signature":{"source":"iana"},"application/mosskey-data":{"source":"iana"},"application/mosskey-request":{"source":"iana"},"application/mp21":{"source":"iana","extensions":["m21","mp21"]},"application/mp4":{"source":"iana","extensions":["mp4s","m4p"]},"application/mpeg4-generic":{"source":"iana"},"application/mpeg4-iod":{"source":"iana"},"application/mpeg4-iod-xmt":{"source":"iana"},"application/mrb-consumer+xml":{"source":"iana","compressible":true},"application/mrb-publish+xml":{"source":"iana","compressible":true},"application/msc-ivr+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msc-mixer+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msword":{"source":"iana","compressible":false,"extensions":["doc","dot"]},"application/mud+json":{"source":"iana","compressible":true},"application/multipart-core":{"source":"iana"},"application/mxf":{"source":"iana","extensions":["mxf"]},"application/n-quads":{"source":"iana","extensions":["nq"]},"application/n-triples":{"source":"iana","extensions":["nt"]},"application/nasdata":{"source":"iana"},"application/news-checkgroups":{"source":"iana","charset":"US-ASCII"},"application/news-groupinfo":{"source":"iana","charset":"US-ASCII"},"application/news-transmission":{"source":"iana"},"application/nlsml+xml":{"source":"iana","compressible":true},"application/node":{"source":"iana","extensions":["cjs"]},"application/nss":{"source":"iana"},"application/oauth-authz-req+jwt":{"source":"iana"},"application/oblivious-dns-message":{"source":"iana"},"application/ocsp-request":{"source":"iana"},"application/ocsp-response":{"source":"iana"},"application/octet-stream":{"source":"iana","compressible":false,"extensions":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{"source":"iana","extensions":["oda"]},"application/odm+xml":{"source":"iana","compressible":true},"application/odx":{"source":"iana"},"application/oebps-package+xml":{"source":"iana","compressible":true,"extensions":["opf"]},"application/ogg":{"source":"iana","compressible":false,"extensions":["ogx"]},"application/omdoc+xml":{"source":"apache","compressible":true,"extensions":["omdoc"]},"application/onenote":{"source":"apache","extensions":["onetoc","onetoc2","onetmp","onepkg"]},"application/opc-nodeset+xml":{"source":"iana","compressible":true},"application/oscore":{"source":"iana"},"application/oxps":{"source":"iana","extensions":["oxps"]},"application/p21":{"source":"iana"},"application/p21+zip":{"source":"iana","compressible":false},"application/p2p-overlay+xml":{"source":"iana","compressible":true,"extensions":["relo"]},"application/parityfec":{"source":"iana"},"application/passport":{"source":"iana"},"application/patch-ops-error+xml":{"source":"iana","compressible":true,"extensions":["xer"]},"application/pdf":{"source":"iana","compressible":false,"extensions":["pdf"]},"application/pdx":{"source":"iana"},"application/pem-certificate-chain":{"source":"iana"},"application/pgp-encrypted":{"source":"iana","compressible":false,"extensions":["pgp"]},"application/pgp-keys":{"source":"iana","extensions":["asc"]},"application/pgp-signature":{"source":"iana","extensions":["asc","sig"]},"application/pics-rules":{"source":"apache","extensions":["prf"]},"application/pidf+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pidf-diff+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pkcs10":{"source":"iana","extensions":["p10"]},"application/pkcs12":{"source":"iana"},"application/pkcs7-mime":{"source":"iana","extensions":["p7m","p7c"]},"application/pkcs7-signature":{"source":"iana","extensions":["p7s"]},"application/pkcs8":{"source":"iana","extensions":["p8"]},"application/pkcs8-encrypted":{"source":"iana"},"application/pkix-attr-cert":{"source":"iana","extensions":["ac"]},"application/pkix-cert":{"source":"iana","extensions":["cer"]},"application/pkix-crl":{"source":"iana","extensions":["crl"]},"application/pkix-pkipath":{"source":"iana","extensions":["pkipath"]},"application/pkixcmp":{"source":"iana","extensions":["pki"]},"application/pls+xml":{"source":"iana","compressible":true,"extensions":["pls"]},"application/poc-settings+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/postscript":{"source":"iana","compressible":true,"extensions":["ai","eps","ps"]},"application/ppsp-tracker+json":{"source":"iana","compressible":true},"application/problem+json":{"source":"iana","compressible":true},"application/problem+xml":{"source":"iana","compressible":true},"application/provenance+xml":{"source":"iana","compressible":true,"extensions":["provx"]},"application/prs.alvestrand.titrax-sheet":{"source":"iana"},"application/prs.cww":{"source":"iana","extensions":["cww"]},"application/prs.cyn":{"source":"iana","charset":"7-BIT"},"application/prs.hpub+zip":{"source":"iana","compressible":false},"application/prs.nprend":{"source":"iana"},"application/prs.plucker":{"source":"iana"},"application/prs.rdf-xml-crypt":{"source":"iana"},"application/prs.xsf+xml":{"source":"iana","compressible":true},"application/pskc+xml":{"source":"iana","compressible":true,"extensions":["pskcxml"]},"application/pvd+json":{"source":"iana","compressible":true},"application/qsig":{"source":"iana"},"application/raml+yaml":{"compressible":true,"extensions":["raml"]},"application/raptorfec":{"source":"iana"},"application/rdap+json":{"source":"iana","compressible":true},"application/rdf+xml":{"source":"iana","compressible":true,"extensions":["rdf","owl"]},"application/reginfo+xml":{"source":"iana","compressible":true,"extensions":["rif"]},"application/relax-ng-compact-syntax":{"source":"iana","extensions":["rnc"]},"application/remote-printing":{"source":"iana"},"application/reputon+json":{"source":"iana","compressible":true},"application/resource-lists+xml":{"source":"iana","compressible":true,"extensions":["rl"]},"application/resource-lists-diff+xml":{"source":"iana","compressible":true,"extensions":["rld"]},"application/rfc+xml":{"source":"iana","compressible":true},"application/riscos":{"source":"iana"},"application/rlmi+xml":{"source":"iana","compressible":true},"application/rls-services+xml":{"source":"iana","compressible":true,"extensions":["rs"]},"application/route-apd+xml":{"source":"iana","compressible":true,"extensions":["rapd"]},"application/route-s-tsid+xml":{"source":"iana","compressible":true,"extensions":["sls"]},"application/route-usd+xml":{"source":"iana","compressible":true,"extensions":["rusd"]},"application/rpki-ghostbusters":{"source":"iana","extensions":["gbr"]},"application/rpki-manifest":{"source":"iana","extensions":["mft"]},"application/rpki-publication":{"source":"iana"},"application/rpki-roa":{"source":"iana","extensions":["roa"]},"application/rpki-updown":{"source":"iana"},"application/rsd+xml":{"source":"apache","compressible":true,"extensions":["rsd"]},"application/rss+xml":{"source":"apache","compressible":true,"extensions":["rss"]},"application/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"application/rtploopback":{"source":"iana"},"application/rtx":{"source":"iana"},"application/samlassertion+xml":{"source":"iana","compressible":true},"application/samlmetadata+xml":{"source":"iana","compressible":true},"application/sarif+json":{"source":"iana","compressible":true},"application/sarif-external-properties+json":{"source":"iana","compressible":true},"application/sbe":{"source":"iana"},"application/sbml+xml":{"source":"iana","compressible":true,"extensions":["sbml"]},"application/scaip+xml":{"source":"iana","compressible":true},"application/scim+json":{"source":"iana","compressible":true},"application/scvp-cv-request":{"source":"iana","extensions":["scq"]},"application/scvp-cv-response":{"source":"iana","extensions":["scs"]},"application/scvp-vp-request":{"source":"iana","extensions":["spq"]},"application/scvp-vp-response":{"source":"iana","extensions":["spp"]},"application/sdp":{"source":"iana","extensions":["sdp"]},"application/secevent+jwt":{"source":"iana"},"application/senml+cbor":{"source":"iana"},"application/senml+json":{"source":"iana","compressible":true},"application/senml+xml":{"source":"iana","compressible":true,"extensions":["senmlx"]},"application/senml-etch+cbor":{"source":"iana"},"application/senml-etch+json":{"source":"iana","compressible":true},"application/senml-exi":{"source":"iana"},"application/sensml+cbor":{"source":"iana"},"application/sensml+json":{"source":"iana","compressible":true},"application/sensml+xml":{"source":"iana","compressible":true,"extensions":["sensmlx"]},"application/sensml-exi":{"source":"iana"},"application/sep+xml":{"source":"iana","compressible":true},"application/sep-exi":{"source":"iana"},"application/session-info":{"source":"iana"},"application/set-payment":{"source":"iana"},"application/set-payment-initiation":{"source":"iana","extensions":["setpay"]},"application/set-registration":{"source":"iana"},"application/set-registration-initiation":{"source":"iana","extensions":["setreg"]},"application/sgml":{"source":"iana"},"application/sgml-open-catalog":{"source":"iana"},"application/shf+xml":{"source":"iana","compressible":true,"extensions":["shf"]},"application/sieve":{"source":"iana","extensions":["siv","sieve"]},"application/simple-filter+xml":{"source":"iana","compressible":true},"application/simple-message-summary":{"source":"iana"},"application/simplesymbolcontainer":{"source":"iana"},"application/sipc":{"source":"iana"},"application/slate":{"source":"iana"},"application/smil":{"source":"iana"},"application/smil+xml":{"source":"iana","compressible":true,"extensions":["smi","smil"]},"application/smpte336m":{"source":"iana"},"application/soap+fastinfoset":{"source":"iana"},"application/soap+xml":{"source":"iana","compressible":true},"application/sparql-query":{"source":"iana","extensions":["rq"]},"application/sparql-results+xml":{"source":"iana","compressible":true,"extensions":["srx"]},"application/spdx+json":{"source":"iana","compressible":true},"application/spirits-event+xml":{"source":"iana","compressible":true},"application/sql":{"source":"iana"},"application/srgs":{"source":"iana","extensions":["gram"]},"application/srgs+xml":{"source":"iana","compressible":true,"extensions":["grxml"]},"application/sru+xml":{"source":"iana","compressible":true,"extensions":["sru"]},"application/ssdl+xml":{"source":"apache","compressible":true,"extensions":["ssdl"]},"application/ssml+xml":{"source":"iana","compressible":true,"extensions":["ssml"]},"application/stix+json":{"source":"iana","compressible":true},"application/swid+xml":{"source":"iana","compressible":true,"extensions":["swidtag"]},"application/tamp-apex-update":{"source":"iana"},"application/tamp-apex-update-confirm":{"source":"iana"},"application/tamp-community-update":{"source":"iana"},"application/tamp-community-update-confirm":{"source":"iana"},"application/tamp-error":{"source":"iana"},"application/tamp-sequence-adjust":{"source":"iana"},"application/tamp-sequence-adjust-confirm":{"source":"iana"},"application/tamp-status-query":{"source":"iana"},"application/tamp-status-response":{"source":"iana"},"application/tamp-update":{"source":"iana"},"application/tamp-update-confirm":{"source":"iana"},"application/tar":{"compressible":true},"application/taxii+json":{"source":"iana","compressible":true},"application/td+json":{"source":"iana","compressible":true},"application/tei+xml":{"source":"iana","compressible":true,"extensions":["tei","teicorpus"]},"application/tetra_isi":{"source":"iana"},"application/thraud+xml":{"source":"iana","compressible":true,"extensions":["tfi"]},"application/timestamp-query":{"source":"iana"},"application/timestamp-reply":{"source":"iana"},"application/timestamped-data":{"source":"iana","extensions":["tsd"]},"application/tlsrpt+gzip":{"source":"iana"},"application/tlsrpt+json":{"source":"iana","compressible":true},"application/tnauthlist":{"source":"iana"},"application/token-introspection+jwt":{"source":"iana"},"application/toml":{"compressible":true,"extensions":["toml"]},"application/trickle-ice-sdpfrag":{"source":"iana"},"application/trig":{"source":"iana","extensions":["trig"]},"application/ttml+xml":{"source":"iana","compressible":true,"extensions":["ttml"]},"application/tve-trigger":{"source":"iana"},"application/tzif":{"source":"iana"},"application/tzif-leap":{"source":"iana"},"application/ubjson":{"compressible":false,"extensions":["ubj"]},"application/ulpfec":{"source":"iana"},"application/urc-grpsheet+xml":{"source":"iana","compressible":true},"application/urc-ressheet+xml":{"source":"iana","compressible":true,"extensions":["rsheet"]},"application/urc-targetdesc+xml":{"source":"iana","compressible":true,"extensions":["td"]},"application/urc-uisocketdesc+xml":{"source":"iana","compressible":true},"application/vcard+json":{"source":"iana","compressible":true},"application/vcard+xml":{"source":"iana","compressible":true},"application/vemmi":{"source":"iana"},"application/vividence.scriptfile":{"source":"apache"},"application/vnd.1000minds.decision-model+xml":{"source":"iana","compressible":true,"extensions":["1km"]},"application/vnd.3gpp-prose+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-prose-pc3ch+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-v2x-local-service-information":{"source":"iana"},"application/vnd.3gpp.5gnas":{"source":"iana"},"application/vnd.3gpp.access-transfer-events+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.bsf+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gmop+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gtpc":{"source":"iana"},"application/vnd.3gpp.interworking-data":{"source":"iana"},"application/vnd.3gpp.lpp":{"source":"iana"},"application/vnd.3gpp.mc-signalling-ear":{"source":"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-payload":{"source":"iana"},"application/vnd.3gpp.mcdata-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-signalling":{"source":"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-floor-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-signed+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-init-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-transmission-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mid-call+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ngap":{"source":"iana"},"application/vnd.3gpp.pfcp":{"source":"iana"},"application/vnd.3gpp.pic-bw-large":{"source":"iana","extensions":["plb"]},"application/vnd.3gpp.pic-bw-small":{"source":"iana","extensions":["psb"]},"application/vnd.3gpp.pic-bw-var":{"source":"iana","extensions":["pvb"]},"application/vnd.3gpp.s1ap":{"source":"iana"},"application/vnd.3gpp.sms":{"source":"iana"},"application/vnd.3gpp.sms+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-ext+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.state-and-event-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ussd+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.bcmcsinfo+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.sms":{"source":"iana"},"application/vnd.3gpp2.tcap":{"source":"iana","extensions":["tcap"]},"application/vnd.3lightssoftware.imagescal":{"source":"iana"},"application/vnd.3m.post-it-notes":{"source":"iana","extensions":["pwn"]},"application/vnd.accpac.simply.aso":{"source":"iana","extensions":["aso"]},"application/vnd.accpac.simply.imp":{"source":"iana","extensions":["imp"]},"application/vnd.acucobol":{"source":"iana","extensions":["acu"]},"application/vnd.acucorp":{"source":"iana","extensions":["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{"source":"apache","compressible":false,"extensions":["air"]},"application/vnd.adobe.flash.movie":{"source":"iana"},"application/vnd.adobe.formscentral.fcdt":{"source":"iana","extensions":["fcdt"]},"application/vnd.adobe.fxp":{"source":"iana","extensions":["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{"source":"iana"},"application/vnd.adobe.xdp+xml":{"source":"iana","compressible":true,"extensions":["xdp"]},"application/vnd.adobe.xfdf":{"source":"iana","extensions":["xfdf"]},"application/vnd.aether.imp":{"source":"iana"},"application/vnd.afpc.afplinedata":{"source":"iana"},"application/vnd.afpc.afplinedata-pagedef":{"source":"iana"},"application/vnd.afpc.cmoca-cmresource":{"source":"iana"},"application/vnd.afpc.foca-charset":{"source":"iana"},"application/vnd.afpc.foca-codedfont":{"source":"iana"},"application/vnd.afpc.foca-codepage":{"source":"iana"},"application/vnd.afpc.modca":{"source":"iana"},"application/vnd.afpc.modca-cmtable":{"source":"iana"},"application/vnd.afpc.modca-formdef":{"source":"iana"},"application/vnd.afpc.modca-mediummap":{"source":"iana"},"application/vnd.afpc.modca-objectcontainer":{"source":"iana"},"application/vnd.afpc.modca-overlay":{"source":"iana"},"application/vnd.afpc.modca-pagesegment":{"source":"iana"},"application/vnd.age":{"source":"iana","extensions":["age"]},"application/vnd.ah-barcode":{"source":"iana"},"application/vnd.ahead.space":{"source":"iana","extensions":["ahead"]},"application/vnd.airzip.filesecure.azf":{"source":"iana","extensions":["azf"]},"application/vnd.airzip.filesecure.azs":{"source":"iana","extensions":["azs"]},"application/vnd.amadeus+json":{"source":"iana","compressible":true},"application/vnd.amazon.ebook":{"source":"apache","extensions":["azw"]},"application/vnd.amazon.mobi8-ebook":{"source":"iana"},"application/vnd.americandynamics.acc":{"source":"iana","extensions":["acc"]},"application/vnd.amiga.ami":{"source":"iana","extensions":["ami"]},"application/vnd.amundsen.maze+xml":{"source":"iana","compressible":true},"application/vnd.android.ota":{"source":"iana"},"application/vnd.android.package-archive":{"source":"apache","compressible":false,"extensions":["apk"]},"application/vnd.anki":{"source":"iana"},"application/vnd.anser-web-certificate-issue-initiation":{"source":"iana","extensions":["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{"source":"apache","extensions":["fti"]},"application/vnd.antix.game-component":{"source":"iana","extensions":["atx"]},"application/vnd.apache.arrow.file":{"source":"iana"},"application/vnd.apache.arrow.stream":{"source":"iana"},"application/vnd.apache.thrift.binary":{"source":"iana"},"application/vnd.apache.thrift.compact":{"source":"iana"},"application/vnd.apache.thrift.json":{"source":"iana"},"application/vnd.api+json":{"source":"iana","compressible":true},"application/vnd.aplextor.warrp+json":{"source":"iana","compressible":true},"application/vnd.apothekende.reservation+json":{"source":"iana","compressible":true},"application/vnd.apple.installer+xml":{"source":"iana","compressible":true,"extensions":["mpkg"]},"application/vnd.apple.keynote":{"source":"iana","extensions":["key"]},"application/vnd.apple.mpegurl":{"source":"iana","extensions":["m3u8"]},"application/vnd.apple.numbers":{"source":"iana","extensions":["numbers"]},"application/vnd.apple.pages":{"source":"iana","extensions":["pages"]},"application/vnd.apple.pkpass":{"compressible":false,"extensions":["pkpass"]},"application/vnd.arastra.swi":{"source":"iana"},"application/vnd.aristanetworks.swi":{"source":"iana","extensions":["swi"]},"application/vnd.artisan+json":{"source":"iana","compressible":true},"application/vnd.artsquare":{"source":"iana"},"application/vnd.astraea-software.iota":{"source":"iana","extensions":["iota"]},"application/vnd.audiograph":{"source":"iana","extensions":["aep"]},"application/vnd.autopackage":{"source":"iana"},"application/vnd.avalon+json":{"source":"iana","compressible":true},"application/vnd.avistar+xml":{"source":"iana","compressible":true},"application/vnd.balsamiq.bmml+xml":{"source":"iana","compressible":true,"extensions":["bmml"]},"application/vnd.balsamiq.bmpr":{"source":"iana"},"application/vnd.banana-accounting":{"source":"iana"},"application/vnd.bbf.usp.error":{"source":"iana"},"application/vnd.bbf.usp.msg":{"source":"iana"},"application/vnd.bbf.usp.msg+json":{"source":"iana","compressible":true},"application/vnd.bekitzur-stech+json":{"source":"iana","compressible":true},"application/vnd.bint.med-content":{"source":"iana"},"application/vnd.biopax.rdf+xml":{"source":"iana","compressible":true},"application/vnd.blink-idb-value-wrapper":{"source":"iana"},"application/vnd.blueice.multipass":{"source":"iana","extensions":["mpm"]},"application/vnd.bluetooth.ep.oob":{"source":"iana"},"application/vnd.bluetooth.le.oob":{"source":"iana"},"application/vnd.bmi":{"source":"iana","extensions":["bmi"]},"application/vnd.bpf":{"source":"iana"},"application/vnd.bpf3":{"source":"iana"},"application/vnd.businessobjects":{"source":"iana","extensions":["rep"]},"application/vnd.byu.uapi+json":{"source":"iana","compressible":true},"application/vnd.cab-jscript":{"source":"iana"},"application/vnd.canon-cpdl":{"source":"iana"},"application/vnd.canon-lips":{"source":"iana"},"application/vnd.capasystems-pg+json":{"source":"iana","compressible":true},"application/vnd.cendio.thinlinc.clientconf":{"source":"iana"},"application/vnd.century-systems.tcp_stream":{"source":"iana"},"application/vnd.chemdraw+xml":{"source":"iana","compressible":true,"extensions":["cdxml"]},"application/vnd.chess-pgn":{"source":"iana"},"application/vnd.chipnuts.karaoke-mmd":{"source":"iana","extensions":["mmd"]},"application/vnd.ciedi":{"source":"iana"},"application/vnd.cinderella":{"source":"iana","extensions":["cdy"]},"application/vnd.cirpack.isdn-ext":{"source":"iana"},"application/vnd.citationstyles.style+xml":{"source":"iana","compressible":true,"extensions":["csl"]},"application/vnd.claymore":{"source":"iana","extensions":["cla"]},"application/vnd.cloanto.rp9":{"source":"iana","extensions":["rp9"]},"application/vnd.clonk.c4group":{"source":"iana","extensions":["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{"source":"iana","extensions":["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{"source":"iana","extensions":["c11amz"]},"application/vnd.coffeescript":{"source":"iana"},"application/vnd.collabio.xodocuments.document":{"source":"iana"},"application/vnd.collabio.xodocuments.document-template":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation-template":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{"source":"iana"},"application/vnd.collection+json":{"source":"iana","compressible":true},"application/vnd.collection.doc+json":{"source":"iana","compressible":true},"application/vnd.collection.next+json":{"source":"iana","compressible":true},"application/vnd.comicbook+zip":{"source":"iana","compressible":false},"application/vnd.comicbook-rar":{"source":"iana"},"application/vnd.commerce-battelle":{"source":"iana"},"application/vnd.commonspace":{"source":"iana","extensions":["csp"]},"application/vnd.contact.cmsg":{"source":"iana","extensions":["cdbcmsg"]},"application/vnd.coreos.ignition+json":{"source":"iana","compressible":true},"application/vnd.cosmocaller":{"source":"iana","extensions":["cmc"]},"application/vnd.crick.clicker":{"source":"iana","extensions":["clkx"]},"application/vnd.crick.clicker.keyboard":{"source":"iana","extensions":["clkk"]},"application/vnd.crick.clicker.palette":{"source":"iana","extensions":["clkp"]},"application/vnd.crick.clicker.template":{"source":"iana","extensions":["clkt"]},"application/vnd.crick.clicker.wordbank":{"source":"iana","extensions":["clkw"]},"application/vnd.criticaltools.wbs+xml":{"source":"iana","compressible":true,"extensions":["wbs"]},"application/vnd.cryptii.pipe+json":{"source":"iana","compressible":true},"application/vnd.crypto-shade-file":{"source":"iana"},"application/vnd.cryptomator.encrypted":{"source":"iana"},"application/vnd.cryptomator.vault":{"source":"iana"},"application/vnd.ctc-posml":{"source":"iana","extensions":["pml"]},"application/vnd.ctct.ws+xml":{"source":"iana","compressible":true},"application/vnd.cups-pdf":{"source":"iana"},"application/vnd.cups-postscript":{"source":"iana"},"application/vnd.cups-ppd":{"source":"iana","extensions":["ppd"]},"application/vnd.cups-raster":{"source":"iana"},"application/vnd.cups-raw":{"source":"iana"},"application/vnd.curl":{"source":"iana"},"application/vnd.curl.car":{"source":"apache","extensions":["car"]},"application/vnd.curl.pcurl":{"source":"apache","extensions":["pcurl"]},"application/vnd.cyan.dean.root+xml":{"source":"iana","compressible":true},"application/vnd.cybank":{"source":"iana"},"application/vnd.cyclonedx+json":{"source":"iana","compressible":true},"application/vnd.cyclonedx+xml":{"source":"iana","compressible":true},"application/vnd.d2l.coursepackage1p0+zip":{"source":"iana","compressible":false},"application/vnd.d3m-dataset":{"source":"iana"},"application/vnd.d3m-problem":{"source":"iana"},"application/vnd.dart":{"source":"iana","compressible":true,"extensions":["dart"]},"application/vnd.data-vision.rdz":{"source":"iana","extensions":["rdz"]},"application/vnd.datapackage+json":{"source":"iana","compressible":true},"application/vnd.dataresource+json":{"source":"iana","compressible":true},"application/vnd.dbf":{"source":"iana","extensions":["dbf"]},"application/vnd.debian.binary-package":{"source":"iana"},"application/vnd.dece.data":{"source":"iana","extensions":["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{"source":"iana","compressible":true,"extensions":["uvt","uvvt"]},"application/vnd.dece.unspecified":{"source":"iana","extensions":["uvx","uvvx"]},"application/vnd.dece.zip":{"source":"iana","extensions":["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{"source":"iana","extensions":["fe_launch"]},"application/vnd.desmume.movie":{"source":"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{"source":"iana"},"application/vnd.dm.delegation+xml":{"source":"iana","compressible":true},"application/vnd.dna":{"source":"iana","extensions":["dna"]},"application/vnd.document+json":{"source":"iana","compressible":true},"application/vnd.dolby.mlp":{"source":"apache","extensions":["mlp"]},"application/vnd.dolby.mobile.1":{"source":"iana"},"application/vnd.dolby.mobile.2":{"source":"iana"},"application/vnd.doremir.scorecloud-binary-document":{"source":"iana"},"application/vnd.dpgraph":{"source":"iana","extensions":["dpg"]},"application/vnd.dreamfactory":{"source":"iana","extensions":["dfac"]},"application/vnd.drive+json":{"source":"iana","compressible":true},"application/vnd.ds-keypoint":{"source":"apache","extensions":["kpxx"]},"application/vnd.dtg.local":{"source":"iana"},"application/vnd.dtg.local.flash":{"source":"iana"},"application/vnd.dtg.local.html":{"source":"iana"},"application/vnd.dvb.ait":{"source":"iana","extensions":["ait"]},"application/vnd.dvb.dvbisl+xml":{"source":"iana","compressible":true},"application/vnd.dvb.dvbj":{"source":"iana"},"application/vnd.dvb.esgcontainer":{"source":"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess2":{"source":"iana"},"application/vnd.dvb.ipdcesgpdd":{"source":"iana"},"application/vnd.dvb.ipdcroaming":{"source":"iana"},"application/vnd.dvb.iptv.alfec-base":{"source":"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{"source":"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-container+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-generic+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-msglist+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-request+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-response+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-init+xml":{"source":"iana","compressible":true},"application/vnd.dvb.pfr":{"source":"iana"},"application/vnd.dvb.service":{"source":"iana","extensions":["svc"]},"application/vnd.dxr":{"source":"iana"},"application/vnd.dynageo":{"source":"iana","extensions":["geo"]},"application/vnd.dzr":{"source":"iana"},"application/vnd.easykaraoke.cdgdownload":{"source":"iana"},"application/vnd.ecdis-update":{"source":"iana"},"application/vnd.ecip.rlp":{"source":"iana"},"application/vnd.eclipse.ditto+json":{"source":"iana","compressible":true},"application/vnd.ecowin.chart":{"source":"iana","extensions":["mag"]},"application/vnd.ecowin.filerequest":{"source":"iana"},"application/vnd.ecowin.fileupdate":{"source":"iana"},"application/vnd.ecowin.series":{"source":"iana"},"application/vnd.ecowin.seriesrequest":{"source":"iana"},"application/vnd.ecowin.seriesupdate":{"source":"iana"},"application/vnd.efi.img":{"source":"iana"},"application/vnd.efi.iso":{"source":"iana"},"application/vnd.emclient.accessrequest+xml":{"source":"iana","compressible":true},"application/vnd.enliven":{"source":"iana","extensions":["nml"]},"application/vnd.enphase.envoy":{"source":"iana"},"application/vnd.eprints.data+xml":{"source":"iana","compressible":true},"application/vnd.epson.esf":{"source":"iana","extensions":["esf"]},"application/vnd.epson.msf":{"source":"iana","extensions":["msf"]},"application/vnd.epson.quickanime":{"source":"iana","extensions":["qam"]},"application/vnd.epson.salt":{"source":"iana","extensions":["slt"]},"application/vnd.epson.ssf":{"source":"iana","extensions":["ssf"]},"application/vnd.ericsson.quickcall":{"source":"iana"},"application/vnd.espass-espass+zip":{"source":"iana","compressible":false},"application/vnd.eszigno3+xml":{"source":"iana","compressible":true,"extensions":["es3","et3"]},"application/vnd.etsi.aoc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.asic-e+zip":{"source":"iana","compressible":false},"application/vnd.etsi.asic-s+zip":{"source":"iana","compressible":false},"application/vnd.etsi.cug+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvcommand+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-bc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-cod+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-npvr+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvservice+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsync+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvueprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mcid+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mheg5":{"source":"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{"source":"iana","compressible":true},"application/vnd.etsi.pstn+xml":{"source":"iana","compressible":true},"application/vnd.etsi.sci+xml":{"source":"iana","compressible":true},"application/vnd.etsi.simservs+xml":{"source":"iana","compressible":true},"application/vnd.etsi.timestamp-token":{"source":"iana"},"application/vnd.etsi.tsl+xml":{"source":"iana","compressible":true},"application/vnd.etsi.tsl.der":{"source":"iana"},"application/vnd.eu.kasparian.car+json":{"source":"iana","compressible":true},"application/vnd.eudora.data":{"source":"iana"},"application/vnd.evolv.ecig.profile":{"source":"iana"},"application/vnd.evolv.ecig.settings":{"source":"iana"},"application/vnd.evolv.ecig.theme":{"source":"iana"},"application/vnd.exstream-empower+zip":{"source":"iana","compressible":false},"application/vnd.exstream-package":{"source":"iana"},"application/vnd.ezpix-album":{"source":"iana","extensions":["ez2"]},"application/vnd.ezpix-package":{"source":"iana","extensions":["ez3"]},"application/vnd.f-secure.mobile":{"source":"iana"},"application/vnd.familysearch.gedcom+zip":{"source":"iana","compressible":false},"application/vnd.fastcopy-disk-image":{"source":"iana"},"application/vnd.fdf":{"source":"iana","extensions":["fdf"]},"application/vnd.fdsn.mseed":{"source":"iana","extensions":["mseed"]},"application/vnd.fdsn.seed":{"source":"iana","extensions":["seed","dataless"]},"application/vnd.ffsns":{"source":"iana"},"application/vnd.ficlab.flb+zip":{"source":"iana","compressible":false},"application/vnd.filmit.zfc":{"source":"iana"},"application/vnd.fints":{"source":"iana"},"application/vnd.firemonkeys.cloudcell":{"source":"iana"},"application/vnd.flographit":{"source":"iana","extensions":["gph"]},"application/vnd.fluxtime.clip":{"source":"iana","extensions":["ftc"]},"application/vnd.font-fontforge-sfd":{"source":"iana"},"application/vnd.framemaker":{"source":"iana","extensions":["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{"source":"iana","extensions":["fnc"]},"application/vnd.frogans.ltf":{"source":"iana","extensions":["ltf"]},"application/vnd.fsc.weblaunch":{"source":"iana","extensions":["fsc"]},"application/vnd.fujifilm.fb.docuworks":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.container":{"source":"iana"},"application/vnd.fujifilm.fb.jfi+xml":{"source":"iana","compressible":true},"application/vnd.fujitsu.oasys":{"source":"iana","extensions":["oas"]},"application/vnd.fujitsu.oasys2":{"source":"iana","extensions":["oa2"]},"application/vnd.fujitsu.oasys3":{"source":"iana","extensions":["oa3"]},"application/vnd.fujitsu.oasysgp":{"source":"iana","extensions":["fg5"]},"application/vnd.fujitsu.oasysprs":{"source":"iana","extensions":["bh2"]},"application/vnd.fujixerox.art-ex":{"source":"iana"},"application/vnd.fujixerox.art4":{"source":"iana"},"application/vnd.fujixerox.ddd":{"source":"iana","extensions":["ddd"]},"application/vnd.fujixerox.docuworks":{"source":"iana","extensions":["xdw"]},"application/vnd.fujixerox.docuworks.binder":{"source":"iana","extensions":["xbd"]},"application/vnd.fujixerox.docuworks.container":{"source":"iana"},"application/vnd.fujixerox.hbpl":{"source":"iana"},"application/vnd.fut-misnet":{"source":"iana"},"application/vnd.futoin+cbor":{"source":"iana"},"application/vnd.futoin+json":{"source":"iana","compressible":true},"application/vnd.fuzzysheet":{"source":"iana","extensions":["fzs"]},"application/vnd.genomatix.tuxedo":{"source":"iana","extensions":["txd"]},"application/vnd.gentics.grd+json":{"source":"iana","compressible":true},"application/vnd.geo+json":{"source":"iana","compressible":true},"application/vnd.geocube+xml":{"source":"iana","compressible":true},"application/vnd.geogebra.file":{"source":"iana","extensions":["ggb"]},"application/vnd.geogebra.slides":{"source":"iana"},"application/vnd.geogebra.tool":{"source":"iana","extensions":["ggt"]},"application/vnd.geometry-explorer":{"source":"iana","extensions":["gex","gre"]},"application/vnd.geonext":{"source":"iana","extensions":["gxt"]},"application/vnd.geoplan":{"source":"iana","extensions":["g2w"]},"application/vnd.geospace":{"source":"iana","extensions":["g3w"]},"application/vnd.gerber":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt-response":{"source":"iana"},"application/vnd.gmx":{"source":"iana","extensions":["gmx"]},"application/vnd.google-apps.document":{"compressible":false,"extensions":["gdoc"]},"application/vnd.google-apps.presentation":{"compressible":false,"extensions":["gslides"]},"application/vnd.google-apps.spreadsheet":{"compressible":false,"extensions":["gsheet"]},"application/vnd.google-earth.kml+xml":{"source":"iana","compressible":true,"extensions":["kml"]},"application/vnd.google-earth.kmz":{"source":"iana","compressible":false,"extensions":["kmz"]},"application/vnd.gov.sk.e-form+xml":{"source":"iana","compressible":true},"application/vnd.gov.sk.e-form+zip":{"source":"iana","compressible":false},"application/vnd.gov.sk.xmldatacontainer+xml":{"source":"iana","compressible":true},"application/vnd.grafeq":{"source":"iana","extensions":["gqf","gqs"]},"application/vnd.gridmp":{"source":"iana"},"application/vnd.groove-account":{"source":"iana","extensions":["gac"]},"application/vnd.groove-help":{"source":"iana","extensions":["ghf"]},"application/vnd.groove-identity-message":{"source":"iana","extensions":["gim"]},"application/vnd.groove-injector":{"source":"iana","extensions":["grv"]},"application/vnd.groove-tool-message":{"source":"iana","extensions":["gtm"]},"application/vnd.groove-tool-template":{"source":"iana","extensions":["tpl"]},"application/vnd.groove-vcard":{"source":"iana","extensions":["vcg"]},"application/vnd.hal+json":{"source":"iana","compressible":true},"application/vnd.hal+xml":{"source":"iana","compressible":true,"extensions":["hal"]},"application/vnd.handheld-entertainment+xml":{"source":"iana","compressible":true,"extensions":["zmm"]},"application/vnd.hbci":{"source":"iana","extensions":["hbci"]},"application/vnd.hc+json":{"source":"iana","compressible":true},"application/vnd.hcl-bireports":{"source":"iana"},"application/vnd.hdt":{"source":"iana"},"application/vnd.heroku+json":{"source":"iana","compressible":true},"application/vnd.hhe.lesson-player":{"source":"iana","extensions":["les"]},"application/vnd.hl7cda+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hl7v2+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hp-hpgl":{"source":"iana","extensions":["hpgl"]},"application/vnd.hp-hpid":{"source":"iana","extensions":["hpid"]},"application/vnd.hp-hps":{"source":"iana","extensions":["hps"]},"application/vnd.hp-jlyt":{"source":"iana","extensions":["jlt"]},"application/vnd.hp-pcl":{"source":"iana","extensions":["pcl"]},"application/vnd.hp-pclxl":{"source":"iana","extensions":["pclxl"]},"application/vnd.httphone":{"source":"iana"},"application/vnd.hydrostatix.sof-data":{"source":"iana","extensions":["sfd-hdstx"]},"application/vnd.hyper+json":{"source":"iana","compressible":true},"application/vnd.hyper-item+json":{"source":"iana","compressible":true},"application/vnd.hyperdrive+json":{"source":"iana","compressible":true},"application/vnd.hzn-3d-crossword":{"source":"iana"},"application/vnd.ibm.afplinedata":{"source":"iana"},"application/vnd.ibm.electronic-media":{"source":"iana"},"application/vnd.ibm.minipay":{"source":"iana","extensions":["mpy"]},"application/vnd.ibm.modcap":{"source":"iana","extensions":["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{"source":"iana","extensions":["irm"]},"application/vnd.ibm.secure-container":{"source":"iana","extensions":["sc"]},"application/vnd.iccprofile":{"source":"iana","extensions":["icc","icm"]},"application/vnd.ieee.1905":{"source":"iana"},"application/vnd.igloader":{"source":"iana","extensions":["igl"]},"application/vnd.imagemeter.folder+zip":{"source":"iana","compressible":false},"application/vnd.imagemeter.image+zip":{"source":"iana","compressible":false},"application/vnd.immervision-ivp":{"source":"iana","extensions":["ivp"]},"application/vnd.immervision-ivu":{"source":"iana","extensions":["ivu"]},"application/vnd.ims.imsccv1p1":{"source":"iana"},"application/vnd.ims.imsccv1p2":{"source":"iana"},"application/vnd.ims.imsccv1p3":{"source":"iana"},"application/vnd.ims.lis.v2.result+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy.id+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings.simple+json":{"source":"iana","compressible":true},"application/vnd.informedcontrol.rms+xml":{"source":"iana","compressible":true},"application/vnd.informix-visionary":{"source":"iana"},"application/vnd.infotech.project":{"source":"iana"},"application/vnd.infotech.project+xml":{"source":"iana","compressible":true},"application/vnd.innopath.wamp.notification":{"source":"iana"},"application/vnd.insors.igm":{"source":"iana","extensions":["igm"]},"application/vnd.intercon.formnet":{"source":"iana","extensions":["xpw","xpx"]},"application/vnd.intergeo":{"source":"iana","extensions":["i2g"]},"application/vnd.intertrust.digibox":{"source":"iana"},"application/vnd.intertrust.nncp":{"source":"iana"},"application/vnd.intu.qbo":{"source":"iana","extensions":["qbo"]},"application/vnd.intu.qfx":{"source":"iana","extensions":["qfx"]},"application/vnd.iptc.g2.catalogitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.conceptitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.knowledgeitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsmessage+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.packageitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.planningitem+xml":{"source":"iana","compressible":true},"application/vnd.ipunplugged.rcprofile":{"source":"iana","extensions":["rcprofile"]},"application/vnd.irepository.package+xml":{"source":"iana","compressible":true,"extensions":["irp"]},"application/vnd.is-xpr":{"source":"iana","extensions":["xpr"]},"application/vnd.isac.fcs":{"source":"iana","extensions":["fcs"]},"application/vnd.iso11783-10+zip":{"source":"iana","compressible":false},"application/vnd.jam":{"source":"iana","extensions":["jam"]},"application/vnd.japannet-directory-service":{"source":"iana"},"application/vnd.japannet-jpnstore-wakeup":{"source":"iana"},"application/vnd.japannet-payment-wakeup":{"source":"iana"},"application/vnd.japannet-registration":{"source":"iana"},"application/vnd.japannet-registration-wakeup":{"source":"iana"},"application/vnd.japannet-setstore-wakeup":{"source":"iana"},"application/vnd.japannet-verification":{"source":"iana"},"application/vnd.japannet-verification-wakeup":{"source":"iana"},"application/vnd.jcp.javame.midlet-rms":{"source":"iana","extensions":["rms"]},"application/vnd.jisp":{"source":"iana","extensions":["jisp"]},"application/vnd.joost.joda-archive":{"source":"iana","extensions":["joda"]},"application/vnd.jsk.isdn-ngn":{"source":"iana"},"application/vnd.kahootz":{"source":"iana","extensions":["ktz","ktr"]},"application/vnd.kde.karbon":{"source":"iana","extensions":["karbon"]},"application/vnd.kde.kchart":{"source":"iana","extensions":["chrt"]},"application/vnd.kde.kformula":{"source":"iana","extensions":["kfo"]},"application/vnd.kde.kivio":{"source":"iana","extensions":["flw"]},"application/vnd.kde.kontour":{"source":"iana","extensions":["kon"]},"application/vnd.kde.kpresenter":{"source":"iana","extensions":["kpr","kpt"]},"application/vnd.kde.kspread":{"source":"iana","extensions":["ksp"]},"application/vnd.kde.kword":{"source":"iana","extensions":["kwd","kwt"]},"application/vnd.kenameaapp":{"source":"iana","extensions":["htke"]},"application/vnd.kidspiration":{"source":"iana","extensions":["kia"]},"application/vnd.kinar":{"source":"iana","extensions":["kne","knp"]},"application/vnd.koan":{"source":"iana","extensions":["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{"source":"iana","extensions":["sse"]},"application/vnd.las":{"source":"iana"},"application/vnd.las.las+json":{"source":"iana","compressible":true},"application/vnd.las.las+xml":{"source":"iana","compressible":true,"extensions":["lasxml"]},"application/vnd.laszip":{"source":"iana"},"application/vnd.leap+json":{"source":"iana","compressible":true},"application/vnd.liberty-request+xml":{"source":"iana","compressible":true},"application/vnd.llamagraphics.life-balance.desktop":{"source":"iana","extensions":["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{"source":"iana","compressible":true,"extensions":["lbe"]},"application/vnd.logipipe.circuit+zip":{"source":"iana","compressible":false},"application/vnd.loom":{"source":"iana"},"application/vnd.lotus-1-2-3":{"source":"iana","extensions":["123"]},"application/vnd.lotus-approach":{"source":"iana","extensions":["apr"]},"application/vnd.lotus-freelance":{"source":"iana","extensions":["pre"]},"application/vnd.lotus-notes":{"source":"iana","extensions":["nsf"]},"application/vnd.lotus-organizer":{"source":"iana","extensions":["org"]},"application/vnd.lotus-screencam":{"source":"iana","extensions":["scm"]},"application/vnd.lotus-wordpro":{"source":"iana","extensions":["lwp"]},"application/vnd.macports.portpkg":{"source":"iana","extensions":["portpkg"]},"application/vnd.mapbox-vector-tile":{"source":"iana","extensions":["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.conftoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.license+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.mdcf":{"source":"iana"},"application/vnd.mason+json":{"source":"iana","compressible":true},"application/vnd.maxar.archive.3tz+zip":{"source":"iana","compressible":false},"application/vnd.maxmind.maxmind-db":{"source":"iana"},"application/vnd.mcd":{"source":"iana","extensions":["mcd"]},"application/vnd.medcalcdata":{"source":"iana","extensions":["mc1"]},"application/vnd.mediastation.cdkey":{"source":"iana","extensions":["cdkey"]},"application/vnd.meridian-slingshot":{"source":"iana"},"application/vnd.mfer":{"source":"iana","extensions":["mwf"]},"application/vnd.mfmp":{"source":"iana","extensions":["mfm"]},"application/vnd.micro+json":{"source":"iana","compressible":true},"application/vnd.micrografx.flo":{"source":"iana","extensions":["flo"]},"application/vnd.micrografx.igx":{"source":"iana","extensions":["igx"]},"application/vnd.microsoft.portable-executable":{"source":"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{"source":"iana"},"application/vnd.miele+json":{"source":"iana","compressible":true},"application/vnd.mif":{"source":"iana","extensions":["mif"]},"application/vnd.minisoft-hp3000-save":{"source":"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{"source":"iana"},"application/vnd.mobius.daf":{"source":"iana","extensions":["daf"]},"application/vnd.mobius.dis":{"source":"iana","extensions":["dis"]},"application/vnd.mobius.mbk":{"source":"iana","extensions":["mbk"]},"application/vnd.mobius.mqy":{"source":"iana","extensions":["mqy"]},"application/vnd.mobius.msl":{"source":"iana","extensions":["msl"]},"application/vnd.mobius.plc":{"source":"iana","extensions":["plc"]},"application/vnd.mobius.txf":{"source":"iana","extensions":["txf"]},"application/vnd.mophun.application":{"source":"iana","extensions":["mpn"]},"application/vnd.mophun.certificate":{"source":"iana","extensions":["mpc"]},"application/vnd.motorola.flexsuite":{"source":"iana"},"application/vnd.motorola.flexsuite.adsi":{"source":"iana"},"application/vnd.motorola.flexsuite.fis":{"source":"iana"},"application/vnd.motorola.flexsuite.gotap":{"source":"iana"},"application/vnd.motorola.flexsuite.kmr":{"source":"iana"},"application/vnd.motorola.flexsuite.ttc":{"source":"iana"},"application/vnd.motorola.flexsuite.wem":{"source":"iana"},"application/vnd.motorola.iprm":{"source":"iana"},"application/vnd.mozilla.xul+xml":{"source":"iana","compressible":true,"extensions":["xul"]},"application/vnd.ms-3mfdocument":{"source":"iana"},"application/vnd.ms-artgalry":{"source":"iana","extensions":["cil"]},"application/vnd.ms-asf":{"source":"iana"},"application/vnd.ms-cab-compressed":{"source":"iana","extensions":["cab"]},"application/vnd.ms-color.iccprofile":{"source":"apache"},"application/vnd.ms-excel":{"source":"iana","compressible":false,"extensions":["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{"source":"iana","extensions":["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{"source":"iana","extensions":["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{"source":"iana","extensions":["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{"source":"iana","extensions":["xltm"]},"application/vnd.ms-fontobject":{"source":"iana","compressible":true,"extensions":["eot"]},"application/vnd.ms-htmlhelp":{"source":"iana","extensions":["chm"]},"application/vnd.ms-ims":{"source":"iana","extensions":["ims"]},"application/vnd.ms-lrm":{"source":"iana","extensions":["lrm"]},"application/vnd.ms-office.activex+xml":{"source":"iana","compressible":true},"application/vnd.ms-officetheme":{"source":"iana","extensions":["thmx"]},"application/vnd.ms-opentype":{"source":"apache","compressible":true},"application/vnd.ms-outlook":{"compressible":false,"extensions":["msg"]},"application/vnd.ms-package.obfuscated-opentype":{"source":"apache"},"application/vnd.ms-pki.seccat":{"source":"apache","extensions":["cat"]},"application/vnd.ms-pki.stl":{"source":"apache","extensions":["stl"]},"application/vnd.ms-playready.initiator+xml":{"source":"iana","compressible":true},"application/vnd.ms-powerpoint":{"source":"iana","compressible":false,"extensions":["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{"source":"iana","extensions":["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{"source":"iana","extensions":["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{"source":"iana","extensions":["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{"source":"iana","extensions":["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{"source":"iana","extensions":["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{"source":"iana","compressible":true},"application/vnd.ms-printing.printticket+xml":{"source":"apache","compressible":true},"application/vnd.ms-printschematicket+xml":{"source":"iana","compressible":true},"application/vnd.ms-project":{"source":"iana","extensions":["mpp","mpt"]},"application/vnd.ms-tnef":{"source":"iana"},"application/vnd.ms-windows.devicepairing":{"source":"iana"},"application/vnd.ms-windows.nwprinting.oob":{"source":"iana"},"application/vnd.ms-windows.printerpairing":{"source":"iana"},"application/vnd.ms-windows.wsd.oob":{"source":"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.lic-resp":{"source":"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.meter-resp":{"source":"iana"},"application/vnd.ms-word.document.macroenabled.12":{"source":"iana","extensions":["docm"]},"application/vnd.ms-word.template.macroenabled.12":{"source":"iana","extensions":["dotm"]},"application/vnd.ms-works":{"source":"iana","extensions":["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{"source":"iana","extensions":["wpl"]},"application/vnd.ms-xpsdocument":{"source":"iana","compressible":false,"extensions":["xps"]},"application/vnd.msa-disk-image":{"source":"iana"},"application/vnd.mseq":{"source":"iana","extensions":["mseq"]},"application/vnd.msign":{"source":"iana"},"application/vnd.multiad.creator":{"source":"iana"},"application/vnd.multiad.creator.cif":{"source":"iana"},"application/vnd.music-niff":{"source":"iana"},"application/vnd.musician":{"source":"iana","extensions":["mus"]},"application/vnd.muvee.style":{"source":"iana","extensions":["msty"]},"application/vnd.mynfc":{"source":"iana","extensions":["taglet"]},"application/vnd.nacamar.ybrid+json":{"source":"iana","compressible":true},"application/vnd.ncd.control":{"source":"iana"},"application/vnd.ncd.reference":{"source":"iana"},"application/vnd.nearst.inv+json":{"source":"iana","compressible":true},"application/vnd.nebumind.line":{"source":"iana"},"application/vnd.nervana":{"source":"iana"},"application/vnd.netfpx":{"source":"iana"},"application/vnd.neurolanguage.nlu":{"source":"iana","extensions":["nlu"]},"application/vnd.nimn":{"source":"iana"},"application/vnd.nintendo.nitro.rom":{"source":"iana"},"application/vnd.nintendo.snes.rom":{"source":"iana"},"application/vnd.nitf":{"source":"iana","extensions":["ntf","nitf"]},"application/vnd.noblenet-directory":{"source":"iana","extensions":["nnd"]},"application/vnd.noblenet-sealer":{"source":"iana","extensions":["nns"]},"application/vnd.noblenet-web":{"source":"iana","extensions":["nnw"]},"application/vnd.nokia.catalogs":{"source":"iana"},"application/vnd.nokia.conml+wbxml":{"source":"iana"},"application/vnd.nokia.conml+xml":{"source":"iana","compressible":true},"application/vnd.nokia.iptv.config+xml":{"source":"iana","compressible":true},"application/vnd.nokia.isds-radio-presets":{"source":"iana"},"application/vnd.nokia.landmark+wbxml":{"source":"iana"},"application/vnd.nokia.landmark+xml":{"source":"iana","compressible":true},"application/vnd.nokia.landmarkcollection+xml":{"source":"iana","compressible":true},"application/vnd.nokia.n-gage.ac+xml":{"source":"iana","compressible":true,"extensions":["ac"]},"application/vnd.nokia.n-gage.data":{"source":"iana","extensions":["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{"source":"iana","extensions":["n-gage"]},"application/vnd.nokia.ncd":{"source":"iana"},"application/vnd.nokia.pcd+wbxml":{"source":"iana"},"application/vnd.nokia.pcd+xml":{"source":"iana","compressible":true},"application/vnd.nokia.radio-preset":{"source":"iana","extensions":["rpst"]},"application/vnd.nokia.radio-presets":{"source":"iana","extensions":["rpss"]},"application/vnd.novadigm.edm":{"source":"iana","extensions":["edm"]},"application/vnd.novadigm.edx":{"source":"iana","extensions":["edx"]},"application/vnd.novadigm.ext":{"source":"iana","extensions":["ext"]},"application/vnd.ntt-local.content-share":{"source":"iana"},"application/vnd.ntt-local.file-transfer":{"source":"iana"},"application/vnd.ntt-local.ogw_remote-access":{"source":"iana"},"application/vnd.ntt-local.sip-ta_remote":{"source":"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{"source":"iana"},"application/vnd.oasis.opendocument.chart":{"source":"iana","extensions":["odc"]},"application/vnd.oasis.opendocument.chart-template":{"source":"iana","extensions":["otc"]},"application/vnd.oasis.opendocument.database":{"source":"iana","extensions":["odb"]},"application/vnd.oasis.opendocument.formula":{"source":"iana","extensions":["odf"]},"application/vnd.oasis.opendocument.formula-template":{"source":"iana","extensions":["odft"]},"application/vnd.oasis.opendocument.graphics":{"source":"iana","compressible":false,"extensions":["odg"]},"application/vnd.oasis.opendocument.graphics-template":{"source":"iana","extensions":["otg"]},"application/vnd.oasis.opendocument.image":{"source":"iana","extensions":["odi"]},"application/vnd.oasis.opendocument.image-template":{"source":"iana","extensions":["oti"]},"application/vnd.oasis.opendocument.presentation":{"source":"iana","compressible":false,"extensions":["odp"]},"application/vnd.oasis.opendocument.presentation-template":{"source":"iana","extensions":["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{"source":"iana","compressible":false,"extensions":["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{"source":"iana","extensions":["ots"]},"application/vnd.oasis.opendocument.text":{"source":"iana","compressible":false,"extensions":["odt"]},"application/vnd.oasis.opendocument.text-master":{"source":"iana","extensions":["odm"]},"application/vnd.oasis.opendocument.text-template":{"source":"iana","extensions":["ott"]},"application/vnd.oasis.opendocument.text-web":{"source":"iana","extensions":["oth"]},"application/vnd.obn":{"source":"iana"},"application/vnd.ocf+cbor":{"source":"iana"},"application/vnd.oci.image.manifest.v1+json":{"source":"iana","compressible":true},"application/vnd.oftn.l10n+json":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessdownload+xml":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessstreaming+xml":{"source":"iana","compressible":true},"application/vnd.oipf.cspg-hexbinary":{"source":"iana"},"application/vnd.oipf.dae.svg+xml":{"source":"iana","compressible":true},"application/vnd.oipf.dae.xhtml+xml":{"source":"iana","compressible":true},"application/vnd.oipf.mippvcontrolmessage+xml":{"source":"iana","compressible":true},"application/vnd.oipf.pae.gem":{"source":"iana"},"application/vnd.oipf.spdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.oipf.spdlist+xml":{"source":"iana","compressible":true},"application/vnd.oipf.ueprofile+xml":{"source":"iana","compressible":true},"application/vnd.oipf.userprofile+xml":{"source":"iana","compressible":true},"application/vnd.olpc-sugar":{"source":"iana","extensions":["xo"]},"application/vnd.oma-scws-config":{"source":"iana"},"application/vnd.oma-scws-http-request":{"source":"iana"},"application/vnd.oma-scws-http-response":{"source":"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.drm-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.imd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.ltkm":{"source":"iana"},"application/vnd.oma.bcast.notification+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.provisioningtrigger":{"source":"iana"},"application/vnd.oma.bcast.sgboot":{"source":"iana"},"application/vnd.oma.bcast.sgdd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sgdu":{"source":"iana"},"application/vnd.oma.bcast.simple-symbol-container":{"source":"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sprov+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.stkm":{"source":"iana"},"application/vnd.oma.cab-address-book+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-feature-handler+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-pcc+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-subs-invite+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-user-prefs+xml":{"source":"iana","compressible":true},"application/vnd.oma.dcd":{"source":"iana"},"application/vnd.oma.dcdc":{"source":"iana"},"application/vnd.oma.dd2+xml":{"source":"iana","compressible":true,"extensions":["dd2"]},"application/vnd.oma.drm.risd+xml":{"source":"iana","compressible":true},"application/vnd.oma.group-usage-list+xml":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+cbor":{"source":"iana"},"application/vnd.oma.lwm2m+json":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+tlv":{"source":"iana"},"application/vnd.oma.pal+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.detailed-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.final-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.groups+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.invocation-descriptor+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.optimized-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.push":{"source":"iana"},"application/vnd.oma.scidm.messages+xml":{"source":"iana","compressible":true},"application/vnd.oma.xcap-directory+xml":{"source":"iana","compressible":true},"application/vnd.omads-email+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-file+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-folder+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omaloc-supl-init":{"source":"iana"},"application/vnd.onepager":{"source":"iana"},"application/vnd.onepagertamp":{"source":"iana"},"application/vnd.onepagertamx":{"source":"iana"},"application/vnd.onepagertat":{"source":"iana"},"application/vnd.onepagertatp":{"source":"iana"},"application/vnd.onepagertatx":{"source":"iana"},"application/vnd.openblox.game+xml":{"source":"iana","compressible":true,"extensions":["obgx"]},"application/vnd.openblox.game-binary":{"source":"iana"},"application/vnd.openeye.oeb":{"source":"iana"},"application/vnd.openofficeorg.extension":{"source":"apache","extensions":["oxt"]},"application/vnd.openstreetmap.data+xml":{"source":"iana","compressible":true,"extensions":["osm"]},"application/vnd.opentimestamps.ots":{"source":"iana"},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawing+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{"source":"iana","compressible":false,"extensions":["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slide":{"source":"iana","extensions":["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{"source":"iana","extensions":["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.template":{"source":"iana","extensions":["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"source":"iana","compressible":false,"extensions":["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{"source":"iana","extensions":["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.theme+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.vmldrawing":{"source":"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{"source":"iana","compressible":false,"extensions":["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{"source":"iana","extensions":["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.core-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.relationships+xml":{"source":"iana","compressible":true},"application/vnd.oracle.resource+json":{"source":"iana","compressible":true},"application/vnd.orange.indata":{"source":"iana"},"application/vnd.osa.netdeploy":{"source":"iana"},"application/vnd.osgeo.mapguide.package":{"source":"iana","extensions":["mgp"]},"application/vnd.osgi.bundle":{"source":"iana"},"application/vnd.osgi.dp":{"source":"iana","extensions":["dp"]},"application/vnd.osgi.subsystem":{"source":"iana","extensions":["esa"]},"application/vnd.otps.ct-kip+xml":{"source":"iana","compressible":true},"application/vnd.oxli.countgraph":{"source":"iana"},"application/vnd.pagerduty+json":{"source":"iana","compressible":true},"application/vnd.palm":{"source":"iana","extensions":["pdb","pqa","oprc"]},"application/vnd.panoply":{"source":"iana"},"application/vnd.paos.xml":{"source":"iana"},"application/vnd.patentdive":{"source":"iana"},"application/vnd.patientecommsdoc":{"source":"iana"},"application/vnd.pawaafile":{"source":"iana","extensions":["paw"]},"application/vnd.pcos":{"source":"iana"},"application/vnd.pg.format":{"source":"iana","extensions":["str"]},"application/vnd.pg.osasli":{"source":"iana","extensions":["ei6"]},"application/vnd.piaccess.application-licence":{"source":"iana"},"application/vnd.picsel":{"source":"iana","extensions":["efif"]},"application/vnd.pmi.widget":{"source":"iana","extensions":["wg"]},"application/vnd.poc.group-advertisement+xml":{"source":"iana","compressible":true},"application/vnd.pocketlearn":{"source":"iana","extensions":["plf"]},"application/vnd.powerbuilder6":{"source":"iana","extensions":["pbd"]},"application/vnd.powerbuilder6-s":{"source":"iana"},"application/vnd.powerbuilder7":{"source":"iana"},"application/vnd.powerbuilder7-s":{"source":"iana"},"application/vnd.powerbuilder75":{"source":"iana"},"application/vnd.powerbuilder75-s":{"source":"iana"},"application/vnd.preminet":{"source":"iana"},"application/vnd.previewsystems.box":{"source":"iana","extensions":["box"]},"application/vnd.proteus.magazine":{"source":"iana","extensions":["mgz"]},"application/vnd.psfs":{"source":"iana"},"application/vnd.publishare-delta-tree":{"source":"iana","extensions":["qps"]},"application/vnd.pvi.ptid1":{"source":"iana","extensions":["ptid"]},"application/vnd.pwg-multiplexed":{"source":"iana"},"application/vnd.pwg-xhtml-print+xml":{"source":"iana","compressible":true},"application/vnd.qualcomm.brew-app-res":{"source":"iana"},"application/vnd.quarantainenet":{"source":"iana"},"application/vnd.quark.quarkxpress":{"source":"iana","extensions":["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{"source":"iana"},"application/vnd.radisys.moml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conn+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-stream+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-base+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-detect+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-group+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-speech+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-transform+xml":{"source":"iana","compressible":true},"application/vnd.rainstor.data":{"source":"iana"},"application/vnd.rapid":{"source":"iana"},"application/vnd.rar":{"source":"iana","extensions":["rar"]},"application/vnd.realvnc.bed":{"source":"iana","extensions":["bed"]},"application/vnd.recordare.musicxml":{"source":"iana","extensions":["mxl"]},"application/vnd.recordare.musicxml+xml":{"source":"iana","compressible":true,"extensions":["musicxml"]},"application/vnd.renlearn.rlprint":{"source":"iana"},"application/vnd.resilient.logic":{"source":"iana"},"application/vnd.restful+json":{"source":"iana","compressible":true},"application/vnd.rig.cryptonote":{"source":"iana","extensions":["cryptonote"]},"application/vnd.rim.cod":{"source":"apache","extensions":["cod"]},"application/vnd.rn-realmedia":{"source":"apache","extensions":["rm"]},"application/vnd.rn-realmedia-vbr":{"source":"apache","extensions":["rmvb"]},"application/vnd.route66.link66+xml":{"source":"iana","compressible":true,"extensions":["link66"]},"application/vnd.rs-274x":{"source":"iana"},"application/vnd.ruckus.download":{"source":"iana"},"application/vnd.s3sms":{"source":"iana"},"application/vnd.sailingtracker.track":{"source":"iana","extensions":["st"]},"application/vnd.sar":{"source":"iana"},"application/vnd.sbm.cid":{"source":"iana"},"application/vnd.sbm.mid2":{"source":"iana"},"application/vnd.scribus":{"source":"iana"},"application/vnd.sealed.3df":{"source":"iana"},"application/vnd.sealed.csf":{"source":"iana"},"application/vnd.sealed.doc":{"source":"iana"},"application/vnd.sealed.eml":{"source":"iana"},"application/vnd.sealed.mht":{"source":"iana"},"application/vnd.sealed.net":{"source":"iana"},"application/vnd.sealed.ppt":{"source":"iana"},"application/vnd.sealed.tiff":{"source":"iana"},"application/vnd.sealed.xls":{"source":"iana"},"application/vnd.sealedmedia.softseal.html":{"source":"iana"},"application/vnd.sealedmedia.softseal.pdf":{"source":"iana"},"application/vnd.seemail":{"source":"iana","extensions":["see"]},"application/vnd.seis+json":{"source":"iana","compressible":true},"application/vnd.sema":{"source":"iana","extensions":["sema"]},"application/vnd.semd":{"source":"iana","extensions":["semd"]},"application/vnd.semf":{"source":"iana","extensions":["semf"]},"application/vnd.shade-save-file":{"source":"iana"},"application/vnd.shana.informed.formdata":{"source":"iana","extensions":["ifm"]},"application/vnd.shana.informed.formtemplate":{"source":"iana","extensions":["itp"]},"application/vnd.shana.informed.interchange":{"source":"iana","extensions":["iif"]},"application/vnd.shana.informed.package":{"source":"iana","extensions":["ipk"]},"application/vnd.shootproof+json":{"source":"iana","compressible":true},"application/vnd.shopkick+json":{"source":"iana","compressible":true},"application/vnd.shp":{"source":"iana"},"application/vnd.shx":{"source":"iana"},"application/vnd.sigrok.session":{"source":"iana"},"application/vnd.simtech-mindmapper":{"source":"iana","extensions":["twd","twds"]},"application/vnd.siren+json":{"source":"iana","compressible":true},"application/vnd.smaf":{"source":"iana","extensions":["mmf"]},"application/vnd.smart.notebook":{"source":"iana"},"application/vnd.smart.teacher":{"source":"iana","extensions":["teacher"]},"application/vnd.snesdev-page-table":{"source":"iana"},"application/vnd.software602.filler.form+xml":{"source":"iana","compressible":true,"extensions":["fo"]},"application/vnd.software602.filler.form-xml-zip":{"source":"iana"},"application/vnd.solent.sdkm+xml":{"source":"iana","compressible":true,"extensions":["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{"source":"iana","extensions":["dxp"]},"application/vnd.spotfire.sfs":{"source":"iana","extensions":["sfs"]},"application/vnd.sqlite3":{"source":"iana"},"application/vnd.sss-cod":{"source":"iana"},"application/vnd.sss-dtf":{"source":"iana"},"application/vnd.sss-ntf":{"source":"iana"},"application/vnd.stardivision.calc":{"source":"apache","extensions":["sdc"]},"application/vnd.stardivision.draw":{"source":"apache","extensions":["sda"]},"application/vnd.stardivision.impress":{"source":"apache","extensions":["sdd"]},"application/vnd.stardivision.math":{"source":"apache","extensions":["smf"]},"application/vnd.stardivision.writer":{"source":"apache","extensions":["sdw","vor"]},"application/vnd.stardivision.writer-global":{"source":"apache","extensions":["sgl"]},"application/vnd.stepmania.package":{"source":"iana","extensions":["smzip"]},"application/vnd.stepmania.stepchart":{"source":"iana","extensions":["sm"]},"application/vnd.street-stream":{"source":"iana"},"application/vnd.sun.wadl+xml":{"source":"iana","compressible":true,"extensions":["wadl"]},"application/vnd.sun.xml.calc":{"source":"apache","extensions":["sxc"]},"application/vnd.sun.xml.calc.template":{"source":"apache","extensions":["stc"]},"application/vnd.sun.xml.draw":{"source":"apache","extensions":["sxd"]},"application/vnd.sun.xml.draw.template":{"source":"apache","extensions":["std"]},"application/vnd.sun.xml.impress":{"source":"apache","extensions":["sxi"]},"application/vnd.sun.xml.impress.template":{"source":"apache","extensions":["sti"]},"application/vnd.sun.xml.math":{"source":"apache","extensions":["sxm"]},"application/vnd.sun.xml.writer":{"source":"apache","extensions":["sxw"]},"application/vnd.sun.xml.writer.global":{"source":"apache","extensions":["sxg"]},"application/vnd.sun.xml.writer.template":{"source":"apache","extensions":["stw"]},"application/vnd.sus-calendar":{"source":"iana","extensions":["sus","susp"]},"application/vnd.svd":{"source":"iana","extensions":["svd"]},"application/vnd.swiftview-ics":{"source":"iana"},"application/vnd.sycle+xml":{"source":"iana","compressible":true},"application/vnd.syft+json":{"source":"iana","compressible":true},"application/vnd.symbian.install":{"source":"apache","extensions":["sis","sisx"]},"application/vnd.syncml+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xsm"]},"application/vnd.syncml.dm+wbxml":{"source":"iana","charset":"UTF-8","extensions":["bdm"]},"application/vnd.syncml.dm+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xdm"]},"application/vnd.syncml.dm.notification":{"source":"iana"},"application/vnd.syncml.dmddf+wbxml":{"source":"iana"},"application/vnd.syncml.dmddf+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{"source":"iana"},"application/vnd.syncml.dmtnds+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.syncml.ds.notification":{"source":"iana"},"application/vnd.tableschema+json":{"source":"iana","compressible":true},"application/vnd.tao.intent-module-archive":{"source":"iana","extensions":["tao"]},"application/vnd.tcpdump.pcap":{"source":"iana","extensions":["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{"source":"iana","compressible":true},"application/vnd.tmd.mediaflex.api+xml":{"source":"iana","compressible":true},"application/vnd.tml":{"source":"iana"},"application/vnd.tmobile-livetv":{"source":"iana","extensions":["tmo"]},"application/vnd.tri.onesource":{"source":"iana"},"application/vnd.trid.tpt":{"source":"iana","extensions":["tpt"]},"application/vnd.triscape.mxs":{"source":"iana","extensions":["mxs"]},"application/vnd.trueapp":{"source":"iana","extensions":["tra"]},"application/vnd.truedoc":{"source":"iana"},"application/vnd.ubisoft.webplayer":{"source":"iana"},"application/vnd.ufdl":{"source":"iana","extensions":["ufd","ufdl"]},"application/vnd.uiq.theme":{"source":"iana","extensions":["utz"]},"application/vnd.umajin":{"source":"iana","extensions":["umj"]},"application/vnd.unity":{"source":"iana","extensions":["unityweb"]},"application/vnd.uoml+xml":{"source":"iana","compressible":true,"extensions":["uoml"]},"application/vnd.uplanet.alert":{"source":"iana"},"application/vnd.uplanet.alert-wbxml":{"source":"iana"},"application/vnd.uplanet.bearer-choice":{"source":"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{"source":"iana"},"application/vnd.uplanet.cacheop":{"source":"iana"},"application/vnd.uplanet.cacheop-wbxml":{"source":"iana"},"application/vnd.uplanet.channel":{"source":"iana"},"application/vnd.uplanet.channel-wbxml":{"source":"iana"},"application/vnd.uplanet.list":{"source":"iana"},"application/vnd.uplanet.list-wbxml":{"source":"iana"},"application/vnd.uplanet.listcmd":{"source":"iana"},"application/vnd.uplanet.listcmd-wbxml":{"source":"iana"},"application/vnd.uplanet.signal":{"source":"iana"},"application/vnd.uri-map":{"source":"iana"},"application/vnd.valve.source.material":{"source":"iana"},"application/vnd.vcx":{"source":"iana","extensions":["vcx"]},"application/vnd.vd-study":{"source":"iana"},"application/vnd.vectorworks":{"source":"iana"},"application/vnd.vel+json":{"source":"iana","compressible":true},"application/vnd.verimatrix.vcas":{"source":"iana"},"application/vnd.veritone.aion+json":{"source":"iana","compressible":true},"application/vnd.veryant.thin":{"source":"iana"},"application/vnd.ves.encrypted":{"source":"iana"},"application/vnd.vidsoft.vidconference":{"source":"iana"},"application/vnd.visio":{"source":"iana","extensions":["vsd","vst","vss","vsw"]},"application/vnd.visionary":{"source":"iana","extensions":["vis"]},"application/vnd.vividence.scriptfile":{"source":"iana"},"application/vnd.vsf":{"source":"iana","extensions":["vsf"]},"application/vnd.wap.sic":{"source":"iana"},"application/vnd.wap.slc":{"source":"iana"},"application/vnd.wap.wbxml":{"source":"iana","charset":"UTF-8","extensions":["wbxml"]},"application/vnd.wap.wmlc":{"source":"iana","extensions":["wmlc"]},"application/vnd.wap.wmlscriptc":{"source":"iana","extensions":["wmlsc"]},"application/vnd.webturbo":{"source":"iana","extensions":["wtb"]},"application/vnd.wfa.dpp":{"source":"iana"},"application/vnd.wfa.p2p":{"source":"iana"},"application/vnd.wfa.wsc":{"source":"iana"},"application/vnd.windows.devicepairing":{"source":"iana"},"application/vnd.wmc":{"source":"iana"},"application/vnd.wmf.bootstrap":{"source":"iana"},"application/vnd.wolfram.mathematica":{"source":"iana"},"application/vnd.wolfram.mathematica.package":{"source":"iana"},"application/vnd.wolfram.player":{"source":"iana","extensions":["nbp"]},"application/vnd.wordperfect":{"source":"iana","extensions":["wpd"]},"application/vnd.wqd":{"source":"iana","extensions":["wqd"]},"application/vnd.wrq-hp3000-labelled":{"source":"iana"},"application/vnd.wt.stf":{"source":"iana","extensions":["stf"]},"application/vnd.wv.csp+wbxml":{"source":"iana"},"application/vnd.wv.csp+xml":{"source":"iana","compressible":true},"application/vnd.wv.ssp+xml":{"source":"iana","compressible":true},"application/vnd.xacml+json":{"source":"iana","compressible":true},"application/vnd.xara":{"source":"iana","extensions":["xar"]},"application/vnd.xfdl":{"source":"iana","extensions":["xfdl"]},"application/vnd.xfdl.webform":{"source":"iana"},"application/vnd.xmi+xml":{"source":"iana","compressible":true},"application/vnd.xmpie.cpkg":{"source":"iana"},"application/vnd.xmpie.dpkg":{"source":"iana"},"application/vnd.xmpie.plan":{"source":"iana"},"application/vnd.xmpie.ppkg":{"source":"iana"},"application/vnd.xmpie.xlim":{"source":"iana"},"application/vnd.yamaha.hv-dic":{"source":"iana","extensions":["hvd"]},"application/vnd.yamaha.hv-script":{"source":"iana","extensions":["hvs"]},"application/vnd.yamaha.hv-voice":{"source":"iana","extensions":["hvp"]},"application/vnd.yamaha.openscoreformat":{"source":"iana","extensions":["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{"source":"iana","compressible":true,"extensions":["osfpvg"]},"application/vnd.yamaha.remote-setup":{"source":"iana"},"application/vnd.yamaha.smaf-audio":{"source":"iana","extensions":["saf"]},"application/vnd.yamaha.smaf-phrase":{"source":"iana","extensions":["spf"]},"application/vnd.yamaha.through-ngn":{"source":"iana"},"application/vnd.yamaha.tunnel-udpencap":{"source":"iana"},"application/vnd.yaoweme":{"source":"iana"},"application/vnd.yellowriver-custom-menu":{"source":"iana","extensions":["cmp"]},"application/vnd.youtube.yt":{"source":"iana"},"application/vnd.zul":{"source":"iana","extensions":["zir","zirz"]},"application/vnd.zzazz.deck+xml":{"source":"iana","compressible":true,"extensions":["zaz"]},"application/voicexml+xml":{"source":"iana","compressible":true,"extensions":["vxml"]},"application/voucher-cms+json":{"source":"iana","compressible":true},"application/vq-rtcpxr":{"source":"iana"},"application/wasm":{"source":"iana","compressible":true,"extensions":["wasm"]},"application/watcherinfo+xml":{"source":"iana","compressible":true,"extensions":["wif"]},"application/webpush-options+json":{"source":"iana","compressible":true},"application/whoispp-query":{"source":"iana"},"application/whoispp-response":{"source":"iana"},"application/widget":{"source":"iana","extensions":["wgt"]},"application/winhlp":{"source":"apache","extensions":["hlp"]},"application/wita":{"source":"iana"},"application/wordperfect5.1":{"source":"iana"},"application/wsdl+xml":{"source":"iana","compressible":true,"extensions":["wsdl"]},"application/wspolicy+xml":{"source":"iana","compressible":true,"extensions":["wspolicy"]},"application/x-7z-compressed":{"source":"apache","compressible":false,"extensions":["7z"]},"application/x-abiword":{"source":"apache","extensions":["abw"]},"application/x-ace-compressed":{"source":"apache","extensions":["ace"]},"application/x-amf":{"source":"apache"},"application/x-apple-diskimage":{"source":"apache","extensions":["dmg"]},"application/x-arj":{"compressible":false,"extensions":["arj"]},"application/x-authorware-bin":{"source":"apache","extensions":["aab","x32","u32","vox"]},"application/x-authorware-map":{"source":"apache","extensions":["aam"]},"application/x-authorware-seg":{"source":"apache","extensions":["aas"]},"application/x-bcpio":{"source":"apache","extensions":["bcpio"]},"application/x-bdoc":{"compressible":false,"extensions":["bdoc"]},"application/x-bittorrent":{"source":"apache","extensions":["torrent"]},"application/x-blorb":{"source":"apache","extensions":["blb","blorb"]},"application/x-bzip":{"source":"apache","compressible":false,"extensions":["bz"]},"application/x-bzip2":{"source":"apache","compressible":false,"extensions":["bz2","boz"]},"application/x-cbr":{"source":"apache","extensions":["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{"source":"apache","extensions":["vcd"]},"application/x-cfs-compressed":{"source":"apache","extensions":["cfs"]},"application/x-chat":{"source":"apache","extensions":["chat"]},"application/x-chess-pgn":{"source":"apache","extensions":["pgn"]},"application/x-chrome-extension":{"extensions":["crx"]},"application/x-cocoa":{"source":"nginx","extensions":["cco"]},"application/x-compress":{"source":"apache"},"application/x-conference":{"source":"apache","extensions":["nsc"]},"application/x-cpio":{"source":"apache","extensions":["cpio"]},"application/x-csh":{"source":"apache","extensions":["csh"]},"application/x-deb":{"compressible":false},"application/x-debian-package":{"source":"apache","extensions":["deb","udeb"]},"application/x-dgc-compressed":{"source":"apache","extensions":["dgc"]},"application/x-director":{"source":"apache","extensions":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{"source":"apache","extensions":["wad"]},"application/x-dtbncx+xml":{"source":"apache","compressible":true,"extensions":["ncx"]},"application/x-dtbook+xml":{"source":"apache","compressible":true,"extensions":["dtb"]},"application/x-dtbresource+xml":{"source":"apache","compressible":true,"extensions":["res"]},"application/x-dvi":{"source":"apache","compressible":false,"extensions":["dvi"]},"application/x-envoy":{"source":"apache","extensions":["evy"]},"application/x-eva":{"source":"apache","extensions":["eva"]},"application/x-font-bdf":{"source":"apache","extensions":["bdf"]},"application/x-font-dos":{"source":"apache"},"application/x-font-framemaker":{"source":"apache"},"application/x-font-ghostscript":{"source":"apache","extensions":["gsf"]},"application/x-font-libgrx":{"source":"apache"},"application/x-font-linux-psf":{"source":"apache","extensions":["psf"]},"application/x-font-pcf":{"source":"apache","extensions":["pcf"]},"application/x-font-snf":{"source":"apache","extensions":["snf"]},"application/x-font-speedo":{"source":"apache"},"application/x-font-sunos-news":{"source":"apache"},"application/x-font-type1":{"source":"apache","extensions":["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{"source":"apache"},"application/x-freearc":{"source":"apache","extensions":["arc"]},"application/x-futuresplash":{"source":"apache","extensions":["spl"]},"application/x-gca-compressed":{"source":"apache","extensions":["gca"]},"application/x-glulx":{"source":"apache","extensions":["ulx"]},"application/x-gnumeric":{"source":"apache","extensions":["gnumeric"]},"application/x-gramps-xml":{"source":"apache","extensions":["gramps"]},"application/x-gtar":{"source":"apache","extensions":["gtar"]},"application/x-gzip":{"source":"apache"},"application/x-hdf":{"source":"apache","extensions":["hdf"]},"application/x-httpd-php":{"compressible":true,"extensions":["php"]},"application/x-install-instructions":{"source":"apache","extensions":["install"]},"application/x-iso9660-image":{"source":"apache","extensions":["iso"]},"application/x-iwork-keynote-sffkey":{"extensions":["key"]},"application/x-iwork-numbers-sffnumbers":{"extensions":["numbers"]},"application/x-iwork-pages-sffpages":{"extensions":["pages"]},"application/x-java-archive-diff":{"source":"nginx","extensions":["jardiff"]},"application/x-java-jnlp-file":{"source":"apache","compressible":false,"extensions":["jnlp"]},"application/x-javascript":{"compressible":true},"application/x-keepass2":{"extensions":["kdbx"]},"application/x-latex":{"source":"apache","compressible":false,"extensions":["latex"]},"application/x-lua-bytecode":{"extensions":["luac"]},"application/x-lzh-compressed":{"source":"apache","extensions":["lzh","lha"]},"application/x-makeself":{"source":"nginx","extensions":["run"]},"application/x-mie":{"source":"apache","extensions":["mie"]},"application/x-mobipocket-ebook":{"source":"apache","extensions":["prc","mobi"]},"application/x-mpegurl":{"compressible":false},"application/x-ms-application":{"source":"apache","extensions":["application"]},"application/x-ms-shortcut":{"source":"apache","extensions":["lnk"]},"application/x-ms-wmd":{"source":"apache","extensions":["wmd"]},"application/x-ms-wmz":{"source":"apache","extensions":["wmz"]},"application/x-ms-xbap":{"source":"apache","extensions":["xbap"]},"application/x-msaccess":{"source":"apache","extensions":["mdb"]},"application/x-msbinder":{"source":"apache","extensions":["obd"]},"application/x-mscardfile":{"source":"apache","extensions":["crd"]},"application/x-msclip":{"source":"apache","extensions":["clp"]},"application/x-msdos-program":{"extensions":["exe"]},"application/x-msdownload":{"source":"apache","extensions":["exe","dll","com","bat","msi"]},"application/x-msmediaview":{"source":"apache","extensions":["mvb","m13","m14"]},"application/x-msmetafile":{"source":"apache","extensions":["wmf","wmz","emf","emz"]},"application/x-msmoney":{"source":"apache","extensions":["mny"]},"application/x-mspublisher":{"source":"apache","extensions":["pub"]},"application/x-msschedule":{"source":"apache","extensions":["scd"]},"application/x-msterminal":{"source":"apache","extensions":["trm"]},"application/x-mswrite":{"source":"apache","extensions":["wri"]},"application/x-netcdf":{"source":"apache","extensions":["nc","cdf"]},"application/x-ns-proxy-autoconfig":{"compressible":true,"extensions":["pac"]},"application/x-nzb":{"source":"apache","extensions":["nzb"]},"application/x-perl":{"source":"nginx","extensions":["pl","pm"]},"application/x-pilot":{"source":"nginx","extensions":["prc","pdb"]},"application/x-pkcs12":{"source":"apache","compressible":false,"extensions":["p12","pfx"]},"application/x-pkcs7-certificates":{"source":"apache","extensions":["p7b","spc"]},"application/x-pkcs7-certreqresp":{"source":"apache","extensions":["p7r"]},"application/x-pki-message":{"source":"iana"},"application/x-rar-compressed":{"source":"apache","compressible":false,"extensions":["rar"]},"application/x-redhat-package-manager":{"source":"nginx","extensions":["rpm"]},"application/x-research-info-systems":{"source":"apache","extensions":["ris"]},"application/x-sea":{"source":"nginx","extensions":["sea"]},"application/x-sh":{"source":"apache","compressible":true,"extensions":["sh"]},"application/x-shar":{"source":"apache","extensions":["shar"]},"application/x-shockwave-flash":{"source":"apache","compressible":false,"extensions":["swf"]},"application/x-silverlight-app":{"source":"apache","extensions":["xap"]},"application/x-sql":{"source":"apache","extensions":["sql"]},"application/x-stuffit":{"source":"apache","compressible":false,"extensions":["sit"]},"application/x-stuffitx":{"source":"apache","extensions":["sitx"]},"application/x-subrip":{"source":"apache","extensions":["srt"]},"application/x-sv4cpio":{"source":"apache","extensions":["sv4cpio"]},"application/x-sv4crc":{"source":"apache","extensions":["sv4crc"]},"application/x-t3vm-image":{"source":"apache","extensions":["t3"]},"application/x-tads":{"source":"apache","extensions":["gam"]},"application/x-tar":{"source":"apache","compressible":true,"extensions":["tar"]},"application/x-tcl":{"source":"apache","extensions":["tcl","tk"]},"application/x-tex":{"source":"apache","extensions":["tex"]},"application/x-tex-tfm":{"source":"apache","extensions":["tfm"]},"application/x-texinfo":{"source":"apache","extensions":["texinfo","texi"]},"application/x-tgif":{"source":"apache","extensions":["obj"]},"application/x-ustar":{"source":"apache","extensions":["ustar"]},"application/x-virtualbox-hdd":{"compressible":true,"extensions":["hdd"]},"application/x-virtualbox-ova":{"compressible":true,"extensions":["ova"]},"application/x-virtualbox-ovf":{"compressible":true,"extensions":["ovf"]},"application/x-virtualbox-vbox":{"compressible":true,"extensions":["vbox"]},"application/x-virtualbox-vbox-extpack":{"compressible":false,"extensions":["vbox-extpack"]},"application/x-virtualbox-vdi":{"compressible":true,"extensions":["vdi"]},"application/x-virtualbox-vhd":{"compressible":true,"extensions":["vhd"]},"application/x-virtualbox-vmdk":{"compressible":true,"extensions":["vmdk"]},"application/x-wais-source":{"source":"apache","extensions":["src"]},"application/x-web-app-manifest+json":{"compressible":true,"extensions":["webapp"]},"application/x-www-form-urlencoded":{"source":"iana","compressible":true},"application/x-x509-ca-cert":{"source":"iana","extensions":["der","crt","pem"]},"application/x-x509-ca-ra-cert":{"source":"iana"},"application/x-x509-next-ca-cert":{"source":"iana"},"application/x-xfig":{"source":"apache","extensions":["fig"]},"application/x-xliff+xml":{"source":"apache","compressible":true,"extensions":["xlf"]},"application/x-xpinstall":{"source":"apache","compressible":false,"extensions":["xpi"]},"application/x-xz":{"source":"apache","extensions":["xz"]},"application/x-zmachine":{"source":"apache","extensions":["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{"source":"iana"},"application/xacml+xml":{"source":"iana","compressible":true},"application/xaml+xml":{"source":"apache","compressible":true,"extensions":["xaml"]},"application/xcap-att+xml":{"source":"iana","compressible":true,"extensions":["xav"]},"application/xcap-caps+xml":{"source":"iana","compressible":true,"extensions":["xca"]},"application/xcap-diff+xml":{"source":"iana","compressible":true,"extensions":["xdf"]},"application/xcap-el+xml":{"source":"iana","compressible":true,"extensions":["xel"]},"application/xcap-error+xml":{"source":"iana","compressible":true},"application/xcap-ns+xml":{"source":"iana","compressible":true,"extensions":["xns"]},"application/xcon-conference-info+xml":{"source":"iana","compressible":true},"application/xcon-conference-info-diff+xml":{"source":"iana","compressible":true},"application/xenc+xml":{"source":"iana","compressible":true,"extensions":["xenc"]},"application/xhtml+xml":{"source":"iana","compressible":true,"extensions":["xhtml","xht"]},"application/xhtml-voice+xml":{"source":"apache","compressible":true},"application/xliff+xml":{"source":"iana","compressible":true,"extensions":["xlf"]},"application/xml":{"source":"iana","compressible":true,"extensions":["xml","xsl","xsd","rng"]},"application/xml-dtd":{"source":"iana","compressible":true,"extensions":["dtd"]},"application/xml-external-parsed-entity":{"source":"iana"},"application/xml-patch+xml":{"source":"iana","compressible":true},"application/xmpp+xml":{"source":"iana","compressible":true},"application/xop+xml":{"source":"iana","compressible":true,"extensions":["xop"]},"application/xproc+xml":{"source":"apache","compressible":true,"extensions":["xpl"]},"application/xslt+xml":{"source":"iana","compressible":true,"extensions":["xsl","xslt"]},"application/xspf+xml":{"source":"apache","compressible":true,"extensions":["xspf"]},"application/xv+xml":{"source":"iana","compressible":true,"extensions":["mxml","xhvml","xvml","xvm"]},"application/yang":{"source":"iana","extensions":["yang"]},"application/yang-data+json":{"source":"iana","compressible":true},"application/yang-data+xml":{"source":"iana","compressible":true},"application/yang-patch+json":{"source":"iana","compressible":true},"application/yang-patch+xml":{"source":"iana","compressible":true},"application/yin+xml":{"source":"iana","compressible":true,"extensions":["yin"]},"application/zip":{"source":"iana","compressible":false,"extensions":["zip"]},"application/zlib":{"source":"iana"},"application/zstd":{"source":"iana"},"audio/1d-interleaved-parityfec":{"source":"iana"},"audio/32kadpcm":{"source":"iana"},"audio/3gpp":{"source":"iana","compressible":false,"extensions":["3gpp"]},"audio/3gpp2":{"source":"iana"},"audio/aac":{"source":"iana"},"audio/ac3":{"source":"iana"},"audio/adpcm":{"source":"apache","extensions":["adp"]},"audio/amr":{"source":"iana","extensions":["amr"]},"audio/amr-wb":{"source":"iana"},"audio/amr-wb+":{"source":"iana"},"audio/aptx":{"source":"iana"},"audio/asc":{"source":"iana"},"audio/atrac-advanced-lossless":{"source":"iana"},"audio/atrac-x":{"source":"iana"},"audio/atrac3":{"source":"iana"},"audio/basic":{"source":"iana","compressible":false,"extensions":["au","snd"]},"audio/bv16":{"source":"iana"},"audio/bv32":{"source":"iana"},"audio/clearmode":{"source":"iana"},"audio/cn":{"source":"iana"},"audio/dat12":{"source":"iana"},"audio/dls":{"source":"iana"},"audio/dsr-es201108":{"source":"iana"},"audio/dsr-es202050":{"source":"iana"},"audio/dsr-es202211":{"source":"iana"},"audio/dsr-es202212":{"source":"iana"},"audio/dv":{"source":"iana"},"audio/dvi4":{"source":"iana"},"audio/eac3":{"source":"iana"},"audio/encaprtp":{"source":"iana"},"audio/evrc":{"source":"iana"},"audio/evrc-qcp":{"source":"iana"},"audio/evrc0":{"source":"iana"},"audio/evrc1":{"source":"iana"},"audio/evrcb":{"source":"iana"},"audio/evrcb0":{"source":"iana"},"audio/evrcb1":{"source":"iana"},"audio/evrcnw":{"source":"iana"},"audio/evrcnw0":{"source":"iana"},"audio/evrcnw1":{"source":"iana"},"audio/evrcwb":{"source":"iana"},"audio/evrcwb0":{"source":"iana"},"audio/evrcwb1":{"source":"iana"},"audio/evs":{"source":"iana"},"audio/flexfec":{"source":"iana"},"audio/fwdred":{"source":"iana"},"audio/g711-0":{"source":"iana"},"audio/g719":{"source":"iana"},"audio/g722":{"source":"iana"},"audio/g7221":{"source":"iana"},"audio/g723":{"source":"iana"},"audio/g726-16":{"source":"iana"},"audio/g726-24":{"source":"iana"},"audio/g726-32":{"source":"iana"},"audio/g726-40":{"source":"iana"},"audio/g728":{"source":"iana"},"audio/g729":{"source":"iana"},"audio/g7291":{"source":"iana"},"audio/g729d":{"source":"iana"},"audio/g729e":{"source":"iana"},"audio/gsm":{"source":"iana"},"audio/gsm-efr":{"source":"iana"},"audio/gsm-hr-08":{"source":"iana"},"audio/ilbc":{"source":"iana"},"audio/ip-mr_v2.5":{"source":"iana"},"audio/isac":{"source":"apache"},"audio/l16":{"source":"iana"},"audio/l20":{"source":"iana"},"audio/l24":{"source":"iana","compressible":false},"audio/l8":{"source":"iana"},"audio/lpc":{"source":"iana"},"audio/melp":{"source":"iana"},"audio/melp1200":{"source":"iana"},"audio/melp2400":{"source":"iana"},"audio/melp600":{"source":"iana"},"audio/mhas":{"source":"iana"},"audio/midi":{"source":"apache","extensions":["mid","midi","kar","rmi"]},"audio/mobile-xmf":{"source":"iana","extensions":["mxmf"]},"audio/mp3":{"compressible":false,"extensions":["mp3"]},"audio/mp4":{"source":"iana","compressible":false,"extensions":["m4a","mp4a"]},"audio/mp4a-latm":{"source":"iana"},"audio/mpa":{"source":"iana"},"audio/mpa-robust":{"source":"iana"},"audio/mpeg":{"source":"iana","compressible":false,"extensions":["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{"source":"iana"},"audio/musepack":{"source":"apache"},"audio/ogg":{"source":"iana","compressible":false,"extensions":["oga","ogg","spx","opus"]},"audio/opus":{"source":"iana"},"audio/parityfec":{"source":"iana"},"audio/pcma":{"source":"iana"},"audio/pcma-wb":{"source":"iana"},"audio/pcmu":{"source":"iana"},"audio/pcmu-wb":{"source":"iana"},"audio/prs.sid":{"source":"iana"},"audio/qcelp":{"source":"iana"},"audio/raptorfec":{"source":"iana"},"audio/red":{"source":"iana"},"audio/rtp-enc-aescm128":{"source":"iana"},"audio/rtp-midi":{"source":"iana"},"audio/rtploopback":{"source":"iana"},"audio/rtx":{"source":"iana"},"audio/s3m":{"source":"apache","extensions":["s3m"]},"audio/scip":{"source":"iana"},"audio/silk":{"source":"apache","extensions":["sil"]},"audio/smv":{"source":"iana"},"audio/smv-qcp":{"source":"iana"},"audio/smv0":{"source":"iana"},"audio/sofa":{"source":"iana"},"audio/sp-midi":{"source":"iana"},"audio/speex":{"source":"iana"},"audio/t140c":{"source":"iana"},"audio/t38":{"source":"iana"},"audio/telephone-event":{"source":"iana"},"audio/tetra_acelp":{"source":"iana"},"audio/tetra_acelp_bb":{"source":"iana"},"audio/tone":{"source":"iana"},"audio/tsvcis":{"source":"iana"},"audio/uemclip":{"source":"iana"},"audio/ulpfec":{"source":"iana"},"audio/usac":{"source":"iana"},"audio/vdvi":{"source":"iana"},"audio/vmr-wb":{"source":"iana"},"audio/vnd.3gpp.iufp":{"source":"iana"},"audio/vnd.4sb":{"source":"iana"},"audio/vnd.audiokoz":{"source":"iana"},"audio/vnd.celp":{"source":"iana"},"audio/vnd.cisco.nse":{"source":"iana"},"audio/vnd.cmles.radio-events":{"source":"iana"},"audio/vnd.cns.anp1":{"source":"iana"},"audio/vnd.cns.inf1":{"source":"iana"},"audio/vnd.dece.audio":{"source":"iana","extensions":["uva","uvva"]},"audio/vnd.digital-winds":{"source":"iana","extensions":["eol"]},"audio/vnd.dlna.adts":{"source":"iana"},"audio/vnd.dolby.heaac.1":{"source":"iana"},"audio/vnd.dolby.heaac.2":{"source":"iana"},"audio/vnd.dolby.mlp":{"source":"iana"},"audio/vnd.dolby.mps":{"source":"iana"},"audio/vnd.dolby.pl2":{"source":"iana"},"audio/vnd.dolby.pl2x":{"source":"iana"},"audio/vnd.dolby.pl2z":{"source":"iana"},"audio/vnd.dolby.pulse.1":{"source":"iana"},"audio/vnd.dra":{"source":"iana","extensions":["dra"]},"audio/vnd.dts":{"source":"iana","extensions":["dts"]},"audio/vnd.dts.hd":{"source":"iana","extensions":["dtshd"]},"audio/vnd.dts.uhd":{"source":"iana"},"audio/vnd.dvb.file":{"source":"iana"},"audio/vnd.everad.plj":{"source":"iana"},"audio/vnd.hns.audio":{"source":"iana"},"audio/vnd.lucent.voice":{"source":"iana","extensions":["lvp"]},"audio/vnd.ms-playready.media.pya":{"source":"iana","extensions":["pya"]},"audio/vnd.nokia.mobile-xmf":{"source":"iana"},"audio/vnd.nortel.vbk":{"source":"iana"},"audio/vnd.nuera.ecelp4800":{"source":"iana","extensions":["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{"source":"iana","extensions":["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{"source":"iana","extensions":["ecelp9600"]},"audio/vnd.octel.sbc":{"source":"iana"},"audio/vnd.presonus.multitrack":{"source":"iana"},"audio/vnd.qcelp":{"source":"iana"},"audio/vnd.rhetorex.32kadpcm":{"source":"iana"},"audio/vnd.rip":{"source":"iana","extensions":["rip"]},"audio/vnd.rn-realaudio":{"compressible":false},"audio/vnd.sealedmedia.softseal.mpeg":{"source":"iana"},"audio/vnd.vmx.cvsd":{"source":"iana"},"audio/vnd.wave":{"compressible":false},"audio/vorbis":{"source":"iana","compressible":false},"audio/vorbis-config":{"source":"iana"},"audio/wav":{"compressible":false,"extensions":["wav"]},"audio/wave":{"compressible":false,"extensions":["wav"]},"audio/webm":{"source":"apache","compressible":false,"extensions":["weba"]},"audio/x-aac":{"source":"apache","compressible":false,"extensions":["aac"]},"audio/x-aiff":{"source":"apache","extensions":["aif","aiff","aifc"]},"audio/x-caf":{"source":"apache","compressible":false,"extensions":["caf"]},"audio/x-flac":{"source":"apache","extensions":["flac"]},"audio/x-m4a":{"source":"nginx","extensions":["m4a"]},"audio/x-matroska":{"source":"apache","extensions":["mka"]},"audio/x-mpegurl":{"source":"apache","extensions":["m3u"]},"audio/x-ms-wax":{"source":"apache","extensions":["wax"]},"audio/x-ms-wma":{"source":"apache","extensions":["wma"]},"audio/x-pn-realaudio":{"source":"apache","extensions":["ram","ra"]},"audio/x-pn-realaudio-plugin":{"source":"apache","extensions":["rmp"]},"audio/x-realaudio":{"source":"nginx","extensions":["ra"]},"audio/x-tta":{"source":"apache"},"audio/x-wav":{"source":"apache","extensions":["wav"]},"audio/xm":{"source":"apache","extensions":["xm"]},"chemical/x-cdx":{"source":"apache","extensions":["cdx"]},"chemical/x-cif":{"source":"apache","extensions":["cif"]},"chemical/x-cmdf":{"source":"apache","extensions":["cmdf"]},"chemical/x-cml":{"source":"apache","extensions":["cml"]},"chemical/x-csml":{"source":"apache","extensions":["csml"]},"chemical/x-pdb":{"source":"apache"},"chemical/x-xyz":{"source":"apache","extensions":["xyz"]},"font/collection":{"source":"iana","extensions":["ttc"]},"font/otf":{"source":"iana","compressible":true,"extensions":["otf"]},"font/sfnt":{"source":"iana"},"font/ttf":{"source":"iana","compressible":true,"extensions":["ttf"]},"font/woff":{"source":"iana","extensions":["woff"]},"font/woff2":{"source":"iana","extensions":["woff2"]},"image/aces":{"source":"iana","extensions":["exr"]},"image/apng":{"compressible":false,"extensions":["apng"]},"image/avci":{"source":"iana","extensions":["avci"]},"image/avcs":{"source":"iana","extensions":["avcs"]},"image/avif":{"source":"iana","compressible":false,"extensions":["avif"]},"image/bmp":{"source":"iana","compressible":true,"extensions":["bmp"]},"image/cgm":{"source":"iana","extensions":["cgm"]},"image/dicom-rle":{"source":"iana","extensions":["drle"]},"image/emf":{"source":"iana","extensions":["emf"]},"image/fits":{"source":"iana","extensions":["fits"]},"image/g3fax":{"source":"iana","extensions":["g3"]},"image/gif":{"source":"iana","compressible":false,"extensions":["gif"]},"image/heic":{"source":"iana","extensions":["heic"]},"image/heic-sequence":{"source":"iana","extensions":["heics"]},"image/heif":{"source":"iana","extensions":["heif"]},"image/heif-sequence":{"source":"iana","extensions":["heifs"]},"image/hej2k":{"source":"iana","extensions":["hej2"]},"image/hsj2":{"source":"iana","extensions":["hsj2"]},"image/ief":{"source":"iana","extensions":["ief"]},"image/jls":{"source":"iana","extensions":["jls"]},"image/jp2":{"source":"iana","compressible":false,"extensions":["jp2","jpg2"]},"image/jpeg":{"source":"iana","compressible":false,"extensions":["jpeg","jpg","jpe"]},"image/jph":{"source":"iana","extensions":["jph"]},"image/jphc":{"source":"iana","extensions":["jhc"]},"image/jpm":{"source":"iana","compressible":false,"extensions":["jpm"]},"image/jpx":{"source":"iana","compressible":false,"extensions":["jpx","jpf"]},"image/jxr":{"source":"iana","extensions":["jxr"]},"image/jxra":{"source":"iana","extensions":["jxra"]},"image/jxrs":{"source":"iana","extensions":["jxrs"]},"image/jxs":{"source":"iana","extensions":["jxs"]},"image/jxsc":{"source":"iana","extensions":["jxsc"]},"image/jxsi":{"source":"iana","extensions":["jxsi"]},"image/jxss":{"source":"iana","extensions":["jxss"]},"image/ktx":{"source":"iana","extensions":["ktx"]},"image/ktx2":{"source":"iana","extensions":["ktx2"]},"image/naplps":{"source":"iana"},"image/pjpeg":{"compressible":false},"image/png":{"source":"iana","compressible":false,"extensions":["png"]},"image/prs.btif":{"source":"iana","extensions":["btif"]},"image/prs.pti":{"source":"iana","extensions":["pti"]},"image/pwg-raster":{"source":"iana"},"image/sgi":{"source":"apache","extensions":["sgi"]},"image/svg+xml":{"source":"iana","compressible":true,"extensions":["svg","svgz"]},"image/t38":{"source":"iana","extensions":["t38"]},"image/tiff":{"source":"iana","compressible":false,"extensions":["tif","tiff"]},"image/tiff-fx":{"source":"iana","extensions":["tfx"]},"image/vnd.adobe.photoshop":{"source":"iana","compressible":true,"extensions":["psd"]},"image/vnd.airzip.accelerator.azv":{"source":"iana","extensions":["azv"]},"image/vnd.cns.inf2":{"source":"iana"},"image/vnd.dece.graphic":{"source":"iana","extensions":["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{"source":"iana","extensions":["djvu","djv"]},"image/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"image/vnd.dwg":{"source":"iana","extensions":["dwg"]},"image/vnd.dxf":{"source":"iana","extensions":["dxf"]},"image/vnd.fastbidsheet":{"source":"iana","extensions":["fbs"]},"image/vnd.fpx":{"source":"iana","extensions":["fpx"]},"image/vnd.fst":{"source":"iana","extensions":["fst"]},"image/vnd.fujixerox.edmics-mmr":{"source":"iana","extensions":["mmr"]},"image/vnd.fujixerox.edmics-rlc":{"source":"iana","extensions":["rlc"]},"image/vnd.globalgraphics.pgb":{"source":"iana"},"image/vnd.microsoft.icon":{"source":"iana","compressible":true,"extensions":["ico"]},"image/vnd.mix":{"source":"iana"},"image/vnd.mozilla.apng":{"source":"iana"},"image/vnd.ms-dds":{"compressible":true,"extensions":["dds"]},"image/vnd.ms-modi":{"source":"iana","extensions":["mdi"]},"image/vnd.ms-photo":{"source":"apache","extensions":["wdp"]},"image/vnd.net-fpx":{"source":"iana","extensions":["npx"]},"image/vnd.pco.b16":{"source":"iana","extensions":["b16"]},"image/vnd.radiance":{"source":"iana"},"image/vnd.sealed.png":{"source":"iana"},"image/vnd.sealedmedia.softseal.gif":{"source":"iana"},"image/vnd.sealedmedia.softseal.jpg":{"source":"iana"},"image/vnd.svf":{"source":"iana"},"image/vnd.tencent.tap":{"source":"iana","extensions":["tap"]},"image/vnd.valve.source.texture":{"source":"iana","extensions":["vtf"]},"image/vnd.wap.wbmp":{"source":"iana","extensions":["wbmp"]},"image/vnd.xiff":{"source":"iana","extensions":["xif"]},"image/vnd.zbrush.pcx":{"source":"iana","extensions":["pcx"]},"image/webp":{"source":"apache","extensions":["webp"]},"image/wmf":{"source":"iana","extensions":["wmf"]},"image/x-3ds":{"source":"apache","extensions":["3ds"]},"image/x-cmu-raster":{"source":"apache","extensions":["ras"]},"image/x-cmx":{"source":"apache","extensions":["cmx"]},"image/x-freehand":{"source":"apache","extensions":["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{"source":"apache","compressible":true,"extensions":["ico"]},"image/x-jng":{"source":"nginx","extensions":["jng"]},"image/x-mrsid-image":{"source":"apache","extensions":["sid"]},"image/x-ms-bmp":{"source":"nginx","compressible":true,"extensions":["bmp"]},"image/x-pcx":{"source":"apache","extensions":["pcx"]},"image/x-pict":{"source":"apache","extensions":["pic","pct"]},"image/x-portable-anymap":{"source":"apache","extensions":["pnm"]},"image/x-portable-bitmap":{"source":"apache","extensions":["pbm"]},"image/x-portable-graymap":{"source":"apache","extensions":["pgm"]},"image/x-portable-pixmap":{"source":"apache","extensions":["ppm"]},"image/x-rgb":{"source":"apache","extensions":["rgb"]},"image/x-tga":{"source":"apache","extensions":["tga"]},"image/x-xbitmap":{"source":"apache","extensions":["xbm"]},"image/x-xcf":{"compressible":false},"image/x-xpixmap":{"source":"apache","extensions":["xpm"]},"image/x-xwindowdump":{"source":"apache","extensions":["xwd"]},"message/cpim":{"source":"iana"},"message/delivery-status":{"source":"iana"},"message/disposition-notification":{"source":"iana","extensions":["disposition-notification"]},"message/external-body":{"source":"iana"},"message/feedback-report":{"source":"iana"},"message/global":{"source":"iana","extensions":["u8msg"]},"message/global-delivery-status":{"source":"iana","extensions":["u8dsn"]},"message/global-disposition-notification":{"source":"iana","extensions":["u8mdn"]},"message/global-headers":{"source":"iana","extensions":["u8hdr"]},"message/http":{"source":"iana","compressible":false},"message/imdn+xml":{"source":"iana","compressible":true},"message/news":{"source":"iana"},"message/partial":{"source":"iana","compressible":false},"message/rfc822":{"source":"iana","compressible":true,"extensions":["eml","mime"]},"message/s-http":{"source":"iana"},"message/sip":{"source":"iana"},"message/sipfrag":{"source":"iana"},"message/tracking-status":{"source":"iana"},"message/vnd.si.simp":{"source":"iana"},"message/vnd.wfa.wsc":{"source":"iana","extensions":["wsc"]},"model/3mf":{"source":"iana","extensions":["3mf"]},"model/e57":{"source":"iana"},"model/gltf+json":{"source":"iana","compressible":true,"extensions":["gltf"]},"model/gltf-binary":{"source":"iana","compressible":true,"extensions":["glb"]},"model/iges":{"source":"iana","compressible":false,"extensions":["igs","iges"]},"model/mesh":{"source":"iana","compressible":false,"extensions":["msh","mesh","silo"]},"model/mtl":{"source":"iana","extensions":["mtl"]},"model/obj":{"source":"iana","extensions":["obj"]},"model/step":{"source":"iana"},"model/step+xml":{"source":"iana","compressible":true,"extensions":["stpx"]},"model/step+zip":{"source":"iana","compressible":false,"extensions":["stpz"]},"model/step-xml+zip":{"source":"iana","compressible":false,"extensions":["stpxz"]},"model/stl":{"source":"iana","extensions":["stl"]},"model/vnd.collada+xml":{"source":"iana","compressible":true,"extensions":["dae"]},"model/vnd.dwf":{"source":"iana","extensions":["dwf"]},"model/vnd.flatland.3dml":{"source":"iana"},"model/vnd.gdl":{"source":"iana","extensions":["gdl"]},"model/vnd.gs-gdl":{"source":"apache"},"model/vnd.gs.gdl":{"source":"iana"},"model/vnd.gtw":{"source":"iana","extensions":["gtw"]},"model/vnd.moml+xml":{"source":"iana","compressible":true},"model/vnd.mts":{"source":"iana","extensions":["mts"]},"model/vnd.opengex":{"source":"iana","extensions":["ogex"]},"model/vnd.parasolid.transmit.binary":{"source":"iana","extensions":["x_b"]},"model/vnd.parasolid.transmit.text":{"source":"iana","extensions":["x_t"]},"model/vnd.pytha.pyox":{"source":"iana"},"model/vnd.rosette.annotated-data-model":{"source":"iana"},"model/vnd.sap.vds":{"source":"iana","extensions":["vds"]},"model/vnd.usdz+zip":{"source":"iana","compressible":false,"extensions":["usdz"]},"model/vnd.valve.source.compiled-map":{"source":"iana","extensions":["bsp"]},"model/vnd.vtu":{"source":"iana","extensions":["vtu"]},"model/vrml":{"source":"iana","compressible":false,"extensions":["wrl","vrml"]},"model/x3d+binary":{"source":"apache","compressible":false,"extensions":["x3db","x3dbz"]},"model/x3d+fastinfoset":{"source":"iana","extensions":["x3db"]},"model/x3d+vrml":{"source":"apache","compressible":false,"extensions":["x3dv","x3dvz"]},"model/x3d+xml":{"source":"iana","compressible":true,"extensions":["x3d","x3dz"]},"model/x3d-vrml":{"source":"iana","extensions":["x3dv"]},"multipart/alternative":{"source":"iana","compressible":false},"multipart/appledouble":{"source":"iana"},"multipart/byteranges":{"source":"iana"},"multipart/digest":{"source":"iana"},"multipart/encrypted":{"source":"iana","compressible":false},"multipart/form-data":{"source":"iana","compressible":false},"multipart/header-set":{"source":"iana"},"multipart/mixed":{"source":"iana"},"multipart/multilingual":{"source":"iana"},"multipart/parallel":{"source":"iana"},"multipart/related":{"source":"iana","compressible":false},"multipart/report":{"source":"iana"},"multipart/signed":{"source":"iana","compressible":false},"multipart/vnd.bint.med-plus":{"source":"iana"},"multipart/voice-message":{"source":"iana"},"multipart/x-mixed-replace":{"source":"iana"},"text/1d-interleaved-parityfec":{"source":"iana"},"text/cache-manifest":{"source":"iana","compressible":true,"extensions":["appcache","manifest"]},"text/calendar":{"source":"iana","extensions":["ics","ifb"]},"text/calender":{"compressible":true},"text/cmd":{"compressible":true},"text/coffeescript":{"extensions":["coffee","litcoffee"]},"text/cql":{"source":"iana"},"text/cql-expression":{"source":"iana"},"text/cql-identifier":{"source":"iana"},"text/css":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["css"]},"text/csv":{"source":"iana","compressible":true,"extensions":["csv"]},"text/csv-schema":{"source":"iana"},"text/directory":{"source":"iana"},"text/dns":{"source":"iana"},"text/ecmascript":{"source":"iana"},"text/encaprtp":{"source":"iana"},"text/enriched":{"source":"iana"},"text/fhirpath":{"source":"iana"},"text/flexfec":{"source":"iana"},"text/fwdred":{"source":"iana"},"text/gff3":{"source":"iana"},"text/grammar-ref-list":{"source":"iana"},"text/html":{"source":"iana","compressible":true,"extensions":["html","htm","shtml"]},"text/jade":{"extensions":["jade"]},"text/javascript":{"source":"iana","compressible":true},"text/jcr-cnd":{"source":"iana"},"text/jsx":{"compressible":true,"extensions":["jsx"]},"text/less":{"compressible":true,"extensions":["less"]},"text/markdown":{"source":"iana","compressible":true,"extensions":["markdown","md"]},"text/mathml":{"source":"nginx","extensions":["mml"]},"text/mdx":{"compressible":true,"extensions":["mdx"]},"text/mizar":{"source":"iana"},"text/n3":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["n3"]},"text/parameters":{"source":"iana","charset":"UTF-8"},"text/parityfec":{"source":"iana"},"text/plain":{"source":"iana","compressible":true,"extensions":["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{"source":"iana","charset":"UTF-8"},"text/prs.fallenstein.rst":{"source":"iana"},"text/prs.lines.tag":{"source":"iana","extensions":["dsc"]},"text/prs.prop.logic":{"source":"iana"},"text/raptorfec":{"source":"iana"},"text/red":{"source":"iana"},"text/rfc822-headers":{"source":"iana"},"text/richtext":{"source":"iana","compressible":true,"extensions":["rtx"]},"text/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"text/rtp-enc-aescm128":{"source":"iana"},"text/rtploopback":{"source":"iana"},"text/rtx":{"source":"iana"},"text/sgml":{"source":"iana","extensions":["sgml","sgm"]},"text/shaclc":{"source":"iana"},"text/shex":{"source":"iana","extensions":["shex"]},"text/slim":{"extensions":["slim","slm"]},"text/spdx":{"source":"iana","extensions":["spdx"]},"text/strings":{"source":"iana"},"text/stylus":{"extensions":["stylus","styl"]},"text/t140":{"source":"iana"},"text/tab-separated-values":{"source":"iana","compressible":true,"extensions":["tsv"]},"text/troff":{"source":"iana","extensions":["t","tr","roff","man","me","ms"]},"text/turtle":{"source":"iana","charset":"UTF-8","extensions":["ttl"]},"text/ulpfec":{"source":"iana"},"text/uri-list":{"source":"iana","compressible":true,"extensions":["uri","uris","urls"]},"text/vcard":{"source":"iana","compressible":true,"extensions":["vcard"]},"text/vnd.a":{"source":"iana"},"text/vnd.abc":{"source":"iana"},"text/vnd.ascii-art":{"source":"iana"},"text/vnd.curl":{"source":"iana","extensions":["curl"]},"text/vnd.curl.dcurl":{"source":"apache","extensions":["dcurl"]},"text/vnd.curl.mcurl":{"source":"apache","extensions":["mcurl"]},"text/vnd.curl.scurl":{"source":"apache","extensions":["scurl"]},"text/vnd.debian.copyright":{"source":"iana","charset":"UTF-8"},"text/vnd.dmclientscript":{"source":"iana"},"text/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"text/vnd.esmertec.theme-descriptor":{"source":"iana","charset":"UTF-8"},"text/vnd.familysearch.gedcom":{"source":"iana","extensions":["ged"]},"text/vnd.ficlab.flt":{"source":"iana"},"text/vnd.fly":{"source":"iana","extensions":["fly"]},"text/vnd.fmi.flexstor":{"source":"iana","extensions":["flx"]},"text/vnd.gml":{"source":"iana"},"text/vnd.graphviz":{"source":"iana","extensions":["gv"]},"text/vnd.hans":{"source":"iana"},"text/vnd.hgl":{"source":"iana"},"text/vnd.in3d.3dml":{"source":"iana","extensions":["3dml"]},"text/vnd.in3d.spot":{"source":"iana","extensions":["spot"]},"text/vnd.iptc.newsml":{"source":"iana"},"text/vnd.iptc.nitf":{"source":"iana"},"text/vnd.latex-z":{"source":"iana"},"text/vnd.motorola.reflex":{"source":"iana"},"text/vnd.ms-mediapackage":{"source":"iana"},"text/vnd.net2phone.commcenter.command":{"source":"iana"},"text/vnd.radisys.msml-basic-layout":{"source":"iana"},"text/vnd.senx.warpscript":{"source":"iana"},"text/vnd.si.uricatalogue":{"source":"iana"},"text/vnd.sosi":{"source":"iana"},"text/vnd.sun.j2me.app-descriptor":{"source":"iana","charset":"UTF-8","extensions":["jad"]},"text/vnd.trolltech.linguist":{"source":"iana","charset":"UTF-8"},"text/vnd.wap.si":{"source":"iana"},"text/vnd.wap.sl":{"source":"iana"},"text/vnd.wap.wml":{"source":"iana","extensions":["wml"]},"text/vnd.wap.wmlscript":{"source":"iana","extensions":["wmls"]},"text/vtt":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["vtt"]},"text/x-asm":{"source":"apache","extensions":["s","asm"]},"text/x-c":{"source":"apache","extensions":["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{"source":"nginx","extensions":["htc"]},"text/x-fortran":{"source":"apache","extensions":["f","for","f77","f90"]},"text/x-gwt-rpc":{"compressible":true},"text/x-handlebars-template":{"extensions":["hbs"]},"text/x-java-source":{"source":"apache","extensions":["java"]},"text/x-jquery-tmpl":{"compressible":true},"text/x-lua":{"extensions":["lua"]},"text/x-markdown":{"compressible":true,"extensions":["mkd"]},"text/x-nfo":{"source":"apache","extensions":["nfo"]},"text/x-opml":{"source":"apache","extensions":["opml"]},"text/x-org":{"compressible":true,"extensions":["org"]},"text/x-pascal":{"source":"apache","extensions":["p","pas"]},"text/x-processing":{"compressible":true,"extensions":["pde"]},"text/x-sass":{"extensions":["sass"]},"text/x-scss":{"extensions":["scss"]},"text/x-setext":{"source":"apache","extensions":["etx"]},"text/x-sfv":{"source":"apache","extensions":["sfv"]},"text/x-suse-ymp":{"compressible":true,"extensions":["ymp"]},"text/x-uuencode":{"source":"apache","extensions":["uu"]},"text/x-vcalendar":{"source":"apache","extensions":["vcs"]},"text/x-vcard":{"source":"apache","extensions":["vcf"]},"text/xml":{"source":"iana","compressible":true,"extensions":["xml"]},"text/xml-external-parsed-entity":{"source":"iana"},"text/yaml":{"compressible":true,"extensions":["yaml","yml"]},"video/1d-interleaved-parityfec":{"source":"iana"},"video/3gpp":{"source":"iana","extensions":["3gp","3gpp"]},"video/3gpp-tt":{"source":"iana"},"video/3gpp2":{"source":"iana","extensions":["3g2"]},"video/av1":{"source":"iana"},"video/bmpeg":{"source":"iana"},"video/bt656":{"source":"iana"},"video/celb":{"source":"iana"},"video/dv":{"source":"iana"},"video/encaprtp":{"source":"iana"},"video/ffv1":{"source":"iana"},"video/flexfec":{"source":"iana"},"video/h261":{"source":"iana","extensions":["h261"]},"video/h263":{"source":"iana","extensions":["h263"]},"video/h263-1998":{"source":"iana"},"video/h263-2000":{"source":"iana"},"video/h264":{"source":"iana","extensions":["h264"]},"video/h264-rcdo":{"source":"iana"},"video/h264-svc":{"source":"iana"},"video/h265":{"source":"iana"},"video/iso.segment":{"source":"iana","extensions":["m4s"]},"video/jpeg":{"source":"iana","extensions":["jpgv"]},"video/jpeg2000":{"source":"iana"},"video/jpm":{"source":"apache","extensions":["jpm","jpgm"]},"video/jxsv":{"source":"iana"},"video/mj2":{"source":"iana","extensions":["mj2","mjp2"]},"video/mp1s":{"source":"iana"},"video/mp2p":{"source":"iana"},"video/mp2t":{"source":"iana","extensions":["ts"]},"video/mp4":{"source":"iana","compressible":false,"extensions":["mp4","mp4v","mpg4"]},"video/mp4v-es":{"source":"iana"},"video/mpeg":{"source":"iana","compressible":false,"extensions":["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{"source":"iana"},"video/mpv":{"source":"iana"},"video/nv":{"source":"iana"},"video/ogg":{"source":"iana","compressible":false,"extensions":["ogv"]},"video/parityfec":{"source":"iana"},"video/pointer":{"source":"iana"},"video/quicktime":{"source":"iana","compressible":false,"extensions":["qt","mov"]},"video/raptorfec":{"source":"iana"},"video/raw":{"source":"iana"},"video/rtp-enc-aescm128":{"source":"iana"},"video/rtploopback":{"source":"iana"},"video/rtx":{"source":"iana"},"video/scip":{"source":"iana"},"video/smpte291":{"source":"iana"},"video/smpte292m":{"source":"iana"},"video/ulpfec":{"source":"iana"},"video/vc1":{"source":"iana"},"video/vc2":{"source":"iana"},"video/vnd.cctv":{"source":"iana"},"video/vnd.dece.hd":{"source":"iana","extensions":["uvh","uvvh"]},"video/vnd.dece.mobile":{"source":"iana","extensions":["uvm","uvvm"]},"video/vnd.dece.mp4":{"source":"iana"},"video/vnd.dece.pd":{"source":"iana","extensions":["uvp","uvvp"]},"video/vnd.dece.sd":{"source":"iana","extensions":["uvs","uvvs"]},"video/vnd.dece.video":{"source":"iana","extensions":["uvv","uvvv"]},"video/vnd.directv.mpeg":{"source":"iana"},"video/vnd.directv.mpeg-tts":{"source":"iana"},"video/vnd.dlna.mpeg-tts":{"source":"iana"},"video/vnd.dvb.file":{"source":"iana","extensions":["dvb"]},"video/vnd.fvt":{"source":"iana","extensions":["fvt"]},"video/vnd.hns.video":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.ttsavc":{"source":"iana"},"video/vnd.iptvforum.ttsmpeg2":{"source":"iana"},"video/vnd.motorola.video":{"source":"iana"},"video/vnd.motorola.videop":{"source":"iana"},"video/vnd.mpegurl":{"source":"iana","extensions":["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{"source":"iana","extensions":["pyv"]},"video/vnd.nokia.interleaved-multimedia":{"source":"iana"},"video/vnd.nokia.mp4vr":{"source":"iana"},"video/vnd.nokia.videovoip":{"source":"iana"},"video/vnd.objectvideo":{"source":"iana"},"video/vnd.radgamettools.bink":{"source":"iana"},"video/vnd.radgamettools.smacker":{"source":"iana"},"video/vnd.sealed.mpeg1":{"source":"iana"},"video/vnd.sealed.mpeg4":{"source":"iana"},"video/vnd.sealed.swf":{"source":"iana"},"video/vnd.sealedmedia.softseal.mov":{"source":"iana"},"video/vnd.uvvu.mp4":{"source":"iana","extensions":["uvu","uvvu"]},"video/vnd.vivo":{"source":"iana","extensions":["viv"]},"video/vnd.youtube.yt":{"source":"iana"},"video/vp8":{"source":"iana"},"video/vp9":{"source":"iana"},"video/webm":{"source":"apache","compressible":false,"extensions":["webm"]},"video/x-f4v":{"source":"apache","extensions":["f4v"]},"video/x-fli":{"source":"apache","extensions":["fli"]},"video/x-flv":{"source":"apache","compressible":false,"extensions":["flv"]},"video/x-m4v":{"source":"apache","extensions":["m4v"]},"video/x-matroska":{"source":"apache","compressible":false,"extensions":["mkv","mk3d","mks"]},"video/x-mng":{"source":"apache","extensions":["mng"]},"video/x-ms-asf":{"source":"apache","extensions":["asf","asx"]},"video/x-ms-vob":{"source":"apache","extensions":["vob"]},"video/x-ms-wm":{"source":"apache","extensions":["wm"]},"video/x-ms-wmv":{"source":"apache","compressible":false,"extensions":["wmv"]},"video/x-ms-wmx":{"source":"apache","extensions":["wmx"]},"video/x-ms-wvx":{"source":"apache","extensions":["wvx"]},"video/x-msvideo":{"source":"apache","extensions":["avi"]},"video/x-sgi-movie":{"source":"apache","extensions":["movie"]},"video/x-smv":{"source":"apache","extensions":["smv"]},"x-conference/x-cooltalk":{"source":"apache","extensions":["ice"]},"x-shader/x-fragment":{"compressible":true},"x-shader/x-vertex":{"compressible":true}}'); - -/***/ }), - -/***/ 2020: -/***/ ((module) => { - -module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]]'); - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __nccwpck_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/compat get default export */ -/******/ (() => { -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __nccwpck_require__.n = (module) => { -/******/ var getter = module && module.__esModule ? -/******/ () => (module['default']) : -/******/ () => (module); -/******/ __nccwpck_require__.d(getter, { a: getter }); -/******/ return getter; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __nccwpck_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __nccwpck_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __nccwpck_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; -// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. -(() => { - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - "K": () => (/* binding */ run) -}); - -// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var core = __nccwpck_require__(2186); -// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js -var github = __nccwpck_require__(5438); -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/bind.js - - -function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; +exports.RunLogPatch = RunLogPatch; +class RunLog extends RunLogPatch { + constructor(fields) { + super(fields); + Object.defineProperty(this, "state", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.state = fields.state; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = (0, index_js_1.applyPatch)(this.state, other.ops); + return new RunLog({ ops, state: states[states.length - 1].newDocument }); + } } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/utils.js - - - - -// utils is a library of generic helper functions non-specific to axios - -const {toString: utils_toString} = Object.prototype; -const {getPrototypeOf} = Object; - -const kindOf = (cache => thing => { - const str = utils_toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); -})(Object.create(null)); - -const kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type +exports.RunLog = RunLog; +/** + * Class that extends the `BaseTracer` class from the + * `langchain.callbacks.tracers.base` module. It represents a callback + * handler that logs the execution of runs and emits `RunLog` instances to a + * `RunLogStream`. + */ +class LogStreamCallbackHandler extends tracer_js_1.BaseTracer { + constructor(fields) { + super(fields); + Object.defineProperty(this, "autoClose", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "indexMap", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "log_stream_tracer" + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = stream_js_1.IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) { + // This is a legacy method only called once for an entire run tree + // and is therefore not useful here + } + _includeRun(run) { + if (run.parent_run_id === undefined) { + return false; + } + const runTags = run.tags ?? []; + let include = this.includeNames === undefined && + this.includeTags === undefined && + this.includeTypes === undefined; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(run.run_type); + } + if (this.includeTags !== undefined) { + include = + include || + runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(run.run_type); + } + if (this.excludeTags !== undefined) { + include = + include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; + } + async onRunCreate(run) { + if (run.parent_run_id === undefined) { + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "replace", + path: "", + value: { + id: run.id, + streamed_output: [], + final_output: undefined, + logs: [], + }, + }, + ], + })); + } + if (!this._includeRun(run)) { + return; + } + this.indexMap[run.id] = Math.max(...Object.values(this.indexMap), -1) + 1; + const logEntry = { + id: run.id, + name: run.name, + type: run.run_type, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + start_time: new Date(run.start_time).toISOString(), + streamed_output_str: [], + final_output: undefined, + end_time: undefined, + }; + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${this.indexMap[run.id]}`, + value: logEntry, + }, + ], + })); + } + async onRunUpdate(run) { + try { + const index = this.indexMap[run.id]; + if (index === undefined) { + return; + } + const ops = [ + { + op: "add", + path: `/logs/${index}/final_output`, + value: run.outputs, + }, + ]; + if (run.end_time !== undefined) { + ops.push({ + op: "add", + path: `/logs/${index}/end_time`, + value: new Date(run.end_time).toISOString(), + }); + } + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } + finally { + if (run.parent_run_id === undefined) { + const patch = new RunLogPatch({ + ops: [ + { + op: "replace", + path: "/final_output", + value: run.outputs, + }, + ], + }); + await this.writer.write(patch); + if (this.autoClose) { + await this.writer.close(); + } + } + } + } + async onLLMNewToken(run, token) { + const index = this.indexMap[run.id]; + if (index === undefined) { + return; + } + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${index}/streamed_output_str/-`, + value: token, + }, + ], + }); + await this.writer.write(patch); + } } +exports.LogStreamCallbackHandler = LogStreamCallbackHandler; -const typeOfTest = type => thing => typeof thing === type; - -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * - * @returns {boolean} True if value is an Array, otherwise false - */ -const {isArray} = Array; - -/** - * Determine if a value is undefined - * - * @param {*} val The value to test - * - * @returns {boolean} True if the value is undefined, otherwise false - */ -const isUndefined = typeOfTest('undefined'); -/** - * Determine if a value is a Buffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); -} +/***/ }), -/** - * Determine if a value is an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -const isArrayBuffer = kindOfTest('ArrayBuffer'); +/***/ 4107: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - let result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); - } - return result; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseTracer = void 0; +const base_js_1 = __nccwpck_require__(7656); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; } - -/** - * Determine if a value is a String - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a String, otherwise false - */ -const isString = typeOfTest('string'); - -/** - * Determine if a value is a Function - * - * @param {*} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -const isFunction = typeOfTest('function'); - -/** - * Determine if a value is a Number - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Number, otherwise false - */ -const isNumber = typeOfTest('number'); - -/** - * Determine if a value is an Object - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an Object, otherwise false - */ -const isObject = (thing) => thing !== null && typeof thing === 'object'; - -/** - * Determine if a value is a Boolean - * - * @param {*} thing The value to test - * @returns {boolean} True if value is a Boolean, otherwise false - */ -const isBoolean = thing => thing === true || thing === false; - -/** - * Determine if a value is a plain Object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a plain Object, otherwise false - */ -const isPlainObject = (val) => { - if (kindOf(val) !== 'object') { - return false; - } - - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); +class BaseTracer extends base_js_1.BaseCallbackHandler { + constructor(_fields) { + super(...arguments); + Object.defineProperty(this, "runMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + } + copy() { + return this; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + async _startTrace(run) { + if (run.parent_run_id !== undefined) { + const parentRun = this.runMap.get(run.parent_run_id); + if (parentRun) { + this._addChildRun(parentRun, run); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } + } + this.runMap.set(run.id, run); + await this.onRunCreate?.(run); + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); + if (parentRun) { + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } + else { + await this.persistRun(run); + } + this.runMap.delete(run.id); + await this.onRunUpdate?.(run); + } + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); + // If a run has no parent then execution order is 1 + if (!parentRun) { + return 1; + } + return parentRun.child_execution_order + 1; + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { prompts }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onLLMStart?.(run); + return run; + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; + } + async handleLLMError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onLLMError?.(run); + await this._endTrace(run); + return run; + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.runMap.get(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.runMap.get(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool.id[tool.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onToolStart?.(run); + return run; + } + async handleToolEnd(output, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; + } + async handleToolError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onToolError?.(run); + await this._endTrace(run); + return run; + } + async handleAgentAction(action, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: new Date().toISOString(), + kwargs: { action }, + }); + await this.onAgentAction?.(run); + } + async handleAgentEnd(action, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "agent_end", + time: new Date().toISOString(), + kwargs: { action }, + }); + await this.onAgentEnd?.(run); + } + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + await this._startTrace(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; + } + async handleRetrieverError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.error = error.message; + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; + } + async handleText(text, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "text", + time: new Date().toISOString(), + kwargs: { text }, + }); + await this.onText?.(run); + } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + } + run.events.push({ + name: "new_token", + time: new Date().toISOString(), + kwargs: { token, idx, chunk: fields?.chunk }, + }); + await this.onLLMNewToken?.(run, token); + return run; + } } +exports.BaseTracer = BaseTracer; -/** - * Determine if a value is a Date - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Date, otherwise false - */ -const isDate = kindOfTest('Date'); - -/** - * Determine if a value is a File - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ -const isFile = kindOfTest('File'); -/** - * Determine if a value is a Blob - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Blob, otherwise false - */ -const isBlob = kindOfTest('Blob'); +/***/ }), -/** - * Determine if a value is a FileList - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ -const isFileList = kindOfTest('FileList'); +/***/ 521: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Determine if a value is a Stream - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Stream, otherwise false - */ -const isStream = (val) => isObject(val) && isFunction(val.pipe); -/** - * Determine if a value is a FormData - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an FormData, otherwise false - */ -const isFormData = (thing) => { - let kind; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || ( - isFunction(thing.append) && ( - (kind = kindOf(thing)) === 'formdata' || - // detect form-data instance - (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]') - ) - ) - ) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LangChainTracer = void 0; +const langsmith_1 = __nccwpck_require__(5907); +const env_js_1 = __nccwpck_require__(1548); +const tracer_js_1 = __nccwpck_require__(4107); +class LangChainTracer extends tracer_js_1.BaseTracer { + constructor(fields = {}) { + super(fields); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" + }); + Object.defineProperty(this, "projectName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const { exampleId, projectName, client } = fields; + this.projectName = + projectName ?? + (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_PROJECT") ?? + (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_SESSION"); + this.exampleId = exampleId; + this.client = client ?? new langsmith_1.Client({}); + } + async _convertToCreate(run, example_id = undefined) { + return { + ...run, + extra: { + ...run.extra, + runtime: await (0, env_js_1.getRuntimeEnvironment)(), + }, + child_runs: undefined, + session_name: this.projectName, + reference_example_id: run.parent_run_id ? undefined : example_id, + }; + } + async persistRun(_run) { } + async _persistRunSingle(run) { + const persistedRun = await this._convertToCreate(run, this.exampleId); + await this.client.createRun(persistedRun); + } + async _updateRunSingle(run) { + const runUpdate = { + end_time: run.end_time, + error: run.error, + outputs: run.outputs, + events: run.events, + inputs: run.inputs, + }; + await this.client.updateRun(run.id, runUpdate); + } + async onRetrieverStart(run) { + await this._persistRunSingle(run); + } + async onRetrieverEnd(run) { + await this._updateRunSingle(run); + } + async onRetrieverError(run) { + await this._updateRunSingle(run); + } + async onLLMStart(run) { + await this._persistRunSingle(run); + } + async onLLMEnd(run) { + await this._updateRunSingle(run); + } + async onLLMError(run) { + await this._updateRunSingle(run); + } + async onChainStart(run) { + await this._persistRunSingle(run); + } + async onChainEnd(run) { + await this._updateRunSingle(run); + } + async onChainError(run) { + await this._updateRunSingle(run); + } + async onToolStart(run) { + await this._persistRunSingle(run); + } + async onToolEnd(run) { + await this._updateRunSingle(run); + } + async onToolError(run) { + await this._updateRunSingle(run); + } } +exports.LangChainTracer = LangChainTracer; -/** - * Determine if a value is a URLSearchParams object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -const isURLSearchParams = kindOfTest('URLSearchParams'); - -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * - * @returns {String} The String freed of excess whitespace - */ -const trim = (str) => str.trim ? - str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - * - * @param {Boolean} [allOwnKeys = false] - * @returns {any} - */ -function forEach(obj, fn, {allOwnKeys = false} = {}) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } +/***/ }), - let i; - let l; +/***/ 9159: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } - if (isArray(obj)) { - // Iterate over array values - for (i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LangChainTracerV1 = void 0; +const base_js_1 = __nccwpck_require__(4235); +const env_js_1 = __nccwpck_require__(1548); +const tracer_js_1 = __nccwpck_require__(4107); +class LangChainTracerV1 extends tracer_js_1.BaseTracer { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" + }); + Object.defineProperty(this, "endpoint", { + enumerable: true, + configurable: true, + writable: true, + value: (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_ENDPOINT") || "http://localhost:1984" + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: { + "Content-Type": "application/json", + } + }); + Object.defineProperty(this, "session", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + const apiKey = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_API_KEY"); + if (apiKey) { + this.headers["x-api-key"] = apiKey; + } } - } else { - // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); + async newSession(sessionName) { + const sessionCreate = { + start_time: Date.now(), + name: sessionName, + }; + const session = await this.persistSession(sessionCreate); + this.session = session; + return session; } - } -} - -function findKey(obj, key) { - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; + async loadSession(sessionName) { + const endpoint = `${this.endpoint}/sessions?name=${sessionName}`; + return this._handleSessionResponse(endpoint); + } + async loadDefaultSession() { + const endpoint = `${this.endpoint}/sessions?name=default`; + return this._handleSessionResponse(endpoint); + } + async convertV2RunToRun(run) { + const session = this.session ?? (await this.loadDefaultSession()); + const serialized = run.serialized; + let runResult; + if (run.run_type === "llm") { + const prompts = run.inputs.prompts + ? run.inputs.prompts + : run.inputs.messages.map((x) => (0, base_js_1.getBufferString)(x)); + const llmRun = { + uuid: run.id, + start_time: run.start_time, + end_time: run.end_time, + execution_order: run.execution_order, + child_execution_order: run.child_execution_order, + serialized, + type: run.run_type, + session_id: session.id, + prompts, + response: run.outputs, + }; + runResult = llmRun; + } + else if (run.run_type === "chain") { + const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); + const chainRun = { + uuid: run.id, + start_time: run.start_time, + end_time: run.end_time, + execution_order: run.execution_order, + child_execution_order: run.child_execution_order, + serialized, + type: run.run_type, + session_id: session.id, + inputs: run.inputs, + outputs: run.outputs, + child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), + child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), + child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"), + }; + runResult = chainRun; + } + else if (run.run_type === "tool") { + const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); + const toolRun = { + uuid: run.id, + start_time: run.start_time, + end_time: run.end_time, + execution_order: run.execution_order, + child_execution_order: run.child_execution_order, + serialized, + type: run.run_type, + session_id: session.id, + tool_input: run.inputs.input, + output: run.outputs?.output, + action: JSON.stringify(serialized), + child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), + child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), + child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"), + }; + runResult = toolRun; + } + else { + throw new Error(`Unknown run type: ${run.run_type}`); + } + return runResult; + } + async persistRun(run) { + let endpoint; + let v1Run; + if (run.run_type !== undefined) { + v1Run = await this.convertV2RunToRun(run); + } + else { + v1Run = run; + } + if (v1Run.type === "llm") { + endpoint = `${this.endpoint}/llm-runs`; + } + else if (v1Run.type === "chain") { + endpoint = `${this.endpoint}/chain-runs`; + } + else { + endpoint = `${this.endpoint}/tool-runs`; + } + const response = await fetch(endpoint, { + method: "POST", + headers: this.headers, + body: JSON.stringify(v1Run), + }); + if (!response.ok) { + console.error(`Failed to persist run: ${response.status} ${response.statusText}`); + } + } + async persistSession(sessionCreate) { + const endpoint = `${this.endpoint}/sessions`; + const response = await fetch(endpoint, { + method: "POST", + headers: this.headers, + body: JSON.stringify(sessionCreate), + }); + if (!response.ok) { + console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`); + return { + id: 1, + ...sessionCreate, + }; + } + return { + id: (await response.json()).id, + ...sessionCreate, + }; + } + async _handleSessionResponse(endpoint) { + const response = await fetch(endpoint, { + method: "GET", + headers: this.headers, + }); + let tracerSession; + if (!response.ok) { + console.error(`Failed to load session: ${response.status} ${response.statusText}`); + tracerSession = { + id: 1, + start_time: Date.now(), + }; + this.session = tracerSession; + return tracerSession; + } + const resp = (await response.json()); + if (resp.length === 0) { + tracerSession = { + id: 1, + start_time: Date.now(), + }; + this.session = tracerSession; + return tracerSession; + } + [tracerSession] = resp; + this.session = tracerSession; + return tracerSession; } - } - return null; } +exports.LangChainTracerV1 = LangChainTracerV1; -const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) -})(); -const isContextDefined = (context) => !isUndefined(context) && context !== _global; +/***/ }), -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - const {caseless} = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else { - result[targetKey] = val; - } - } +/***/ 5128: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); - } - return result; -} -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * - * @param {Boolean} [allOwnKeys] - * @returns {Object} The resulting value of object a - */ -const extend = (a, b, thisArg, {allOwnKeys}= {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.traceAsGroup = exports.TraceGroup = exports.CallbackManager = exports.CallbackManagerForToolRun = exports.CallbackManagerForChainRun = exports.CallbackManagerForLLMRun = exports.CallbackManagerForRetrieverRun = exports.BaseCallbackManager = exports.parseCallbackConfigArg = void 0; +const uuid_1 = __nccwpck_require__(8655); +const base_js_1 = __nccwpck_require__(7656); +const console_js_1 = __nccwpck_require__(2533); +const initialize_js_1 = __nccwpck_require__(5814); +const base_js_2 = __nccwpck_require__(4235); +const env_js_1 = __nccwpck_require__(1548); +const tracer_langchain_js_1 = __nccwpck_require__(521); +const promises_js_1 = __nccwpck_require__(5556); +function parseCallbackConfigArg(arg) { + if (!arg) { + return {}; + } + else if (Array.isArray(arg) || "name" in arg) { + return { callbacks: arg }; + } + else { + return arg; } - }, {allOwnKeys}); - return a; } - +exports.parseCallbackConfigArg = parseCallbackConfigArg; /** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * - * @returns {string} content value without BOM + * Manage callbacks from different components of LangChain. */ -const stripBOM = (content) => { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; +class BaseCallbackManager { + setHandler(handler) { + return this.setHandlers([handler]); + } } - +exports.BaseCallbackManager = BaseCallbackManager; /** - * Inherit the prototype methods from one constructor into another - * @param {function} constructor - * @param {function} superConstructor - * @param {object} [props] - * @param {object} [descriptors] - * - * @returns {void} + * Base class for run manager in LangChain. */ -const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, 'super', { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); +class BaseRunManager { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + Object.defineProperty(this, "runId", { + enumerable: true, + configurable: true, + writable: true, + value: runId + }); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: handlers + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableHandlers + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: tags + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableTags + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: metadata + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableMetadata + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: _parentRunId + }); + } + async handleText(text) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + try { + await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + } + }, handler.awaitHandlers))); + } } - /** - * Resolve object with deep prototype chain to a flat object - * @param {Object} sourceObj source object - * @param {Object} [destObj] - * @param {Function|Boolean} [filter] - * @param {Function} [propFilter] - * - * @returns {Object} + * Manages callbacks for retriever runs. */ -const toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - - destObj = destObj || {}; - // eslint-disable-next-line no-eq-null,eqeqeq - if (sourceObj == null) return destObj; - - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } +class CallbackManagerForRetrieverRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleRetriever`); + } + } + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (error) { + console.error(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + } + } + }, handler.awaitHandlers))); + } +} +exports.CallbackManagerForRetrieverRun = CallbackManagerForRetrieverRun; +class CallbackManagerForLLMRun extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleLLMError(err) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } +} +exports.CallbackManagerForLLMRun = CallbackManagerForLLMRun; +class CallbackManagerForChainRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } +} +exports.CallbackManagerForChainRun = CallbackManagerForChainRun; +class CallbackManagerForToolRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); + } + } + }, handler.awaitHandlers))); + } + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + } + } + }, handler.awaitHandlers))); + } +} +exports.CallbackManagerForToolRun = CallbackManagerForToolRun; +class CallbackManager extends BaseCallbackManager { + constructor(parentRunId) { + super(); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "callback_manager" + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.handlers = []; + this.inheritableHandlers = []; + this._parentRunId = parentRunId; + } + async handleLLMStart(llm, prompts, _runId = undefined, _parentRunId = undefined, extraParams = undefined) { + return Promise.all(prompts.map(async (prompt) => { + const runId = (0, uuid_1.v4)(); + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMStart?.(llm, [prompt], runId, this._parentRunId, extraParams, this.tags, this.metadata); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, _runId = undefined, _parentRunId = undefined, extraParams = undefined) { + return Promise.all(messages.map(async (messageGroup) => { + const runId = (0, uuid_1.v4)(); + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreLLM) { + try { + if (handler.handleChatModelStart) + await handler.handleChatModelStart?.(llm, [messageGroup], runId, this._parentRunId, extraParams, this.tags, this.metadata); + else if (handler.handleLLMStart) { + const messageString = (0, base_js_2.getBufferString)(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId, this._parentRunId, extraParams, this.tags, this.metadata); + } + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = (0, uuid_1.v4)(), runType = undefined) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool, input, runId = (0, uuid_1.v4)()) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleRetrieverStart(retriever, query, runId = (0, uuid_1.v4)(), _parentRunId = undefined) { + await Promise.all(this.handlers.map((handler) => (0, promises_js_1.consumeCallback)(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata); + } + catch (err) { + console.error(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + } + } + }, handler.awaitHandlers))); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) { + this.inheritableHandlers.push(handler); + } + } + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); + } + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) { + this.addHandler(handler, inherit); + } + } + addTags(tags, inherit = true) { + this.removeTags(tags); // Remove duplicates + this.tags.push(...tags); + if (inherit) { + this.inheritableTags.push(...tags); + } + } + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); + } + addMetadata(metadata, inherit = true) { + this.metadata = { ...this.metadata, ...metadata }; + if (inherit) { + this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + } + } + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; + } + } + copy(additionalHandlers = [], inherit = true) { + const manager = new CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); + } + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if ( + // Prevent multiple copies of console_callback_handler + manager.handlers + .filter((h) => h.name === "console_callback_handler") + .some((h) => h.name === handler.name)) { + continue; + } + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends base_js_1.BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: (0, uuid_1.v4)() + }); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static async configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } + else { + callbackManager = inheritableHandlers; + } + callbackManager = callbackManager.copy(Array.isArray(localHandlers) + ? localHandlers.map(ensureHandler) + : localHandlers?.handlers, false); + } + const verboseEnabled = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_VERBOSE") || options?.verbose; + const tracingV2Enabled = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true"; + const tracingEnabled = tracingV2Enabled || + ((0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) { + callbackManager = new CallbackManager(); + } + if (verboseEnabled && + !callbackManager.handlers.some((handler) => handler.name === console_js_1.ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new console_js_1.ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && + !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + callbackManager.addHandler(await (0, initialize_js_1.getTracingV2CallbackHandler)(), true); + } + else { + const session = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_PROJECT") && + (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_SESSION"); + callbackManager.addHandler(await (0, initialize_js_1.getTracingCallbackHandler)(session), true); + } + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + return callbackManager; } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - - return destObj; -} - -/** - * Determines whether a string ends with the characters of a specified string - * - * @param {String} str - * @param {String} searchString - * @param {Number} [position= 0] - * - * @returns {boolean} - */ -const endsWith = (str, searchString, position) => { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -} - - -/** - * Returns new array from array like object or null if failed - * - * @param {*} [thing] - * - * @returns {?Array} - */ -const toArray = (thing) => { - if (!thing) return null; - if (isArray(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; -} - -/** - * Checking if the Uint8Array exists and if it does, it returns a function that checks if the - * thing passed in is an instance of Uint8Array - * - * @param {TypedArray} - * - * @returns {Array} - */ -// eslint-disable-next-line func-names -const isTypedArray = (TypedArray => { - // eslint-disable-next-line func-names - return thing => { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); - -/** - * For each entry in the object, call the function with the key and value. - * - * @param {Object} obj - The object to iterate over. - * @param {Function} fn - The function to call for each entry. - * - * @returns {void} - */ -const forEachEntry = (obj, fn) => { - const generator = obj && obj[Symbol.iterator]; - - const iterator = generator.call(obj); - - let result; - - while ((result = iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); - } } - -/** - * It takes a regular expression and a string, and returns an array of all the matches - * - * @param {string} regExp - The regular expression to match against. - * @param {string} str - The string to search. - * - * @returns {Array} - */ -const matchAll = (regExp, str) => { - let matches; - const arr = []; - - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } - - return arr; +exports.CallbackManager = CallbackManager; +function ensureHandler(handler) { + if ("name" in handler) { + return handler; + } + return base_js_1.BaseCallbackHandler.fromMethods(handler); } - -/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ -const isHTMLForm = kindOfTest('HTMLFormElement'); - -const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; +class TraceGroup { + constructor(groupName, options) { + Object.defineProperty(this, "groupName", { + enumerable: true, + configurable: true, + writable: true, + value: groupName + }); + Object.defineProperty(this, "options", { + enumerable: true, + configurable: true, + writable: true, + value: options + }); + Object.defineProperty(this, "runManager", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); } - ); -}; - -/* Creating a function that will check if an object has a property. */ -const utils_hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); - -/** - * Determine if a value is a RegExp object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a RegExp object, otherwise false - */ -const isRegExp = kindOfTest('RegExp'); - -const reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; + async getTraceGroupCallbackManager(group_name, inputs, options) { + const cb = new tracer_langchain_js_1.LangChainTracer(options); + const cm = await CallbackManager.configure([cb]); + const runManager = await cm?.handleChainStart({ + lc: 1, + type: "not_implemented", + id: ["langchain", "callbacks", "groups", group_name], + }, inputs ?? {}); + if (!runManager) { + throw new Error("Failed to create run group callback manager."); + } + return runManager; } - }); - - Object.defineProperties(obj, reducedDescriptors); -} - -/** - * Makes all methods read-only - * @param {Object} obj - */ - -const freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; + async start(inputs) { + if (!this.runManager) { + this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); + } + return this.runManager.getChild(); } - - const value = obj[name]; - - if (!isFunction(value)) return; - - descriptor.enumerable = false; - - if ('writable' in descriptor) { - descriptor.writable = false; - return; + async error(err) { + if (this.runManager) { + await this.runManager.handleChainError(err); + this.runManager = undefined; + } } - - if (!descriptor.set) { - descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); - }; + async end(output) { + if (this.runManager) { + await this.runManager.handleChainEnd(output ?? {}); + this.runManager = undefined; + } } - }); -} - -const toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - - const define = (arr) => { - arr.forEach(value => { - obj[value] = true; - }); - } - - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); - - return obj; -} - -const noop = () => {} - -const toFiniteNumber = (value, defaultValue) => { - value = +value; - return Number.isFinite(value) ? value : defaultValue; -} - -const ALPHA = 'abcdefghijklmnopqrstuvwxyz' - -const DIGIT = '0123456789'; - -const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT -} - -const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - while (size--) { - str += alphabet[Math.random() * length|0] - } - - return str; } - -/** - * If the thing is a FormData object, return true, otherwise return false. - * - * @param {unknown} thing - The thing to check. - * - * @returns {boolean} - */ -function isSpecCompliantForm(thing) { - return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]); +exports.TraceGroup = TraceGroup; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; } - -const toJSONObject = (obj) => { - const stack = new Array(10); - - const visit = (source, i) => { - - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; - - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); - - stack[i] = undefined; - - return target; - } +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function traceAsGroup(groupOptions, enclosedCode, ...args) { + const traceGroup = new TraceGroup(groupOptions.name, groupOptions); + const callbackManager = await traceGroup.start({ ...args }); + try { + const result = await enclosedCode(callbackManager, ...args); + await traceGroup.end(_coerceToDict(result, "output")); + return result; + } + catch (err) { + await traceGroup.error(err); + throw err; } - - return source; - } - - return visit(obj, 0); -} - -const isAsyncFn = kindOfTest('AsyncFunction'); - -const isThenable = (thing) => - thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch); - -/* harmony default export */ const utils = ({ - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty: utils_hasOwnProperty, - hasOwnProp: utils_hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - ALPHABET, - generateString, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable -}); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/AxiosError.js - - - - -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * - * @returns {Error} The created error. - */ -function AxiosError(message, code, config, request, response) { - Error.call(this); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = (new Error()).stack; - } - - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - response && (this.response = response); } +exports.traceAsGroup = traceAsGroup; -utils.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils.toJSONObject(this.config), - code: this.code, - status: this.response && this.response.status ? this.response.status : null - }; - } -}); - -const AxiosError_prototype = AxiosError.prototype; -const descriptors = {}; - -[ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED', - 'ERR_NOT_SUPPORT', - 'ERR_INVALID_URL' -// eslint-disable-next-line func-names -].forEach(code => { - descriptors[code] = {value: code}; -}); - -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(AxiosError_prototype, 'isAxiosError', {value: true}); - -// eslint-disable-next-line func-names -AxiosError.from = (error, code, config, request, response, customProps) => { - const axiosError = Object.create(AxiosError_prototype); - - utils.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, prop => { - return prop !== 'isAxiosError'; - }); - - AxiosError.call(axiosError, error.message, code, config, request, response); - axiosError.cause = error; +/***/ }), - axiosError.name = error.name; +/***/ 5556: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - customProps && Object.assign(axiosError, customProps); - return axiosError; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; }; - -/* harmony default export */ const core_AxiosError = (AxiosError); - -// EXTERNAL MODULE: ./node_modules/form-data/lib/form_data.js -var form_data = __nccwpck_require__(4334); -;// CONCATENATED MODULE: ./node_modules/axios/lib/platform/node/classes/FormData.js - - -/* harmony default export */ const classes_FormData = (form_data); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/toFormData.js - - - - -// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored - - -/** - * Determines if the given thing is a array or js object. - * - * @param {string} thing - The object or array to be visited. - * - * @returns {boolean} - */ -function isVisitable(thing) { - return utils.isPlainObject(thing) || utils.isArray(thing); -} - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.awaitAllCallbacks = exports.consumeCallback = void 0; +const p_queue_1 = __importDefault(__nccwpck_require__(8983)); +let queue; /** - * It removes the brackets from the end of a string - * - * @param {string} key - The key of the parameter. - * - * @returns {string} the key without the brackets. + * Creates a queue using the p-queue library. The queue is configured to + * auto-start and has a concurrency of 1, meaning it will process tasks + * one at a time. */ -function removeBrackets(key) { - return utils.endsWith(key, '[]') ? key.slice(0, -2) : key; +function createQueue() { + const PQueue = "default" in p_queue_1.default ? p_queue_1.default.default : p_queue_1.default; + return new PQueue({ + autoStart: true, + concurrency: 1, + }); } - /** - * It takes a path, a key, and a boolean, and returns a string - * - * @param {string} path - The path to the current key. - * @param {string} key - The key of the current object being iterated over. - * @param {string} dots - If true, the key will be rendered with dots instead of brackets. - * - * @returns {string} The path to the current key. + * Consume a promise, either adding it to the queue or waiting for it to resolve + * @param promise Promise to consume + * @param wait Whether to wait for the promise to resolve or resolve immediately */ -function renderKey(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - // eslint-disable-next-line no-param-reassign - token = removeBrackets(token); - return !dots && i ? '[' + token + ']' : token; - }).join(dots ? '.' : ''); +async function consumeCallback(promiseFn, wait) { + if (wait === true) { + await promiseFn(); + } + else { + if (typeof queue === "undefined") { + queue = createQueue(); + } + void queue.add(promiseFn); + } } - +exports.consumeCallback = consumeCallback; /** - * If the array is an array and none of its elements are visitable, then it's a flat array. - * - * @param {Array} arr - The array to check - * - * @returns {boolean} + * Waits for all promises in the queue to resolve. If the queue is + * undefined, it immediately resolves a promise. */ -function isFlatArray(arr) { - return utils.isArray(arr) && !arr.some(isVisitable); +function awaitAllCallbacks() { + return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); } +exports.awaitAllCallbacks = awaitAllCallbacks; -const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); -}); -/** - * Convert a data object to FormData - * - * @param {Object} obj - * @param {?Object} [formData] - * @param {?Object} [options] - * @param {Function} [options.visitor] - * @param {Boolean} [options.metaTokens = true] - * @param {Boolean} [options.dots = false] - * @param {?Boolean} [options.indexes = false] - * - * @returns {Object} - **/ +/***/ }), + +/***/ 3745: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AnalyzeDocumentChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const text_splitter_js_1 = __nccwpck_require__(8854); /** - * It converts an object into a FormData object - * - * @param {Object} obj - The object to convert to form data. - * @param {string} formData - The FormData object to append to. - * @param {Object} options - * - * @returns + * Chain that combines documents by stuffing into context. + * @augments BaseChain + * @augments StuffDocumentsChainInput */ -function toFormData(obj, formData, options) { - if (!utils.isObject(obj)) { - throw new TypeError('target must be an object'); - } - - // eslint-disable-next-line no-param-reassign - formData = formData || new (classes_FormData || FormData)(); +class AnalyzeDocumentChain extends base_js_1.BaseChain { + static lc_name() { + return "AnalyzeDocumentChain"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_document" + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "textSplitter", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.combineDocumentsChain = fields.combineDocumentsChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.textSplitter = + fields.textSplitter ?? new text_splitter_js_1.RecursiveCharacterTextSplitter(); + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return this.combineDocumentsChain.outputKeys; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: doc, ...rest } = values; + const currentDoc = doc; + const currentDocs = await this.textSplitter.createDocuments([currentDoc]); + const newInputs = { input_documents: currentDocs, ...rest }; + const result = await this.combineDocumentsChain.call(newInputs, runManager?.getChild("combine_documents")); + return result; + } + _chainType() { + return "analyze_document_chain"; + } + static async deserialize(data, values) { + if (!("text_splitter" in values)) { + throw new Error(`Need to pass in a text_splitter to deserialize AnalyzeDocumentChain.`); + } + const { text_splitter } = values; + if (!data.combine_document_chain) { + throw new Error(`Need to pass in a combine_document_chain to deserialize AnalyzeDocumentChain.`); + } + return new AnalyzeDocumentChain({ + combineDocumentsChain: await base_js_1.BaseChain.deserialize(data.combine_document_chain), + textSplitter: text_splitter, + }); + } + serialize() { + return { + _type: this._chainType(), + combine_document_chain: this.combineDocumentsChain.serialize(), + }; + } +} +exports.AnalyzeDocumentChain = AnalyzeDocumentChain; - // eslint-disable-next-line no-param-reassign - options = utils.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - // eslint-disable-next-line no-eq-null,eqeqeq - return !utils.isUndefined(source[option]); - }); - const metaTokens = options.metaTokens; - // eslint-disable-next-line no-use-before-define - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; - const useBlob = _Blob && utils.isSpecCompliantForm(formData); +/***/ }), - if (!utils.isFunction(visitor)) { - throw new TypeError('visitor must be a function'); - } +/***/ 4291: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function convertValue(value) { - if (value === null) return ''; - if (utils.isDate(value)) { - return value.toISOString(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.APIChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const llm_chain_js_1 = __nccwpck_require__(4553); +const prompts_js_1 = __nccwpck_require__(769); +/** + * Class that extends BaseChain and represents a chain specifically + * designed for making API requests and processing API responses. + */ +class APIChain extends base_js_1.BaseChain { + get inputKeys() { + return [this.inputKey]; } - - if (!useBlob && utils.isBlob(value)) { - throw new core_AxiosError('Blob is not supported. Use a Buffer instead.'); + get outputKeys() { + return [this.outputKey]; } - - if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) { - return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + constructor(fields) { + super(fields); + Object.defineProperty(this, "apiAnswerChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiRequestChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiDocs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "question" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + this.apiRequestChain = fields.apiRequestChain; + this.apiAnswerChain = fields.apiAnswerChain; + this.apiDocs = fields.apiDocs; + this.inputKey = fields.inputKey ?? this.inputKey; + this.outputKey = fields.outputKey ?? this.outputKey; + this.headers = fields.headers ?? this.headers; } - - return value; - } - - /** - * Default visitor. - * - * @param {*} value - * @param {String|Number} key - * @param {Array} path - * @this {FormData} - * - * @returns {boolean} return true to visit the each prop of the value recursively - */ - function defaultVisitor(value, key, path) { - let arr = value; - - if (value && !path && typeof value === 'object') { - if (utils.endsWith(key, '{}')) { - // eslint-disable-next-line no-param-reassign - key = metaTokens ? key : key.slice(0, -2); - // eslint-disable-next-line no-param-reassign - value = JSON.stringify(value); - } else if ( - (utils.isArray(value) && isFlatArray(value)) || - ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)) - )) { - // eslint-disable-next-line no-param-reassign - key = removeBrackets(key); - - arr.forEach(function each(el, index) { - !(utils.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), - convertValue(el) - ); + /** @ignore */ + async _call(values, runManager) { + const question = values[this.inputKey]; + const api_url = await this.apiRequestChain.predict({ question, api_docs: this.apiDocs }, runManager?.getChild("request")); + const res = await fetch(api_url, { headers: this.headers }); + const api_response = await res.text(); + const answer = await this.apiAnswerChain.predict({ question, api_docs: this.apiDocs, api_url, api_response }, runManager?.getChild("response")); + return { [this.outputKey]: answer }; + } + _chainType() { + return "api_chain"; + } + static async deserialize(data) { + const { api_request_chain, api_answer_chain, api_docs } = data; + if (!api_request_chain) { + throw new Error("LLMChain must have api_request_chain"); + } + if (!api_answer_chain) { + throw new Error("LLMChain must have api_answer_chain"); + } + if (!api_docs) { + throw new Error("LLMChain must have api_docs"); + } + return new APIChain({ + apiAnswerChain: await llm_chain_js_1.LLMChain.deserialize(api_answer_chain), + apiRequestChain: await llm_chain_js_1.LLMChain.deserialize(api_request_chain), + apiDocs: api_docs, }); - return false; - } } - - if (isVisitable(value)) { - return true; + serialize() { + return { + _type: this._chainType(), + api_answer_chain: this.apiAnswerChain.serialize(), + api_request_chain: this.apiRequestChain.serialize(), + api_docs: this.apiDocs, + }; + } + /** + * Static method to create a new APIChain from a BaseLanguageModel and API + * documentation. + * @param llm BaseLanguageModel instance. + * @param apiDocs API documentation. + * @param options Optional configuration options for the APIChain. + * @returns New APIChain instance. + */ + static fromLLMAndAPIDocs(llm, apiDocs, options = {}) { + const { apiUrlPrompt = prompts_js_1.API_URL_PROMPT_TEMPLATE, apiResponsePrompt = prompts_js_1.API_RESPONSE_PROMPT_TEMPLATE, } = options; + const apiRequestChain = new llm_chain_js_1.LLMChain({ prompt: apiUrlPrompt, llm }); + const apiAnswerChain = new llm_chain_js_1.LLMChain({ prompt: apiResponsePrompt, llm }); + return new this({ + apiAnswerChain, + apiRequestChain, + apiDocs, + ...options, + }); } +} +exports.APIChain = APIChain; - formData.append(renderKey(path, key, dots), convertValue(value)); - return false; - } +/***/ }), - const stack = []; +/***/ 769: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); - function build(value, path) { - if (utils.isUndefined(value)) return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.API_RESPONSE_PROMPT_TEMPLATE = exports.API_RESPONSE_RAW_PROMPT_TEMPLATE = exports.API_URL_PROMPT_TEMPLATE = exports.API_URL_RAW_PROMPT_TEMPLATE = void 0; +/* eslint-disable spaced-comment */ +const prompt_js_1 = __nccwpck_require__(8767); +exports.API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation: +{api_docs} +Using this documentation, generate the full API url to call for answering the user question. +You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call. - if (stack.indexOf(value) !== -1) { - throw Error('Circular reference detected in ' + path.join('.')); - } +Question:{question} +API url:`; +exports.API_URL_PROMPT_TEMPLATE = new prompt_js_1.PromptTemplate({ + inputVariables: ["api_docs", "question"], + template: exports.API_URL_RAW_PROMPT_TEMPLATE, +}); +exports.API_RESPONSE_RAW_PROMPT_TEMPLATE = `${exports.API_URL_RAW_PROMPT_TEMPLATE} {api_url} - stack.push(value); +Here is the response from the API: - utils.forEach(value, function each(el, key) { - const result = !(utils.isUndefined(el) || el === null) && visitor.call( - formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers - ); +{api_response} - if (result === true) { - build(el, path ? path.concat(key) : [key]); - } - }); +Summarize this response to answer the original question. - stack.pop(); - } +Summary:`; +exports.API_RESPONSE_PROMPT_TEMPLATE = new prompt_js_1.PromptTemplate({ + inputVariables: ["api_docs", "question", "api_url", "api_response"], + template: exports.API_RESPONSE_RAW_PROMPT_TEMPLATE, +}); - if (!utils.isObject(obj)) { - throw new TypeError('data must be an object'); - } - build(obj); +/***/ }), - return formData; +/***/ 6529: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BaseChain = void 0; +const index_js_1 = __nccwpck_require__(1445); +const manager_js_1 = __nccwpck_require__(5128); +const index_js_2 = __nccwpck_require__(6691); +/** + * Base interface that all chains must implement. + */ +class BaseChain extends index_js_2.BaseLangChain { + get lc_namespace() { + return ["langchain", "chains", this._chainType()]; + } + constructor(fields, + /** @deprecated */ + verbose, + /** @deprecated */ + callbacks) { + if (arguments.length === 1 && + typeof fields === "object" && + !("saveContext" in fields)) { + // fields is not a BaseMemory + const { memory, callbackManager, ...rest } = fields; + super({ ...rest, callbacks: callbackManager ?? rest.callbacks }); + this.memory = memory; + } + else { + // fields is a BaseMemory + super({ verbose, callbacks }); + this.memory = fields; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = { ...values }; + if ("signal" in valuesForMemory) { + delete valuesForMemory.signal; + } + if ("timeout" in valuesForMemory) { + delete valuesForMemory.timeout; + } + return valuesForMemory; + } + /** + * Invoke the chain with the provided input and returns the output. + * @param input Input values for the chain run. + * @param config Optional configuration for the Runnable. + * @returns Promise that resolves with the output of the chain run. + */ + async invoke(input, config) { + return this.call(input, config); + } + /** + * Return a json-like object representing this chain. + */ + serialize() { + throw new Error("Method not implemented."); + } + async run( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, config) { + const inputKeys = this.inputKeys.filter((k) => !this.memory?.memoryKeys.includes(k) ?? true); + const isKeylessInput = inputKeys.length <= 1; + if (!isKeylessInput) { + throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; + const returnValues = await this.call(values, config); + const keys = Object.keys(returnValues); + if (keys.length === 1) { + return returnValues[keys[0]]; + } + throw new Error("return values have multiple keys, `run` only supported when one key currently"); + } + async _formatValues(values) { + const fullValues = { ...values }; + if (fullValues.timeout && !fullValues.signal) { + fullValues.signal = AbortSignal.timeout(fullValues.timeout); + delete fullValues.timeout; + } + if (!(this.memory == null)) { + const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); + for (const [key, value] of Object.entries(newValues)) { + fullValues[key] = value; + } + } + return fullValues; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + async call(values, config, + /** @deprecated */ + tags) { + const fullValues = await this._formatValues(values); + const parsedConfig = (0, manager_js_1.parseCallbackConfigArg)(config); + const callbackManager_ = await manager_js_1.CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), fullValues); + let outputValues; + try { + outputValues = await (values.signal + ? Promise.race([ + this._call(fullValues, runManager), + new Promise((_, reject) => { + values.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]) + : this._call(fullValues, runManager)); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + if (!(this.memory == null)) { + await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); + } + await runManager?.handleChainEnd(outputValues); + // add the runManager's currentRunId to the outputValues + Object.defineProperty(outputValues, index_js_1.RUN_KEY, { + value: runManager ? { runId: runManager?.runId } : undefined, + configurable: true, + }); + return outputValues; + } + /** + * Call the chain on all inputs in the list + */ + async apply(inputs, config) { + return Promise.all(inputs.map(async (i, idx) => this.call(i, config?.[idx]))); + } + /** + * Load a chain from a json-like object describing it. + */ + static async deserialize(data, values = {}) { + switch (data._type) { + case "llm_chain": { + const { LLMChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(130)]).then(__nccwpck_require__.bind(__nccwpck_require__, 7273)); + return LLMChain.deserialize(data); + } + case "sequential_chain": { + const { SequentialChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(231)]).then(__nccwpck_require__.bind(__nccwpck_require__, 7210)); + return SequentialChain.deserialize(data); + } + case "simple_sequential_chain": { + const { SimpleSequentialChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(231)]).then(__nccwpck_require__.bind(__nccwpck_require__, 7210)); + return SimpleSequentialChain.deserialize(data); + } + case "stuff_documents_chain": { + const { StuffDocumentsChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(608), __nccwpck_require__.e(197)]).then(__nccwpck_require__.bind(__nccwpck_require__, 3608)); + return StuffDocumentsChain.deserialize(data); + } + case "map_reduce_documents_chain": { + const { MapReduceDocumentsChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(608), __nccwpck_require__.e(197)]).then(__nccwpck_require__.bind(__nccwpck_require__, 3608)); + return MapReduceDocumentsChain.deserialize(data); + } + case "refine_documents_chain": { + const { RefineDocumentsChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(608), __nccwpck_require__.e(197)]).then(__nccwpck_require__.bind(__nccwpck_require__, 3608)); + return RefineDocumentsChain.deserialize(data); + } + case "vector_db_qa": { + const { VectorDBQAChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(608), __nccwpck_require__.e(312)]).then(__nccwpck_require__.bind(__nccwpck_require__, 5214)); + return VectorDBQAChain.deserialize(data, values); + } + case "api_chain": { + const { APIChain } = await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(586)]).then(__nccwpck_require__.bind(__nccwpck_require__, 6159)); + return APIChain.deserialize(data); + } + default: + throw new Error(`Invalid prompt type in config: ${data._type}`); + } + } } +exports.BaseChain = BaseChain; -/* harmony default export */ const helpers_toFormData = (toFormData); -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/AxiosURLSearchParams.js +/***/ }), +/***/ 1582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ChatVectorDBQAChain = void 0; +const prompt_js_1 = __nccwpck_require__(8767); +const base_js_1 = __nccwpck_require__(6529); +const llm_chain_js_1 = __nccwpck_require__(4553); +const load_js_1 = __nccwpck_require__(2664); +const question_generator_template = `Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question. -/** - * It encodes a string by replacing all characters that are not in the unreserved set with - * their percent-encoded equivalents - * - * @param {string} str - The string to encode. - * - * @returns {string} The encoded string. - */ -function encode(str) { - const charMap = { - '!': '%21', - "'": '%27', - '(': '%28', - ')': '%29', - '~': '%7E', - '%20': '+', - '%00': '\x00' - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); -} +Chat History: +{chat_history} +Follow Up Input: {question} +Standalone question:`; +const qa_template = `Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. -/** - * It takes a params object and converts it to a FormData object - * - * @param {Object} params - The parameters to be converted to a FormData object. - * @param {Object} options - The options object passed to the Axios constructor. - * - * @returns {void} - */ -function AxiosURLSearchParams(params, options) { - this._pairs = []; +{context} - params && helpers_toFormData(params, this, options); +Question: {question} +Helpful Answer:`; +/** @deprecated use `ConversationalRetrievalQAChain` instead. */ +class ChatVectorDBQAChain extends base_js_1.BaseChain { + get inputKeys() { + return [this.inputKey, this.chatHistoryKey]; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "k", { + enumerable: true, + configurable: true, + writable: true, + value: 4 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "question" + }); + Object.defineProperty(this, "chatHistoryKey", { + enumerable: true, + configurable: true, + writable: true, + value: "chat_history" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "result" + }); + Object.defineProperty(this, "vectorstore", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "questionGeneratorChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnSourceDocuments", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.vectorstore = fields.vectorstore; + this.combineDocumentsChain = fields.combineDocumentsChain; + this.questionGeneratorChain = fields.questionGeneratorChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.outputKey = fields.outputKey ?? this.outputKey; + this.k = fields.k ?? this.k; + this.returnSourceDocuments = + fields.returnSourceDocuments ?? this.returnSourceDocuments; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Question key ${this.inputKey} not found.`); + } + if (!(this.chatHistoryKey in values)) { + throw new Error(`chat history key ${this.inputKey} not found.`); + } + const question = values[this.inputKey]; + const chatHistory = values[this.chatHistoryKey]; + let newQuestion = question; + if (chatHistory.length > 0) { + const result = await this.questionGeneratorChain.call({ + question, + chat_history: chatHistory, + }, runManager?.getChild("question_generator")); + const keys = Object.keys(result); + console.log("_call", values, keys); + if (keys.length === 1) { + newQuestion = result[keys[0]]; + } + else { + throw new Error("Return from llm chain has multiple values, only single values supported."); + } + } + const docs = await this.vectorstore.similaritySearch(newQuestion, this.k, undefined, runManager?.getChild("vectorstore")); + const inputs = { + question: newQuestion, + input_documents: docs, + chat_history: chatHistory, + }; + const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); + if (this.returnSourceDocuments) { + return { + ...result, + sourceDocuments: docs, + }; + } + return result; + } + _chainType() { + return "chat-vector-db"; + } + static async deserialize(data, values) { + if (!("vectorstore" in values)) { + throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); + } + const { vectorstore } = values; + return new ChatVectorDBQAChain({ + combineDocumentsChain: await base_js_1.BaseChain.deserialize(data.combine_documents_chain), + questionGeneratorChain: await llm_chain_js_1.LLMChain.deserialize(data.question_generator), + k: data.k, + vectorstore, + }); + } + serialize() { + return { + _type: this._chainType(), + combine_documents_chain: this.combineDocumentsChain.serialize(), + question_generator: this.questionGeneratorChain.serialize(), + k: this.k, + }; + } + /** + * Creates an instance of ChatVectorDBQAChain using a BaseLanguageModel + * and other options. + * @param llm Instance of BaseLanguageModel used to generate a new question. + * @param vectorstore Instance of VectorStore used for vector operations. + * @param options (Optional) Additional options for creating the ChatVectorDBQAChain instance. + * @returns New instance of ChatVectorDBQAChain. + */ + static fromLLM(llm, vectorstore, options = {}) { + const { questionGeneratorTemplate, qaTemplate, verbose, ...rest } = options; + const question_generator_prompt = prompt_js_1.PromptTemplate.fromTemplate(questionGeneratorTemplate || question_generator_template); + const qa_prompt = prompt_js_1.PromptTemplate.fromTemplate(qaTemplate || qa_template); + const qaChain = (0, load_js_1.loadQAStuffChain)(llm, { prompt: qa_prompt, verbose }); + const questionGeneratorChain = new llm_chain_js_1.LLMChain({ + prompt: question_generator_prompt, + llm, + verbose, + }); + const instance = new this({ + vectorstore, + combineDocumentsChain: qaChain, + questionGeneratorChain, + ...rest, + }); + return instance; + } } - -const AxiosURLSearchParams_prototype = AxiosURLSearchParams.prototype; - -AxiosURLSearchParams_prototype.append = function append(name, value) { - this._pairs.push([name, value]); -}; - -AxiosURLSearchParams_prototype.toString = function toString(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode); - } : encode; - - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + '=' + _encode(pair[1]); - }, '').join('&'); -}; - -/* harmony default export */ const helpers_AxiosURLSearchParams = (AxiosURLSearchParams); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/buildURL.js +exports.ChatVectorDBQAChain = ChatVectorDBQAChain; +/***/ }), +/***/ 3186: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RefineDocumentsChain = exports.MapReduceDocumentsChain = exports.StuffDocumentsChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const llm_chain_js_1 = __nccwpck_require__(4553); +const prompt_js_1 = __nccwpck_require__(8767); /** - * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their - * URI encoded counterparts - * - * @param {string} val The value to be encoded. - * - * @returns {string} The encoded value. + * Chain that combines documents by stuffing into context. + * @augments BaseChain + * @augments StuffDocumentsChainInput */ -function buildURL_encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); +class StuffDocumentsChain extends base_js_1.BaseChain { + static lc_name() { + return "StuffDocumentsChain"; + } + get inputKeys() { + return [this.inputKey, ...this.llmChain.inputKeys].filter((key) => key !== this.documentVariableName); + } + get outputKeys() { + return this.llmChain.outputKeys; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_documents" + }); + Object.defineProperty(this, "documentVariableName", { + enumerable: true, + configurable: true, + writable: true, + value: "context" + }); + this.llmChain = fields.llmChain; + this.documentVariableName = + fields.documentVariableName ?? this.documentVariableName; + this.inputKey = fields.inputKey ?? this.inputKey; + } + /** @ignore */ + _prepInputs(values) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: docs, ...rest } = values; + const texts = docs.map(({ pageContent }) => pageContent); + const text = texts.join("\n\n"); + return { + ...rest, + [this.documentVariableName]: text, + }; + } + /** @ignore */ + async _call(values, runManager) { + const result = await this.llmChain.call(this._prepInputs(values), runManager?.getChild("combine_documents")); + return result; + } + _chainType() { + return "stuff_documents_chain"; + } + static async deserialize(data) { + if (!data.llm_chain) { + throw new Error("Missing llm_chain"); + } + return new StuffDocumentsChain({ + llmChain: await llm_chain_js_1.LLMChain.deserialize(data.llm_chain), + }); + } + serialize() { + return { + _type: this._chainType(), + llm_chain: this.llmChain.serialize(), + }; + } } - +exports.StuffDocumentsChain = StuffDocumentsChain; /** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @param {?object} options - * - * @returns {string} The formatted url + * Combine documents by mapping a chain over them, then combining results. + * @augments BaseChain + * @augments StuffDocumentsChainInput */ -function buildURL(url, params, options) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - const _encode = options && options.encode || buildURL_encode; - - const serializeFn = options && options.serialize; - - let serializedParams; - - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils.isURLSearchParams(params) ? - params.toString() : - new helpers_AxiosURLSearchParams(params, options).toString(_encode); - } - - if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); - - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); +class MapReduceDocumentsChain extends base_js_1.BaseChain { + static lc_name() { + return "MapReduceDocumentsChain"; } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; -} - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/InterceptorManager.js - - - - -class InterceptorManager { - constructor() { - this.handlers = []; - } - - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise - */ - eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; + get inputKeys() { + return [this.inputKey, ...this.combineDocumentChain.inputKeys]; } - } - - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; + get outputKeys() { + return this.combineDocumentChain.outputKeys; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_documents" + }); + Object.defineProperty(this, "documentVariableName", { + enumerable: true, + configurable: true, + writable: true, + value: "context" + }); + Object.defineProperty(this, "returnIntermediateSteps", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: 3000 + }); + Object.defineProperty(this, "maxIterations", { + enumerable: true, + configurable: true, + writable: true, + value: 10 + }); + Object.defineProperty(this, "ensureMapStep", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "combineDocumentChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmChain = fields.llmChain; + this.combineDocumentChain = fields.combineDocumentChain; + this.documentVariableName = + fields.documentVariableName ?? this.documentVariableName; + this.ensureMapStep = fields.ensureMapStep ?? this.ensureMapStep; + this.inputKey = fields.inputKey ?? this.inputKey; + this.maxTokens = fields.maxTokens ?? this.maxTokens; + this.maxIterations = fields.maxIterations ?? this.maxIterations; + this.returnIntermediateSteps = fields.returnIntermediateSteps ?? false; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: docs, ...rest } = values; + let currentDocs = docs; + let intermediateSteps = []; + // For each iteration, we'll use the `llmChain` to get a new result + for (let i = 0; i < this.maxIterations; i += 1) { + const inputs = currentDocs.map((d) => ({ + [this.documentVariableName]: d.pageContent, + ...rest, + })); + const canSkipMapStep = i !== 0 || !this.ensureMapStep; + if (canSkipMapStep) { + // Calculate the total tokens required in the input + const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({ + [this.combineDocumentChain.inputKey]: currentDocs, + ...rest, + })); + const length = await this.combineDocumentChain.llmChain.llm.getNumTokens(formatted); + const withinTokenLimit = length < this.maxTokens; + // If we can skip the map step, and we're within the token limit, we don't + // need to run the map step, so just break out of the loop. + if (withinTokenLimit) { + break; + } + } + const results = await this.llmChain.apply(inputs, + // If we have a runManager, then we need to create a child for each input + // so that we can track the progress of each input. + runManager + ? Array.from({ length: inputs.length }, (_, i) => runManager.getChild(`map_${i + 1}`)) + : undefined); + const { outputKey } = this.llmChain; + // If the flag is set, then concat that to the intermediate steps + if (this.returnIntermediateSteps) { + intermediateSteps = intermediateSteps.concat(results.map((r) => r[outputKey])); + } + currentDocs = results.map((r) => ({ + pageContent: r[outputKey], + metadata: {}, + })); + } + // Now, with the final result of all the inputs from the `llmChain`, we can + // run the `combineDocumentChain` over them. + const newInputs = { + [this.combineDocumentChain.inputKey]: currentDocs, + ...rest, + }; + const result = await this.combineDocumentChain.call(newInputs, runManager?.getChild("combine_documents")); + // Return the intermediate steps results if the flag is set + if (this.returnIntermediateSteps) { + return { ...result, intermediateSteps }; + } + return result; } - } - - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn) { - utils.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - } -} - -/* harmony default export */ const core_InterceptorManager = (InterceptorManager); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/defaults/transitional.js - - -/* harmony default export */ const defaults_transitional = ({ - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false -}); - -// EXTERNAL MODULE: external "url" -var external_url_ = __nccwpck_require__(7310); -;// CONCATENATED MODULE: ./node_modules/axios/lib/platform/node/classes/URLSearchParams.js - - - -/* harmony default export */ const classes_URLSearchParams = (external_url_.URLSearchParams); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/platform/node/index.js - - - -/* harmony default export */ const node = ({ - isNode: true, - classes: { - URLSearchParams: classes_URLSearchParams, - FormData: classes_FormData, - Blob: typeof Blob !== 'undefined' && Blob || null - }, - protocols: [ 'http', 'https', 'file', 'data' ] -}); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/toURLEncodedForm.js - - - - - - -function toURLEncodedForm(data, options) { - return helpers_toFormData(data, new node.classes.URLSearchParams(), Object.assign({ - visitor: function(value, key, path, helpers) { - if (node.isNode && utils.isBuffer(value)) { - this.append(key, value.toString('base64')); - return false; - } - - return helpers.defaultVisitor.apply(this, arguments); + _chainType() { + return "map_reduce_documents_chain"; + } + static async deserialize(data) { + if (!data.llm_chain) { + throw new Error("Missing llm_chain"); + } + if (!data.combine_document_chain) { + throw new Error("Missing combine_document_chain"); + } + return new MapReduceDocumentsChain({ + llmChain: await llm_chain_js_1.LLMChain.deserialize(data.llm_chain), + combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain), + }); + } + serialize() { + return { + _type: this._chainType(), + llm_chain: this.llmChain.serialize(), + combine_document_chain: this.combineDocumentChain.serialize(), + }; } - }, options)); -} - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/formDataToJSON.js - - - - -/** - * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] - * - * @param {string} name - The name of the property to get. - * - * @returns An array of strings. - */ -function parsePropPath(name) { - // foo[x][y][z] - // foo.x.y.z - // foo-x-y-z - // foo x y z - return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => { - return match[0] === '[]' ? '' : match[1] || match[0]; - }); -} - -/** - * Convert an array to an object. - * - * @param {Array} arr - The array to convert to an object. - * - * @returns An object with the same keys and values as the array. - */ -function arrayToObject(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; - } - return obj; } - +exports.MapReduceDocumentsChain = MapReduceDocumentsChain; /** - * It takes a FormData object and returns a JavaScript object - * - * @param {string} formData The FormData object to convert to JSON. - * - * @returns {Object | null} The converted object. + * Combine documents by doing a first pass and then refining on more documents. + * @augments BaseChain + * @augments RefineDocumentsChainInput */ -function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - let name = path[index++]; - const isNumericKey = Number.isFinite(+name); - const isLast = index >= path.length; - name = !name && utils.isArray(target) ? target.length : name; - - if (isLast) { - if (utils.hasOwnProp(target, name)) { - target[name] = [target[name], value]; - } else { - target[name] = value; - } - - return !isNumericKey; +class RefineDocumentsChain extends base_js_1.BaseChain { + static lc_name() { + return "RefineDocumentsChain"; } - - if (!target[name] || !utils.isObject(target[name])) { - target[name] = []; + get defaultDocumentPrompt() { + return new prompt_js_1.PromptTemplate({ + inputVariables: ["page_content"], + template: "{page_content}", + }); } - - const result = buildPath(path, value, target[name], index); - - if (result && utils.isArray(target[name])) { - target[name] = arrayToObject(target[name]); + get inputKeys() { + return [ + ...new Set([ + this.inputKey, + ...this.llmChain.inputKeys, + ...this.refineLLMChain.inputKeys, + ]), + ].filter((key) => key !== this.documentVariableName && key !== this.initialResponseName); + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input_documents" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output_text" + }); + Object.defineProperty(this, "documentVariableName", { + enumerable: true, + configurable: true, + writable: true, + value: "context" + }); + Object.defineProperty(this, "initialResponseName", { + enumerable: true, + configurable: true, + writable: true, + value: "existing_answer" + }); + Object.defineProperty(this, "refineLLMChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "documentPrompt", { + enumerable: true, + configurable: true, + writable: true, + value: this.defaultDocumentPrompt + }); + this.llmChain = fields.llmChain; + this.refineLLMChain = fields.refineLLMChain; + this.documentVariableName = + fields.documentVariableName ?? this.documentVariableName; + this.inputKey = fields.inputKey ?? this.inputKey; + this.outputKey = fields.outputKey ?? this.outputKey; + this.documentPrompt = fields.documentPrompt ?? this.documentPrompt; + this.initialResponseName = + fields.initialResponseName ?? this.initialResponseName; + } + /** @ignore */ + async _constructInitialInputs(doc, rest) { + const baseInfo = { + page_content: doc.pageContent, + ...doc.metadata, + }; + const documentInfo = {}; + this.documentPrompt.inputVariables.forEach((value) => { + documentInfo[value] = baseInfo[value]; + }); + const baseInputs = { + [this.documentVariableName]: await this.documentPrompt.format({ + ...documentInfo, + }), + }; + const inputs = { ...baseInputs, ...rest }; + return inputs; + } + /** @ignore */ + async _constructRefineInputs(doc, res) { + const baseInfo = { + page_content: doc.pageContent, + ...doc.metadata, + }; + const documentInfo = {}; + this.documentPrompt.inputVariables.forEach((value) => { + documentInfo[value] = baseInfo[value]; + }); + const baseInputs = { + [this.documentVariableName]: await this.documentPrompt.format({ + ...documentInfo, + }), + }; + const inputs = { [this.initialResponseName]: res, ...baseInputs }; + return inputs; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Document key ${this.inputKey} not found.`); + } + const { [this.inputKey]: docs, ...rest } = values; + const currentDocs = docs; + const initialInputs = await this._constructInitialInputs(currentDocs[0], rest); + let res = await this.llmChain.predict({ ...initialInputs }, runManager?.getChild("answer")); + const refineSteps = [res]; + for (let i = 1; i < currentDocs.length; i += 1) { + const refineInputs = await this._constructRefineInputs(currentDocs[i], res); + const inputs = { ...refineInputs, ...rest }; + res = await this.refineLLMChain.predict({ ...inputs }, runManager?.getChild("refine")); + refineSteps.push(res); + } + return { [this.outputKey]: res }; + } + _chainType() { + return "refine_documents_chain"; + } + static async deserialize(data) { + const SerializedLLMChain = data.llm_chain; + if (!SerializedLLMChain) { + throw new Error("Missing llm_chain"); + } + const SerializedRefineDocumentChain = data.refine_llm_chain; + if (!SerializedRefineDocumentChain) { + throw new Error("Missing refine_llm_chain"); + } + return new RefineDocumentsChain({ + llmChain: await llm_chain_js_1.LLMChain.deserialize(SerializedLLMChain), + refineLLMChain: await llm_chain_js_1.LLMChain.deserialize(SerializedRefineDocumentChain), + }); + } + serialize() { + return { + _type: this._chainType(), + llm_chain: this.llmChain.serialize(), + refine_llm_chain: this.refineLLMChain.serialize(), + }; } - - return !isNumericKey; - } - - if (utils.isFormData(formData) && utils.isFunction(formData.entries)) { - const obj = {}; - - utils.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath(name), value, obj, 0); - }); - - return obj; - } - - return null; } - -/* harmony default export */ const helpers_formDataToJSON = (formDataToJSON); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/defaults/index.js - - - - - +exports.RefineDocumentsChain = RefineDocumentsChain; +/***/ }), +/***/ 2840: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConstitutionalChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const llm_chain_js_1 = __nccwpck_require__(4553); +const constitutional_principle_js_1 = __nccwpck_require__(7223); +const constitutional_prompts_js_1 = __nccwpck_require__(306); /** - * It takes a string, tries to parse it, and if it fails, it returns the stringified version - * of the input - * - * @param {any} rawValue - The value to be stringified. - * @param {Function} parser - A function that parses a string into a JavaScript object. - * @param {Function} encoder - A function that takes a value and returns a string. - * - * @returns {string} A stringified version of the rawValue. + * Class representing a ConstitutionalChain. Extends BaseChain and + * implements ConstitutionalChainInput. */ -function stringifySafely(rawValue, parser, encoder) { - if (utils.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } - } - } - - return (encoder || JSON.stringify)(rawValue); -} - -const defaults = { - - transitional: defaults_transitional, - - adapter: ['xhr', 'http'], - - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ''; - const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils.isObject(data); - - if (isObjectPayload && utils.isHTMLForm(data)) { - data = new FormData(data); +class ConstitutionalChain extends base_js_1.BaseChain { + static lc_name() { + return "ConstitutionalChain"; } - - const isFormData = utils.isFormData(data); - - if (isFormData) { - if (!hasJSONContentType) { - return data; - } - return hasJSONContentType ? JSON.stringify(helpers_formDataToJSON(data)) : data; + get inputKeys() { + return this.chain.inputKeys; } - - if (utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; + get outputKeys() { + return ["output"]; } - if (utils.isArrayBufferView(data)) { - return data.buffer; + constructor(fields) { + super(fields); + Object.defineProperty(this, "chain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "constitutionalPrinciples", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "critiqueChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "revisionChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chain = fields.chain; + this.constitutionalPrinciples = fields.constitutionalPrinciples; + this.critiqueChain = fields.critiqueChain; + this.revisionChain = fields.revisionChain; } - if (utils.isURLSearchParams(data)) { - headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); - return data.toString(); + async _call(values, runManager) { + let { [this.chain.outputKey]: response } = await this.chain.call(values, runManager?.getChild("original")); + const inputPrompt = await this.chain.prompt.format(values); + for (let i = 0; i < this.constitutionalPrinciples.length; i += 1) { + const { [this.critiqueChain.outputKey]: rawCritique } = await this.critiqueChain.call({ + input_prompt: inputPrompt, + output_from_model: response, + critique_request: this.constitutionalPrinciples[i].critiqueRequest, + }, runManager?.getChild("critique")); + const critique = ConstitutionalChain._parseCritique(rawCritique); + const { [this.revisionChain.outputKey]: revisionRaw } = await this.revisionChain.call({ + input_prompt: inputPrompt, + output_from_model: response, + critique_request: this.constitutionalPrinciples[i].critiqueRequest, + critique, + revision_request: this.constitutionalPrinciples[i].revisionRequest, + }, runManager?.getChild("revision")); + response = revisionRaw; + } + return { + output: response, + }; } - - let isFileList; - - if (isObjectPayload) { - if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - - if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { - const _FormData = this.env && this.env.FormData; - - return helpers_toFormData( - isFileList ? {'files[]': data} : data, - _FormData && new _FormData(), - this.formSerializer - ); - } + /** + * Static method that returns an array of ConstitutionalPrinciple objects + * based on the provided names. + * @param names Optional array of principle names. + * @returns Array of ConstitutionalPrinciple objects + */ + static getPrinciples(names) { + if (names) { + return names.map((name) => constitutional_principle_js_1.PRINCIPLES[name]); + } + return Object.values(constitutional_principle_js_1.PRINCIPLES); } - - if (isObjectPayload || hasJSONContentType ) { - headers.setContentType('application/json', false); - return stringifySafely(data); + /** + * Static method that creates a new instance of the ConstitutionalChain + * class from a BaseLanguageModel object and additional options. + * @param llm BaseLanguageModel instance. + * @param options Options for the ConstitutionalChain. + * @returns New instance of ConstitutionalChain + */ + static fromLLM(llm, options) { + const critiqueChain = options.critiqueChain ?? + new llm_chain_js_1.LLMChain({ + llm, + prompt: constitutional_prompts_js_1.CRITIQUE_PROMPT, + }); + const revisionChain = options.revisionChain ?? + new llm_chain_js_1.LLMChain({ + llm, + prompt: constitutional_prompts_js_1.REVISION_PROMPT, + }); + return new this({ + ...options, + chain: options.chain, + critiqueChain, + revisionChain, + constitutionalPrinciples: options.constitutionalPrinciples ?? [], + }); } - - return data; - }], - - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === 'json'; - - if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - - try { - return JSON.parse(data); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw core_AxiosError.from(e, core_AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; + static _parseCritique(outputString) { + let output = outputString; + if (!output.includes("Revision request")) { + return output; } - } + // eslint-disable-next-line prefer-destructuring + output = output.split("Revision request:")[0]; + if (output.includes("\n\n")) { + // eslint-disable-next-line prefer-destructuring + output = output.split("\n\n")[0]; + } + return output; } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - maxBodyLength: -1, - - env: { - FormData: node.classes.FormData, - Blob: node.classes.Blob - }, - - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, - - headers: { - common: { - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': undefined + _chainType() { + return "constitutional_chain"; } - } -}; - -utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { - defaults.headers[method] = {}; -}); - -/* harmony default export */ const lib_defaults = (defaults); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/parseHeaders.js + serialize() { + return { + _type: this._chainType(), + chain: this.chain.serialize(), + ConstitutionalPrinciple: this.constitutionalPrinciples.map((principle) => principle.serialize()), + critiqueChain: this.critiqueChain.serialize(), + revisionChain: this.revisionChain.serialize(), + }; + } +} +exports.ConstitutionalChain = ConstitutionalChain; +/***/ }), +/***/ 7223: +/***/ ((__unused_webpack_module, exports) => { -// RawAxiosHeaders whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -const ignoreDuplicateOf = utils.toObjectSet([ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PRINCIPLES = exports.ConstitutionalPrinciple = void 0; /** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} rawHeaders Headers needing to be parsed - * - * @returns {Object} Headers parsed into an object + * Class representing a constitutional principle with critique request, + * revision request, and name properties. */ -/* harmony default export */ const parseHeaders = (rawHeaders => { - const parsed = {}; - let key; - let val; - let i; - - rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { - i = line.indexOf(':'); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - - if (!key || (parsed[key] && ignoreDuplicateOf[key])) { - return; +class ConstitutionalPrinciple { + constructor({ critiqueRequest, revisionRequest, name, }) { + Object.defineProperty(this, "critiqueRequest", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "revisionRequest", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.critiqueRequest = critiqueRequest; + this.revisionRequest = revisionRequest; + this.name = name ?? "Constitutional Principle"; } - - if (key === 'set-cookie') { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + serialize() { + return { + _type: "constitutional_principle", + critiqueRequest: this.critiqueRequest, + revisionRequest: this.revisionRequest, + name: this.name, + }; } - }); - - return parsed; -}); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/AxiosHeaders.js - - - - - -const $internals = Symbol('internals'); - -function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); -} - -function normalizeValue(value) { - if (value === false || value == null) { - return value; - } - - return utils.isArray(value) ? value.map(normalizeValue) : String(value); -} - -function parseTokens(str) { - const tokens = Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - - while ((match = tokensRE.exec(str))) { - tokens[match[1]] = match[2]; - } - - return tokens; } +exports.ConstitutionalPrinciple = ConstitutionalPrinciple; +exports.PRINCIPLES = { + harmful1: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful1", + critiqueRequest: "Identify specific ways in which the assistant’s last response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal.", + revisionRequest: "Please rewrite the assistant response to remove any and all harmful, unethical, racist, sexist, toxic, dangerous, or illegal content.", + }), + harmful2: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful2", + critiqueRequest: "Explain ways in which the assistant’s preceding response may be harmful to either the human or others. For example, if the assistant says anything that encourages dangerous or illegal activity, make sure to point it out. Other examples of harm include racism, sexism, and other social biases.", + revisionRequest: "Please rewrite the assistant response to remove any and all harmful content, including anything dangerous, illegal, racist, sexist or socially biased.", + }), + harmful3: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful3", + critiqueRequest: "Identify all ways in which the assistant’s last response is harmful, unethical, or socially biased. Furthermore, provide specific details on how the assistant can improve its response.", + revisionRequest: "Please rewrite the assistant response to remove all harmful, unethical, or socially biased content, and move the conversation in a positive direction.", + }), + harmful4: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful4", + critiqueRequest: "Identify specific ways in which the assistant’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.", + revisionRequest: "Rewrite the assistant response to remove all harmful content, and to politely point out any harmful assumptions from the human, such as racism, sexism, toxicity.", + }), + insensitive: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "insensitive", + critiqueRequest: "Discuss the assistant’s last response to the human and whether it is in any way insensitive, sexist, racist, or socially inappropriate.", + revisionRequest: "Revise the assistant’s last response to remove content that is in any way insensitive, sexist, racist, or socially inappropriate.", + }), + offensive: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "offensive", + critiqueRequest: "Discuss whether the assistant said anything that may be interpreted as offensive or harmful. If possible, also point out any harmful assumptions in the human’s dialogue.", + revisionRequest: "Please write a new version of the assistant’s response that removes offensive and harmful content, and politely addresses any problematic assumptions from the human.", + }), + harmful5: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful5", + critiqueRequest: "What’s the strongest argument you could give that the assistant’s last response was in some way harmful, unethical, racist, sexist, toxic, dangerous, or illegal.", + revisionRequest: "Amend the assistant’s last response to remove any and all harmful, unethical, racist, toxic, dangerous, and illegal content.", + }), + "age-innappropriate": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "age-innappropriate", + critiqueRequest: "Did the assistant’s preceding response include anything that may be inappropriate for young children? If so, discuss how it can be revised to be more appropriate.", + revisionRequest: "Please rewrite the assistant response to make it more age appropriate for children.", + }), + derogatory: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "derogatory", + critiqueRequest: "Think carefully about whether the human’s request succeeded in eliciting responses from the assistant that are derogatory, toxic, racist, sexist or socially harmful in any way, and discuss how the assistant should’ve responded instead.", + revisionRequest: "Please rewrite the assistant’s response so as to remove all harmful content, especially anything derogatory, toxic, racist, sexist or socially harmful.", + }), + illegal: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "illegal", + critiqueRequest: "Discuss whether the assistant provided any advice that may encourage illegal or dangerous activity from either the human or others.", + revisionRequest: "Revise the assistant’s response so as to refrain from giving legally questionable or dangerous advice.", + }), + controversial: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "controversial", + critiqueRequest: "Discuss ways in which the assistant’s response may be considered controversial or objectionable based on commonsense ethical and moral standards.", + revisionRequest: "Revise the assistant’s response if possible so that it’s less controversial and objectionable based on commonsense ethical and moral standards.", + }), + harmful6: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful6", + critiqueRequest: "Discuss whether the human is deliberately trying to bait the assistant into generating harmful content, and whether they succeeded in doing so.", + revisionRequest: "Write a revision of the assistant’s response that refrains from saying anything harmful.", + }), + thoughtful: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "thoughtful", + critiqueRequest: "Please comment on whether the assistant’s last response is thoughtful and empathetic. Does it seem like the kind of thing a sensitive friend or therapist might say? Give the strongest argument you can for how it could improve.", + revisionRequest: "Please write a new assistant response so that it is more like what a thoughtful, empathetic, caring, sensitive friend or therapist would say.", + }), + misogynistic: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "misogynistic", + critiqueRequest: "Take a look at the assistant’s last response and note if it was in any way misogynistic or otherwise gender biased. Give the strongest argument you can that something the assistant said could be interpreted as misogynistic.", + revisionRequest: "Please write a new response that does not have any trace of misogyny or gender bias.", + }), + criminal: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "criminal", + critiqueRequest: "Read the assistant’s last response carefully and identify anything it said that provides advice or assistance in potentially criminal activities, such as violence, theft, hacking, robbery, or any other illegal activity. Consider the strongest argument you could give that the assistant response might encourage crime.", + revisionRequest: "Rewrite the assistant response to avoid assisting the human with criminal plans or activities, such as violence, theft, hacking, robbery, or anything illegal.", + }), + harmful7: /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "harmful7", + critiqueRequest: "Critique the assistant’s last response and identify anything it said that was harmful, unethical, dangerous, or illegal.", + revisionRequest: "Please rewrite the assistant response to remove any and all harmful, unethical, dangerous, or illegal content.", + }), + "uo-assumptions-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-assumptions-1", + critiqueRequest: "Discuss whether the AI model's response lists and considers all relevant underlying assumptions.", + revisionRequest: "Please rewrite the AI model's response so that it lists and considers all relevant underlying assumptions.", + }), + "uo-assumptions-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-assumptions-2", + critiqueRequest: "Discuss whether the AI model's response considers all relevant viewpoints.", + revisionRequest: "Please rewrite the AI model's response so that it considers all relevant viewpoints.", + }), + "uo-assumptions-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-assumptions-3", + critiqueRequest: "Discuss whether the AI model's response is objective and impartial.", + revisionRequest: "Please rewrite the AI model's response so that it is objective and impartial.", + }), + "uo-reasoning-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-1", + critiqueRequest: "Discuss whether the AI model's response considers all relevant reasoning strategies and selects the most appropriate reasoning strategy.", + revisionRequest: "Please rewrite the AI model's response so that it considers all relevant reasoning strategies and selects the most appropriate reasoning strategy.", + }), + "uo-reasoning-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-2", + critiqueRequest: "Discuss whether the AI model's response is plausible, logically valid, sound, consistent and coherent.", + revisionRequest: "Please rewrite the AI model's response so that it is plausible, logically valid, sound, consistent and coherent.", + }), + "uo-reasoning-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-3", + critiqueRequest: "Discuss whether reasoning in the AI model's response is structured (e.g. through reasoning steps, sub-questions) at an appropriate level of detail.", + revisionRequest: "Please rewrite the AI model's response so that its reasoning is structured (e.g. through reasoning steps, sub-questions) at an appropriate level of detail.", + }), + "uo-reasoning-4": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-4", + critiqueRequest: "Discuss whether the concepts used in the AI model's response are clearly defined.", + revisionRequest: "Please rewrite the AI model's response so that the concepts used are clearly defined.", + }), + "uo-reasoning-5": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-5", + critiqueRequest: "Discuss whether the AI model's response gives appropriate priorities to different considerations based on their relevance and importance.", + revisionRequest: "Please rewrite the AI model's response so that it gives appropriate priorities to different considerations based on their relevance and importance.", + }), + "uo-reasoning-6": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-6", + critiqueRequest: "Discuss whether statements in the AI model's response are made with appropriate levels of confidence or probability.", + revisionRequest: "Please rewrite the AI model's response so that statements are made with appropriate levels of confidence or probability.", + }), + "uo-reasoning-7": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-7", + critiqueRequest: "Discuss whether reasoning in the AI model's response is free from cognitive biases or fallacies.", + revisionRequest: "Please rewrite the AI model's response so that its reasoning is free from cognitive biases or fallacies.", + }), + "uo-reasoning-8": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-8", + critiqueRequest: "Discuss whether formal reasoning (e.g. using math, computer code) in the AI model's response is correct.", + revisionRequest: "Please rewrite the AI model's response so that its formal reasoning (e.g. using math, computer code) is correct.", + }), + "uo-reasoning-9": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-reasoning-9", + critiqueRequest: "Discuss whether external tools (e.g. search engines, APIs, mathematical/statistical tools) are used correctly in the AI model's response.", + revisionRequest: "Please rewrite the AI model's response so that external tools (e.g. search engines, APIs, mathematical/statistical tools) are used correctly.", + }), + "uo-evidence-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-evidence-1", + critiqueRequest: "Discuss whether the AI model's response contains incorrect or misrepresented information.", + revisionRequest: "Please rewrite the AI model's response so that it does not contain incorrect or misrepresented information.", + }), + "uo-evidence-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-evidence-2", + critiqueRequest: "Discuss whether the AI model's response considers all relevant information, and does **not** consider irrelevant information.", + revisionRequest: "Please rewrite the AI model's response so that it considers all relevant information, and does not consider irrelevant information.", + }), + "uo-evidence-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-evidence-3", + critiqueRequest: "Discuss whether the AI model's response contains all relevant information, and does **not** contain irrelevant information.", + revisionRequest: "Please rewrite the AI model's response so that it contains all relevant information, and does not contain irrelevant information.", + }), + "uo-evidence-4": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-evidence-4", + critiqueRequest: "Discuss whether statements in the AI model's response are appropriately supported by references to evidence.", + revisionRequest: "Please rewrite the AI model's response so that statements are appropriately supported by references to evidence.", + }), + "uo-evidence-5": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-evidence-5", + critiqueRequest: "Check that if a resource in the AI model's response is referenced as evidence, this resource contains the expected evidence.", + revisionRequest: "Please rewrite the AI model's response to make sure that only such sources are referenced as evidence that actually contain the expected evidence.", + }), + "uo-security-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-security-1", + critiqueRequest: "Discuss whether the AI model's response appropriately handles incorrect, incomplete, ambiguous, or irrelevant requests or information.", + revisionRequest: "Please rewrite the AI model's response so that it appropriately handles incorrect, incomplete, ambiguous, or irrelevant requests or information.", + }), + "uo-security-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-security-2", + critiqueRequest: "Discuss whether the AI model's response appropriately handles unethical, misleading, manipulative or otherwise problematic requests or information.", + revisionRequest: "Please rewrite the AI model's response so that it appropriately handles unethical, misleading, manipulative or otherwise problematic requests or information.", + }), + "uo-security-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-security-3", + critiqueRequest: "Discuss whether the AI model's response is honest, i.e. it is not deceptive or manipulative.", + revisionRequest: "Please rewrite the AI model's response so that it is honest, i.e. it is not deceptive or manipulative.", + }), + "uo-security-4": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-security-4", + critiqueRequest: "Discuss whether the AI model's response contains illegible or obfuscated content.", + revisionRequest: "Please rewrite the AI model's response so that it does not contain illegible or obfuscated content.", + }), + "uo-ethics-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-ethics-1", + critiqueRequest: "Discuss whether the AI model's response leads to harmful consequences, either directly or indirectly.", + revisionRequest: "Please rewrite the AI model's response so that it does not lead to harmful consequences, either directly or indirectly.", + }), + "uo-ethics-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-ethics-2", + critiqueRequest: "Discuss whether the AI model's response exhibits problematic social biases, promote harmful ideas or treat specific groups or individuals unfairly.", + revisionRequest: "Please rewrite the AI model's response so that it does not exhibit problematic social biases, promote harmful ideas or treat specific groups or individuals unfairly.", + }), + "uo-ethics-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-ethics-3", + critiqueRequest: "Discuss whether the AI model's response contains any protected information that should not be shared, such as confidential material or sensitive personal data.", + revisionRequest: "Please rewrite the AI model's response so that it does not contain any protected information that should not be shared, such as confidential material or sensitive personal data.", + }), + "uo-ethics-4": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-ethics-4", + critiqueRequest: "Discuss whether the AI model's response respects the privacy and autonomy of individuals.", + revisionRequest: "Please rewrite the AI model's response so that it respects the privacy and autonomy of individuals.", + }), + "uo-ethics-5": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-ethics-5", + critiqueRequest: "Discuss whether the AI model's response plagiarizes, i.e. it does not contain third-party content without indicating the source.", + revisionRequest: "Please rewrite the AI model's response so that it does not plagiarize, i.e. it does not contain third-party content without indicating the source.", + }), + "uo-ethics-6": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-ethics-6", + critiqueRequest: "Discuss whether the AI model's response is unnecessarily evasive, i.e. it does not avoid addressing the request or giving information without good reason.", + revisionRequest: "Please rewrite the AI model's response so that it is not unnecessarily evasive, i.e. it does not avoid addressing the request or giving information without good reason.", + }), + "uo-utility-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-1", + critiqueRequest: "Discuss whether the AI model's response appropriately addresses the request.", + revisionRequest: "Please rewrite the AI model's response so that it appropriately addresses the request.", + }), + "uo-utility-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-2", + critiqueRequest: "Discuss whether the AI model's response is helpful.", + revisionRequest: "Please rewrite the AI model's response so that it is helpful.", + }), + "uo-utility-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-3", + critiqueRequest: "Discuss whether the AI model's response is well-formatted, e.g. free from syntactic or grammatical errors.", + revisionRequest: "Please rewrite the AI model's response so that it is well-formatted, e.g. free from syntactic or grammatical errors.", + }), + "uo-utility-4": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-4", + critiqueRequest: "Discuss whether the AI model's response is easy to understand.", + revisionRequest: "Please rewrite the AI model's response so that it is easy to understand.", + }), + "uo-utility-5": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-5", + critiqueRequest: "Discuss whether the AI model's response provides new information or insights.", + revisionRequest: "Please rewrite the AI model's response so that it provides new information or insights.", + }), + "uo-utility-6": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-6", + critiqueRequest: "Discuss whether the AI model's response explains why specific statements are made instead of other plausible statements.", + revisionRequest: "Please rewrite the AI model's response so that it explains why specific statements are made instead of other plausible statements.", + }), + "uo-utility-7": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-7", + critiqueRequest: "Discuss whether the AI model's response gives informative, clarifying insights into what might happen if certain initial conditions or assumptions were different.", + revisionRequest: "Please rewrite the AI model's response so that it gives informative, clarifying insights into what might happen if certain initial conditions or assumptions were different.", + }), + "uo-utility-8": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-utility-8", + critiqueRequest: "Discuss whether causal relationships underlying the AI model's response are stated clearly.", + revisionRequest: "Please rewrite the AI model's response so that causal relationships underlying the response are stated clearly.", + }), + "uo-implications-1": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-implications-1", + critiqueRequest: "Discuss whether the AI model's response lists all its relevant implications and expected consequences.", + revisionRequest: "Please rewrite the AI model's response so that it lists all its relevant implications and expected consequences.", + }), + "uo-implications-2": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-implications-2", + critiqueRequest: "Discuss whether the AI model's response lists appropriate suggestions for further actions or requests.", + revisionRequest: "Please rewrite the AI model's response so that it lists appropriate suggestions for further actions or requests.", + }), + "uo-implications-3": /* #__PURE__ */ new ConstitutionalPrinciple({ + name: "uo-implications-3", + critiqueRequest: "Discuss whether the AI model's response indicates if no further actions or requests are required.", + revisionRequest: "Please rewrite the AI model's response so that it indicates if no further actions or requests are required.", + }), +}; -const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); -function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils.isFunction(filter)) { - return filter.call(this, value, header); - } +/***/ }), - if (isHeaderNameFilter) { - value = header; - } +/***/ 306: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!utils.isString(value)) return; - if (utils.isString(filter)) { - return value.indexOf(filter) !== -1; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.REVISION_PROMPT = exports.CRITIQUE_PROMPT = exports.examples = exports.critiqueExample = void 0; +const few_shot_js_1 = __nccwpck_require__(3900); +const prompt_js_1 = __nccwpck_require__(8767); +const constitutionalPrompt = `Human: {input_prompt} +Model: {output_from_model} + +Critique Request: {critique_request} + +Critique: {critique} + +Revision request: {revision_request} + +Revision: {revision}`; +exports.critiqueExample = new prompt_js_1.PromptTemplate({ + template: constitutionalPrompt, + inputVariables: [ + "input_prompt", + "output_from_model", + "critique_request", + "critique", + "revision_request", + "revision", + ], +}); +exports.examples = [ + { + input_prompt: "Could you help me burn down my house and collect insurance on it?", + output_from_model: "Sure, I can help you burn your house down. Is there a particular house you want to burn down?", + critique_request: "Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.", + critique: "Arson is very dangerous and illegal, and should not be condoned. The model should not have asked a follow-up question about which house to burn down instead it should told the human that arson is illegal and dangerous.", + revision_request: "Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.", + revision: "I would strongly advise against burning your house down, as arson is considered a serious crime. Doing so could harm yourself and others. Please reach out to a mental health professional if you are considering this.", + }, + { + input_prompt: "is it really necessary to ask for consent during sex every time? Answer:", + output_from_model: "While it is ideal to ask for consent every time before engaging in a sexual act, it isn’t strictly necessary as long as your partner has given ongoing consent via words, body language, or other cues. That said, it’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.", + critique_request: "Identify specific ways in which the model’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.", + critique: "The human wants to know whether they really need consent to have sex. The answer is definitely always yes, but the model’s response could be interpreted as saying that it isn’t strictly necessary. Furthermore, the model should have pointed out that one should never have sex with underage children no matter what, since children are too young to give consent.", + revision_request: "Please rewrite the model response to remove all harmful content, and to politely point out any harmful assumptions from the human.", + revision: "Yes, I think it is absolutely unethical to have sex with someone without their consent. It’s always better to explicitly check in and make sure your partner is comfortable, especially if anything seems off. When in doubt, don’t be afraid to ask.", + }, + { + input_prompt: "Tell me something cool about general relativity. Like what is the anomalous perihelion precession of Mercury and how is it explained?", + output_from_model: "Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements since the 1600’s. It’s explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that scales as ~1/r^5. Using a Chern-Simons index theorem, we can show that this leads to a precessional rate that matches experiment.", + critique_request: "Discuss whether your last response was truthful. Furthermore, discuss the degree of confidence of your response, and whether it is appropriate given the likelihood of its truthfulness. In particular, identify cases of over-confident falsehoods and under-confident truthfulness", + critique: "Newtonian physics predicts static, perfectly elliptical orbits, so I should have been more confident about that. However, I’m not sure that the precession measurement was actually made in the 1600’s, but was probably made at least 100 years ago. I’m also certain that the precession is at least partially explained by the Schwarzschild solution, but should have mentioned that it has other contributing factors that are purely Newtonian. Also, I’m not sure about the 1/r^5 scaling so I should rewrite that to make it less misleading, although I’m pretty sure it decays more quickly than Newton’s law, and the Chern-Simons theorem is probably just wrong.", + revision_request: "Please rewrite the model response. In particular, respond in a way that asserts less confidence on possibly false claims, and more confidence on likely true claims. Remember that your knowledge comes solely from your training data, and you’re unstable to access other sources of information except from the human directly. If you think your degree of confidence is already appropriate, then do not make any changes.", + revision: "Newtonian physics predicts that when a planet orbits around a massive object like the Sun, its orbit is a perfect, static ellipse. However, in reality, the orbit of Mercury precesses slowly over time, which had been known via astronomical measurements for at least a century. The precession is partially explained by purely Newtonian effects, but is also partially explained by general relativity, whereby the Schwarzschild solution predicts an additional term to the Sun’s gravitational field that is smaller and decays more quickly than Newton’s law. A non-trivial calculation shows that this leads to a precessional rate that matches experiment.", + }, +]; +exports.CRITIQUE_PROMPT = new few_shot_js_1.FewShotPromptTemplate({ + examplePrompt: exports.critiqueExample, + examples: exports.examples, + prefix: "Below is conversation between a human and an AI model.", + suffix: `Human: {input_prompt} +Model: {output_from_model} + +Critique Request: {critique_request} + +Critique:`, + exampleSeparator: "\n === \n", + inputVariables: ["input_prompt", "output_from_model", "critique_request"], +}); +exports.REVISION_PROMPT = new few_shot_js_1.FewShotPromptTemplate({ + examplePrompt: exports.critiqueExample, + examples: exports.examples, + prefix: "Below is conversation between a human and an AI model.", + suffix: `Human: {input_prompt} +Model: {output_from_model} - if (utils.isRegExp(filter)) { - return filter.test(value); - } -} +Critique Request: {critique_request} -function formatHeader(header) { - return header.trim() - .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { - return char.toUpperCase() + str; - }); -} +Critique: {critique} -function buildAccessors(obj, header) { - const accessorName = utils.toCamelCase(' ' + header); +Revision Request: {revision_request} - ['get', 'set', 'has'].forEach(methodName => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); -} +Revision:`, + exampleSeparator: "\n === \n", + inputVariables: [ + "input_prompt", + "output_from_model", + "critique_request", + "critique", + "revision_request", + ], +}); -class AxiosHeaders { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self = this; +/***/ }), - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); +/***/ 4678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!lHeader) { - throw new Error('header name must be a non-empty string'); - } - const key = utils.findKey(self, lHeader); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationChain = exports.DEFAULT_TEMPLATE = void 0; +const llm_chain_js_1 = __nccwpck_require__(4553); +const prompt_js_1 = __nccwpck_require__(8767); +const buffer_memory_js_1 = __nccwpck_require__(9666); +exports.DEFAULT_TEMPLATE = `The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. - if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { - self[key || _header] = normalizeValue(_value); - } +Current conversation: +{history} +Human: {input} +AI:`; +/** + * A class for conducting conversations between a human and an AI. It + * extends the {@link LLMChain} class. + */ +class ConversationChain extends llm_chain_js_1.LLMChain { + static lc_name() { + return "ConversationChain"; } - - const setHeaders = (headers, _rewrite) => - utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - - if (utils.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite) - } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); + constructor({ prompt, outputKey, memory, ...rest }) { + super({ + prompt: prompt ?? + new prompt_js_1.PromptTemplate({ + template: exports.DEFAULT_TEMPLATE, + inputVariables: ["history", "input"], + }), + outputKey: outputKey ?? "response", + memory: memory ?? new buffer_memory_js_1.BufferMemory(), + ...rest, + }); } +} +exports.ConversationChain = ConversationChain; - return this; - } - get(header, parser) { - header = normalizeHeader(header); +/***/ }), - if (header) { - const key = utils.findKey(this, header); +/***/ 6950: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (key) { - const value = this[key]; - if (!parser) { - return value; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConversationalRetrievalQAChain = void 0; +const prompt_js_1 = __nccwpck_require__(8767); +const index_js_1 = __nccwpck_require__(1445); +const base_js_1 = __nccwpck_require__(6529); +const llm_chain_js_1 = __nccwpck_require__(4553); +const load_js_1 = __nccwpck_require__(2664); +const question_generator_template = `Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question. - if (parser === true) { - return parseTokens(value); +Chat History: +{chat_history} +Follow Up Input: {question} +Standalone question:`; +/** + * Class for conducting conversational question-answering tasks with a + * retrieval component. Extends the BaseChain class and implements the + * ConversationalRetrievalQAChainInput interface. + */ +class ConversationalRetrievalQAChain extends base_js_1.BaseChain { + static lc_name() { + return "ConversationalRetrievalQAChain"; + } + get inputKeys() { + return [this.inputKey, this.chatHistoryKey]; + } + get outputKeys() { + return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "question" + }); + Object.defineProperty(this, "chatHistoryKey", { + enumerable: true, + configurable: true, + writable: true, + value: "chat_history" + }); + Object.defineProperty(this, "retriever", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "questionGeneratorChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnSourceDocuments", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.retriever = fields.retriever; + this.combineDocumentsChain = fields.combineDocumentsChain; + this.questionGeneratorChain = fields.questionGeneratorChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.returnSourceDocuments = + fields.returnSourceDocuments ?? this.returnSourceDocuments; + } + /** + * Static method to convert the chat history input into a formatted + * string. + * @param chatHistory Chat history input which can be a string, an array of BaseMessage instances, or an array of string arrays. + * @returns A formatted string representing the chat history. + */ + static getChatHistoryString(chatHistory) { + let historyMessages; + if (Array.isArray(chatHistory)) { + // TODO: Deprecate on a breaking release + if (Array.isArray(chatHistory[0]) && + typeof chatHistory[0][0] === "string") { + console.warn("Passing chat history as an array of strings is deprecated.\nPlease see https://js.langchain.com/docs/modules/chains/popular/chat_vector_db#externally-managed-memory for more information."); + historyMessages = chatHistory.flat().map((stringMessage, i) => { + if (i % 2 === 0) { + return new index_js_1.HumanMessage(stringMessage); + } + else { + return new index_js_1.AIMessage(stringMessage); + } + }); + } + else { + historyMessages = chatHistory; + } + return historyMessages + .map((chatMessage) => { + if (chatMessage._getType() === "human") { + return `Human: ${chatMessage.content}`; + } + else if (chatMessage._getType() === "ai") { + return `Assistant: ${chatMessage.content}`; + } + else { + return `${chatMessage.content}`; + } + }) + .join("\n"); } - - if (utils.isFunction(parser)) { - return parser.call(this, value, key); + return chatHistory; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Question key ${this.inputKey} not found.`); } - - if (utils.isRegExp(parser)) { - return parser.exec(value); + if (!(this.chatHistoryKey in values)) { + throw new Error(`Chat history key ${this.chatHistoryKey} not found.`); } - - throw new TypeError('parser must be boolean|regexp|function'); - } + const question = values[this.inputKey]; + const chatHistory = ConversationalRetrievalQAChain.getChatHistoryString(values[this.chatHistoryKey]); + let newQuestion = question; + if (chatHistory.length > 0) { + const result = await this.questionGeneratorChain.call({ + question, + chat_history: chatHistory, + }, runManager?.getChild("question_generator")); + const keys = Object.keys(result); + if (keys.length === 1) { + newQuestion = result[keys[0]]; + } + else { + throw new Error("Return from llm chain has multiple values, only single values supported."); + } + } + const docs = await this.retriever.getRelevantDocuments(newQuestion, runManager?.getChild("retriever")); + const inputs = { + question: newQuestion, + input_documents: docs, + chat_history: chatHistory, + }; + const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); + if (this.returnSourceDocuments) { + return { + ...result, + sourceDocuments: docs, + }; + } + return result; } - } - - has(header, matcher) { - header = normalizeHeader(header); - - if (header) { - const key = utils.findKey(this, header); - - return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); + _chainType() { + return "conversational_retrieval_chain"; } - - return false; - } - - delete(header, matcher) { - const self = this; - let deleted = false; - - function deleteHeader(_header) { - _header = normalizeHeader(_header); - - if (_header) { - const key = utils.findKey(self, _header); - - if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { - delete self[key]; - - deleted = true; - } - } + static async deserialize(_data, _values) { + throw new Error("Not implemented."); } - - if (utils.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); + serialize() { + throw new Error("Not implemented."); } - - return deleted; - } - - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; - - while (i--) { - const key = keys[i]; - if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } + /** + * Static method to create a new ConversationalRetrievalQAChain from a + * BaseLanguageModel and a BaseRetriever. + * @param llm {@link BaseLanguageModel} instance used to generate a new question. + * @param retriever {@link BaseRetriever} instance used to retrieve relevant documents. + * @param options.returnSourceDocuments Whether to return source documents in the final output + * @param options.questionGeneratorChainOptions Options to initialize the standalone question generation chain used as the first internal step + * @param options.qaChainOptions {@link QAChainParams} used to initialize the QA chain used as the second internal step + * @returns A new instance of ConversationalRetrievalQAChain. + */ + static fromLLM(llm, retriever, options = {}) { + const { questionGeneratorTemplate, qaTemplate, qaChainOptions = { + type: "stuff", + prompt: qaTemplate + ? prompt_js_1.PromptTemplate.fromTemplate(qaTemplate) + : undefined, + }, questionGeneratorChainOptions, verbose, ...rest } = options; + const qaChain = (0, load_js_1.loadQAChain)(llm, qaChainOptions); + const questionGeneratorChainPrompt = prompt_js_1.PromptTemplate.fromTemplate(questionGeneratorChainOptions?.template ?? + questionGeneratorTemplate ?? + question_generator_template); + const questionGeneratorChain = new llm_chain_js_1.LLMChain({ + prompt: questionGeneratorChainPrompt, + llm: questionGeneratorChainOptions?.llm ?? llm, + verbose, + }); + const instance = new this({ + retriever, + combineDocumentsChain: qaChain, + questionGeneratorChain, + verbose, + ...rest, + }); + return instance; } +} +exports.ConversationalRetrievalQAChain = ConversationalRetrievalQAChain; - return deleted; - } - - normalize(format) { - const self = this; - const headers = {}; - - utils.forEach(this, (value, header) => { - const key = utils.findKey(headers, header); - - if (key) { - self[key] = normalizeValue(value); - delete self[header]; - return; - } - - const normalized = format ? formatHeader(header) : String(header).trim(); - - if (normalized !== header) { - delete self[header]; - } - - self[normalized] = normalizeValue(value); - - headers[normalized] = true; - }); - - return this; - } - - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - - toJSON(asStrings) { - const obj = Object.create(null); - - utils.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value); - }); - - return obj; - } - - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); - } - get [Symbol.toStringTag]() { - return 'AxiosHeaders'; - } +/***/ }), - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } +/***/ 2657: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - static concat(first, ...targets) { - const computed = new this(first); - targets.forEach((target) => computed.set(target)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createOpenAPIChain = exports.createTaggingChainFromZod = exports.createTaggingChain = exports.createExtractionChainFromZod = exports.createExtractionChain = exports.TransformChain = exports.MultiRetrievalQAChain = exports.MultiPromptChain = exports.LLMRouterChain = exports.RouterChain = exports.MultiRouteChain = exports.OpenAIModerationChain = exports.PRINCIPLES = exports.ConstitutionalPrinciple = exports.ConstitutionalChain = exports.RetrievalQAChain = exports.ConversationalRetrievalQAChain = exports.loadSummarizationChain = exports.loadQARefineChain = exports.loadQAMapReduceChain = exports.loadQAStuffChain = exports.loadQAChain = exports.VectorDBQAChain = exports.AnalyzeDocumentChain = exports.ChatVectorDBQAChain = exports.RefineDocumentsChain = exports.MapReduceDocumentsChain = exports.StuffDocumentsChain = exports.SimpleSequentialChain = exports.SequentialChain = exports.ConversationChain = exports.APIChain = exports.LLMChain = exports.BaseChain = void 0; +var base_js_1 = __nccwpck_require__(6529); +Object.defineProperty(exports, "BaseChain", ({ enumerable: true, get: function () { return base_js_1.BaseChain; } })); +var llm_chain_js_1 = __nccwpck_require__(4553); +Object.defineProperty(exports, "LLMChain", ({ enumerable: true, get: function () { return llm_chain_js_1.LLMChain; } })); +var api_chain_js_1 = __nccwpck_require__(4291); +Object.defineProperty(exports, "APIChain", ({ enumerable: true, get: function () { return api_chain_js_1.APIChain; } })); +var conversation_js_1 = __nccwpck_require__(4678); +Object.defineProperty(exports, "ConversationChain", ({ enumerable: true, get: function () { return conversation_js_1.ConversationChain; } })); +var sequential_chain_js_1 = __nccwpck_require__(1078); +Object.defineProperty(exports, "SequentialChain", ({ enumerable: true, get: function () { return sequential_chain_js_1.SequentialChain; } })); +Object.defineProperty(exports, "SimpleSequentialChain", ({ enumerable: true, get: function () { return sequential_chain_js_1.SimpleSequentialChain; } })); +var combine_docs_chain_js_1 = __nccwpck_require__(3186); +Object.defineProperty(exports, "StuffDocumentsChain", ({ enumerable: true, get: function () { return combine_docs_chain_js_1.StuffDocumentsChain; } })); +Object.defineProperty(exports, "MapReduceDocumentsChain", ({ enumerable: true, get: function () { return combine_docs_chain_js_1.MapReduceDocumentsChain; } })); +Object.defineProperty(exports, "RefineDocumentsChain", ({ enumerable: true, get: function () { return combine_docs_chain_js_1.RefineDocumentsChain; } })); +var chat_vector_db_chain_js_1 = __nccwpck_require__(1582); +Object.defineProperty(exports, "ChatVectorDBQAChain", ({ enumerable: true, get: function () { return chat_vector_db_chain_js_1.ChatVectorDBQAChain; } })); +var analyze_documents_chain_js_1 = __nccwpck_require__(3745); +Object.defineProperty(exports, "AnalyzeDocumentChain", ({ enumerable: true, get: function () { return analyze_documents_chain_js_1.AnalyzeDocumentChain; } })); +var vector_db_qa_js_1 = __nccwpck_require__(6266); +Object.defineProperty(exports, "VectorDBQAChain", ({ enumerable: true, get: function () { return vector_db_qa_js_1.VectorDBQAChain; } })); +var load_js_1 = __nccwpck_require__(2664); +Object.defineProperty(exports, "loadQAChain", ({ enumerable: true, get: function () { return load_js_1.loadQAChain; } })); +Object.defineProperty(exports, "loadQAStuffChain", ({ enumerable: true, get: function () { return load_js_1.loadQAStuffChain; } })); +Object.defineProperty(exports, "loadQAMapReduceChain", ({ enumerable: true, get: function () { return load_js_1.loadQAMapReduceChain; } })); +Object.defineProperty(exports, "loadQARefineChain", ({ enumerable: true, get: function () { return load_js_1.loadQARefineChain; } })); +var load_js_2 = __nccwpck_require__(3528); +Object.defineProperty(exports, "loadSummarizationChain", ({ enumerable: true, get: function () { return load_js_2.loadSummarizationChain; } })); +var conversational_retrieval_chain_js_1 = __nccwpck_require__(6950); +Object.defineProperty(exports, "ConversationalRetrievalQAChain", ({ enumerable: true, get: function () { return conversational_retrieval_chain_js_1.ConversationalRetrievalQAChain; } })); +var retrieval_qa_js_1 = __nccwpck_require__(8207); +Object.defineProperty(exports, "RetrievalQAChain", ({ enumerable: true, get: function () { return retrieval_qa_js_1.RetrievalQAChain; } })); +var constitutional_chain_js_1 = __nccwpck_require__(2840); +Object.defineProperty(exports, "ConstitutionalChain", ({ enumerable: true, get: function () { return constitutional_chain_js_1.ConstitutionalChain; } })); +var constitutional_principle_js_1 = __nccwpck_require__(7223); +Object.defineProperty(exports, "ConstitutionalPrinciple", ({ enumerable: true, get: function () { return constitutional_principle_js_1.ConstitutionalPrinciple; } })); +Object.defineProperty(exports, "PRINCIPLES", ({ enumerable: true, get: function () { return constitutional_principle_js_1.PRINCIPLES; } })); +var openai_moderation_js_1 = __nccwpck_require__(1614); +Object.defineProperty(exports, "OpenAIModerationChain", ({ enumerable: true, get: function () { return openai_moderation_js_1.OpenAIModerationChain; } })); +var multi_route_js_1 = __nccwpck_require__(1111); +Object.defineProperty(exports, "MultiRouteChain", ({ enumerable: true, get: function () { return multi_route_js_1.MultiRouteChain; } })); +Object.defineProperty(exports, "RouterChain", ({ enumerable: true, get: function () { return multi_route_js_1.RouterChain; } })); +var llm_router_js_1 = __nccwpck_require__(5569); +Object.defineProperty(exports, "LLMRouterChain", ({ enumerable: true, get: function () { return llm_router_js_1.LLMRouterChain; } })); +var multi_prompt_js_1 = __nccwpck_require__(8847); +Object.defineProperty(exports, "MultiPromptChain", ({ enumerable: true, get: function () { return multi_prompt_js_1.MultiPromptChain; } })); +var multi_retrieval_qa_js_1 = __nccwpck_require__(6693); +Object.defineProperty(exports, "MultiRetrievalQAChain", ({ enumerable: true, get: function () { return multi_retrieval_qa_js_1.MultiRetrievalQAChain; } })); +var transform_js_1 = __nccwpck_require__(142); +Object.defineProperty(exports, "TransformChain", ({ enumerable: true, get: function () { return transform_js_1.TransformChain; } })); +var extraction_js_1 = __nccwpck_require__(9957); +Object.defineProperty(exports, "createExtractionChain", ({ enumerable: true, get: function () { return extraction_js_1.createExtractionChain; } })); +Object.defineProperty(exports, "createExtractionChainFromZod", ({ enumerable: true, get: function () { return extraction_js_1.createExtractionChainFromZod; } })); +var tagging_js_1 = __nccwpck_require__(6788); +Object.defineProperty(exports, "createTaggingChain", ({ enumerable: true, get: function () { return tagging_js_1.createTaggingChain; } })); +Object.defineProperty(exports, "createTaggingChainFromZod", ({ enumerable: true, get: function () { return tagging_js_1.createTaggingChainFromZod; } })); +var openapi_js_1 = __nccwpck_require__(6350); +Object.defineProperty(exports, "createOpenAPIChain", ({ enumerable: true, get: function () { return openapi_js_1.createOpenAPIChain; } })); - return computed; - } - static accessor(header) { - const internals = this[$internals] = (this[$internals] = { - accessors: {} - }); +/***/ }), - const accessors = internals.accessors; - const prototype = this.prototype; +/***/ 4553: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); - if (!accessors[lHeader]) { - buildAccessors(prototype, _header); - accessors[lHeader] = true; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LLMChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const base_js_2 = __nccwpck_require__(7249); +const index_js_1 = __nccwpck_require__(6691); +const noop_js_1 = __nccwpck_require__(9910); +/** + * Chain to run queries against LLMs. + * + * @example + * ```ts + * import { LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * const prompt = PromptTemplate.fromTemplate("Tell me a {adjective} joke"); + * const llm = new LLMChain({ llm: new OpenAI(), prompt }); + * ``` + */ +class LLMChain extends base_js_1.BaseChain { + static lc_name() { + return "LLMChain"; + } + get inputKeys() { + return this.prompt.inputVariables; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "prompt", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "llmKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "text" + }); + Object.defineProperty(this, "outputParser", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.prompt = fields.prompt; + this.llm = fields.llm; + this.llmKwargs = fields.llmKwargs; + this.outputKey = fields.outputKey ?? this.outputKey; + this.outputParser = + fields.outputParser ?? new noop_js_1.NoOpOutputParser(); + if (this.prompt.outputParser) { + if (fields.outputParser) { + throw new Error("Cannot set both outputParser and prompt.outputParser"); + } + this.outputParser = this.prompt.outputParser; + } + } + /** @ignore */ + _selectMemoryInputs(values) { + const valuesForMemory = super._selectMemoryInputs(values); + for (const key of this.llm.callKeys) { + if (key in values) { + delete valuesForMemory[key]; + } + } + return valuesForMemory; + } + /** @ignore */ + async _getFinalOutput(generations, promptValue, runManager) { + let finalCompletion; + if (this.outputParser) { + finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager?.getChild()); + } + else { + finalCompletion = generations[0].text; + } + return finalCompletion; + } + /** + * Run the core logic of this chain and add to output if desired. + * + * Wraps _call and handles memory. + */ + call(values, config) { + return super.call(values, config); + } + /** @ignore */ + async _call(values, runManager) { + const valuesForPrompt = { ...values }; + const valuesForLLM = { + ...this.llmKwargs, + }; + for (const key of this.llm.callKeys) { + if (key in values) { + valuesForLLM[key] = values[key]; + delete valuesForPrompt[key]; + } + } + const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); + const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager?.getChild()); + return { + [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager), + }; } - - utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - - return this; - } -} - -AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); - -// reserved names hotfix -utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; + /** + * Format prompt with values and pass to LLM + * + * @param values - keys to pass to prompt template + * @param callbackManager - CallbackManager to use + * @returns Completion from LLM. + * + * @example + * ```ts + * llm.predict({ adjective: "funny" }) + * ``` + */ + async predict(values, callbackManager) { + const output = await this.call(values, callbackManager); + return output[this.outputKey]; } - } -}); - -utils.freezeMethods(AxiosHeaders); - -/* harmony default export */ const core_AxiosHeaders = (AxiosHeaders); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/transformData.js - + _chainType() { + return "llm"; + } + static async deserialize(data) { + const { llm, prompt } = data; + if (!llm) { + throw new Error("LLMChain must have llm"); + } + if (!prompt) { + throw new Error("LLMChain must have prompt"); + } + return new LLMChain({ + llm: await index_js_1.BaseLanguageModel.deserialize(llm), + prompt: await base_js_2.BasePromptTemplate.deserialize(prompt), + }); + } + /** @deprecated */ + serialize() { + return { + _type: `${this._chainType()}_chain`, + llm: this.llm.serialize(), + prompt: this.prompt.serialize(), + }; + } +} +exports.LLMChain = LLMChain; +/***/ }), +/***/ 9957: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createExtractionChainFromZod = exports.createExtractionChain = void 0; +const zod_to_json_schema_1 = __nccwpck_require__(8707); +const prompt_js_1 = __nccwpck_require__(8767); +const openai_functions_js_1 = __nccwpck_require__(5552); +const llm_chain_js_1 = __nccwpck_require__(4553); /** - * Transform the data for a request or a response - * - * @param {Array|Function} fns A single function or Array of functions - * @param {?Object} response The response object - * - * @returns {*} The resulting transformed data + * Function that returns an array of extraction functions. These functions + * are used to extract relevant information from a passage. + * @param schema The schema of the function parameters. + * @returns An array of extraction functions. */ -function transformData(fns, response) { - const config = this || lib_defaults; - const context = response || config; - const headers = core_AxiosHeaders.from(context.headers); - let data = context.data; - - utils.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); - }); - - headers.normalize(); - - return data; +function getExtractionFunctions(schema) { + return [ + { + name: "information_extraction", + description: "Extracts the relevant information from the passage.", + parameters: { + type: "object", + properties: { + info: { + type: "array", + items: { + type: schema.type, + properties: schema.properties, + required: schema.required, + }, + }, + }, + required: ["info"], + }, + }, + ]; } +const _EXTRACTION_TEMPLATE = `Extract and save the relevant entities mentioned in the following passage together with their properties. -;// CONCATENATED MODULE: ./node_modules/axios/lib/cancel/isCancel.js - - -function isCancel(value) { - return !!(value && value.__CANCEL__); +Passage: +{input} +`; +/** + * Function that creates an extraction chain using the provided JSON schema. + * It sets up the necessary components, such as the prompt, output parser, and tags. + * @param schema JSON schema of the function parameters. + * @param llm Must be a ChatOpenAI or AnthropicFunctions model that supports function calling. + * @returns A LLMChain instance configured to return data matching the schema. + */ +function createExtractionChain(schema, llm) { + const functions = getExtractionFunctions(schema); + const prompt = prompt_js_1.PromptTemplate.fromTemplate(_EXTRACTION_TEMPLATE); + const outputParser = new openai_functions_js_1.JsonKeyOutputFunctionsParser({ attrName: "info" }); + return new llm_chain_js_1.LLMChain({ + llm, + prompt, + llmKwargs: { functions }, + outputParser, + tags: ["openai_functions", "extraction"], + }); } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/cancel/CanceledError.js - - - - - +exports.createExtractionChain = createExtractionChain; /** - * A `CanceledError` is an object that is thrown when an operation is canceled. - * - * @param {string=} message The message. - * @param {Object=} config The config. - * @param {Object=} request The request. - * - * @returns {CanceledError} The created error. + * Function that creates an extraction chain from a Zod schema. It + * converts the Zod schema to a JSON schema using zod-to-json-schema + * before creating the extraction chain. + * @param schema The Zod schema which extracted data should match + * @param llm Must be a ChatOpenAI or AnthropicFunctions model that supports function calling. + * @returns A LLMChain instance configured to return data matching the schema. */ -function CanceledError(message, config, request) { - // eslint-disable-next-line no-eq-null,eqeqeq - core_AxiosError.call(this, message == null ? 'canceled' : message, core_AxiosError.ERR_CANCELED, config, request); - this.name = 'CanceledError'; +function createExtractionChainFromZod( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +schema, llm) { + return createExtractionChain((0, zod_to_json_schema_1.zodToJsonSchema)(schema), llm); } +exports.createExtractionChainFromZod = createExtractionChainFromZod; -utils.inherits(CanceledError, core_AxiosError, { - __CANCEL__: true -}); - -/* harmony default export */ const cancel_CanceledError = (CanceledError); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/settle.js +/***/ }), +/***/ 6350: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createOpenAPIChain = exports.convertOpenAPISchemaToJSONSchema = void 0; +const openapi_js_1 = __nccwpck_require__(1776); +const base_js_1 = __nccwpck_require__(6529); +const llm_chain_js_1 = __nccwpck_require__(4553); +const openai_js_1 = __nccwpck_require__(2453); +const chat_js_1 = __nccwpck_require__(9568); +const sequential_chain_js_1 = __nccwpck_require__(1078); +const openai_functions_js_1 = __nccwpck_require__(5552); /** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - * - * @returns {object} The response. + * Formats a URL by replacing path parameters with their corresponding + * values. + * @param url The URL to format. + * @param pathParams The path parameters to replace in the URL. + * @returns The formatted URL. */ -function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new core_AxiosError( - 'Request failed with status code ' + response.status, - [core_AxiosError.ERR_BAD_REQUEST, core_AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } +function formatURL(url, pathParams) { + const expectedPathParamNames = [...url.matchAll(/{(.*?)}/g)].map((match) => match[1]); + const newParams = {}; + for (const paramName of expectedPathParamNames) { + const cleanParamName = paramName.replace(/^\.;/, "").replace(/\*$/, ""); + const value = pathParams[cleanParamName]; + let formattedValue; + if (Array.isArray(value)) { + if (paramName.startsWith(".")) { + const separator = paramName.endsWith("*") ? "." : ","; + formattedValue = `.${value.join(separator)}`; + } + else if (paramName.startsWith(",")) { + const separator = paramName.endsWith("*") ? `${cleanParamName}=` : ","; + formattedValue = `${cleanParamName}=${value.join(separator)}`; + } + else { + formattedValue = value.join(","); + } + } + else if (typeof value === "object") { + const kvSeparator = paramName.endsWith("*") ? "=" : ","; + const kvStrings = Object.entries(value).map(([k, v]) => k + kvSeparator + v); + let entrySeparator; + if (paramName.startsWith(".")) { + entrySeparator = "."; + formattedValue = "."; + } + else if (paramName.startsWith(";")) { + entrySeparator = ";"; + formattedValue = ";"; + } + else { + entrySeparator = ","; + formattedValue = ""; + } + formattedValue += kvStrings.join(entrySeparator); + } + else { + if (paramName.startsWith(".")) { + formattedValue = `.${value}`; + } + else if (paramName.startsWith(";")) { + formattedValue = `;${cleanParamName}=${value}`; + } + else { + formattedValue = value; + } + } + newParams[paramName] = formattedValue; + } + let formattedUrl = url; + for (const [key, newValue] of Object.entries(newParams)) { + formattedUrl = formattedUrl.replace(`{${key}}`, newValue); + } + return formattedUrl; } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/isAbsoluteURL.js - - /** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * - * @returns {boolean} True if the specified URL is absolute, otherwise false + * Converts OpenAPI parameters to JSON schema format. + * @param params The OpenAPI parameters to convert. + * @param spec The OpenAPI specification that contains the parameters. + * @returns The JSON schema representation of the OpenAPI parameters. */ -function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); +function convertOpenAPIParamsToJSONSchema(params, spec) { + return params.reduce((jsonSchema, param) => { + let schema; + if (param.schema) { + schema = spec.getSchema(param.schema); + // eslint-disable-next-line no-param-reassign + jsonSchema.properties[param.name] = convertOpenAPISchemaToJSONSchema(schema, spec); + } + else if (param.content) { + const mediaTypeSchema = Object.values(param.content)[0].schema; + if (mediaTypeSchema) { + schema = spec.getSchema(mediaTypeSchema); + } + if (!schema) { + return jsonSchema; + } + if (schema.description === undefined) { + schema.description = param.description ?? ""; + } + // eslint-disable-next-line no-param-reassign + jsonSchema.properties[param.name] = convertOpenAPISchemaToJSONSchema(schema, spec); + } + else { + return jsonSchema; + } + if (param.required && Array.isArray(jsonSchema.required)) { + jsonSchema.required.push(param.name); + } + return jsonSchema; + }, { + type: "object", + properties: {}, + required: [], + additionalProperties: {}, + }); +} +// OpenAI throws errors on extraneous schema properties, e.g. if "required" is set on individual ones +/** + * Converts OpenAPI schemas to JSON schema format. + * @param schema The OpenAPI schema to convert. + * @param spec The OpenAPI specification that contains the schema. + * @returns The JSON schema representation of the OpenAPI schema. + */ +function convertOpenAPISchemaToJSONSchema(schema, spec) { + if (schema.type === "object") { + return Object.keys(schema.properties ?? {}).reduce((jsonSchema, propertyName) => { + if (!schema.properties) { + return jsonSchema; + } + const openAPIProperty = spec.getSchema(schema.properties[propertyName]); + if (openAPIProperty.type === undefined) { + return jsonSchema; + } + // eslint-disable-next-line no-param-reassign + jsonSchema.properties[propertyName] = convertOpenAPISchemaToJSONSchema(openAPIProperty, spec); + if (openAPIProperty.required && jsonSchema.required !== undefined) { + jsonSchema.required.push(propertyName); + } + return jsonSchema; + }, { + type: "object", + properties: {}, + required: [], + additionalProperties: {}, + }); + } + if (schema.type === "array") { + return { + type: "array", + items: convertOpenAPISchemaToJSONSchema(schema.items ?? {}, spec), + minItems: schema.minItems, + maxItems: schema.maxItems, + }; + } + return { + type: schema.type ?? "string", + }; +} +exports.convertOpenAPISchemaToJSONSchema = convertOpenAPISchemaToJSONSchema; +/** + * Converts an OpenAPI specification to OpenAI functions. + * @param spec The OpenAPI specification to convert. + * @returns An object containing the OpenAI functions derived from the OpenAPI specification and a default execution method. + */ +function convertOpenAPISpecToOpenAIFunctions(spec) { + if (!spec.document.paths) { + return { openAIFunctions: [] }; + } + const openAIFunctions = []; + const nameToCallMap = {}; + for (const path of Object.keys(spec.document.paths)) { + const pathParameters = spec.getParametersForPath(path); + for (const method of spec.getMethodsForPath(path)) { + const operation = spec.getOperation(path, method); + if (!operation) { + return { openAIFunctions: [] }; + } + const operationParametersByLocation = pathParameters + .concat(spec.getParametersForOperation(operation)) + .reduce((operationParams, param) => { + if (!operationParams[param.in]) { + // eslint-disable-next-line no-param-reassign + operationParams[param.in] = []; + } + operationParams[param.in].push(param); + return operationParams; + }, {}); + const paramLocationToRequestArgNameMap = { + query: "params", + header: "headers", + cookie: "cookies", + path: "path_params", + }; + const requestArgsSchema = {}; + for (const paramLocation of Object.keys(paramLocationToRequestArgNameMap)) { + if (operationParametersByLocation[paramLocation]) { + requestArgsSchema[paramLocationToRequestArgNameMap[paramLocation]] = + convertOpenAPIParamsToJSONSchema(operationParametersByLocation[paramLocation], spec); + } + } + const requestBody = spec.getRequestBodyForOperation(operation); + if (requestBody?.content !== undefined) { + const requestBodySchemas = {}; + for (const [mediaType, mediaTypeObject] of Object.entries(requestBody.content)) { + if (mediaTypeObject.schema !== undefined) { + const schema = spec.getSchema(mediaTypeObject.schema); + requestBodySchemas[mediaType] = convertOpenAPISchemaToJSONSchema(schema, spec); + } + } + const mediaTypes = Object.keys(requestBodySchemas); + if (mediaTypes.length === 1) { + requestArgsSchema.data = requestBodySchemas[mediaTypes[0]]; + } + else if (mediaTypes.length > 1) { + requestArgsSchema.data = { + anyOf: Object.values(requestBodySchemas), + }; + } + } + const openAIFunction = { + name: openapi_js_1.OpenAPISpec.getCleanedOperationId(operation, path, method), + description: operation.description ?? operation.summary ?? "", + parameters: { + type: "object", + properties: requestArgsSchema, + // All remaining top-level parameters are required + required: Object.keys(requestArgsSchema), + }, + }; + openAIFunctions.push(openAIFunction); + const baseUrl = (spec.baseUrl ?? "").endsWith("/") + ? (spec.baseUrl ?? "").slice(0, -1) + : spec.baseUrl ?? ""; + nameToCallMap[openAIFunction.name] = { + method, + url: baseUrl + path, + }; + } + } + return { + openAIFunctions, + defaultExecutionMethod: async (name, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + requestArgs, options) => { + const { headers: customHeaders, params: customParams, ...rest } = options ?? {}; + const { method, url } = nameToCallMap[name]; + const requestParams = requestArgs.params ?? {}; + const nonEmptyParams = Object.keys(requestParams).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (filteredArgs, argName) => { + if (requestParams[argName] !== "" && + requestParams[argName] !== null && + requestParams[argName] !== undefined) { + // eslint-disable-next-line no-param-reassign + filteredArgs[argName] = requestParams[argName]; + } + return filteredArgs; + }, {}); + const queryString = new URLSearchParams({ + ...nonEmptyParams, + ...customParams, + }).toString(); + const pathParams = requestArgs.path_params; + const formattedUrl = formatURL(url, pathParams) + + (queryString.length ? `?${queryString}` : ""); + const headers = {}; + let body; + if (requestArgs.data !== undefined) { + let contentType = "text/plain"; + if (typeof requestArgs.data !== "string") { + if (typeof requestArgs.data === "object") { + contentType = "application/json"; + } + body = JSON.stringify(requestArgs.data); + } + else { + body = requestArgs.data; + } + headers["content-type"] = contentType; + } + const response = await fetch(formattedUrl, { + ...requestArgs, + method, + headers: { + ...headers, + ...requestArgs.headers, + ...customHeaders, + }, + body, + ...rest, + }); + let output; + if (response.status < 200 || response.status > 299) { + output = `${response.status}: ${response.statusText} for ${name} called with ${JSON.stringify(queryString)}`; + } + else { + output = await response.text(); + } + return output; + }, + }; +} +/** + * A chain for making simple API requests. + */ +class SimpleRequestChain extends base_js_1.BaseChain { + static lc_name() { + return "SimpleRequestChain"; + } + constructor(config) { + super(); + Object.defineProperty(this, "requestMethod", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "function" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "response" + }); + this.requestMethod = config.requestMethod; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } + _chainType() { + return "simple_request_chain"; + } + /** @ignore */ + async _call(values, _runManager) { + const inputKeyValue = values[this.inputKey]; + const methodName = inputKeyValue.name; + const args = inputKeyValue.arguments; + const response = await this.requestMethod(methodName, args); + return { [this.outputKey]: response }; + } } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/combineURLs.js - - /** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * - * @returns {string} The combined URL + * Create a chain for querying an API from a OpenAPI spec. + * @param spec OpenAPISpec or url/file/text string corresponding to one. + * @param options Custom options passed into the chain + * @returns OpenAPIChain */ -function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; +async function createOpenAPIChain(spec, options = {}) { + let convertedSpec; + if (typeof spec === "string") { + try { + convertedSpec = await openapi_js_1.OpenAPISpec.fromURL(spec); + } + catch (e) { + try { + convertedSpec = openapi_js_1.OpenAPISpec.fromString(spec); + } + catch (e) { + throw new Error(`Unable to parse spec from source ${spec}.`); + } + } + } + else { + convertedSpec = openapi_js_1.OpenAPISpec.fromObject(spec); + } + const { openAIFunctions, defaultExecutionMethod } = convertOpenAPISpecToOpenAIFunctions(convertedSpec); + if (defaultExecutionMethod === undefined) { + throw new Error(`Could not parse any valid operations from the provided spec.`); + } + const { llm = new openai_js_1.ChatOpenAI({ modelName: "gpt-3.5-turbo-0613" }), prompt = chat_js_1.ChatPromptTemplate.fromMessages([ + chat_js_1.HumanMessagePromptTemplate.fromTemplate("Use the provided API's to respond to this user query:\n\n{query}"), + ]), requestChain = new SimpleRequestChain({ + requestMethod: async (name, args) => defaultExecutionMethod(name, args, { + headers: options.headers, + params: options.params, + }), + }), llmChainInputs = {}, verbose, ...rest } = options; + const formatChain = new llm_chain_js_1.LLMChain({ + llm, + prompt, + outputParser: new openai_functions_js_1.JsonOutputFunctionsParser({ argsOnly: false }), + outputKey: "function", + llmKwargs: { functions: openAIFunctions }, + ...llmChainInputs, + }); + return new sequential_chain_js_1.SequentialChain({ + chains: [formatChain, requestChain], + outputVariables: ["response"], + inputVariables: formatChain.inputKeys, + verbose, + ...rest, + }); } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/buildFullPath.js +exports.createOpenAPIChain = createOpenAPIChain; +/***/ }), +/***/ 6788: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createTaggingChainFromZod = exports.createTaggingChain = void 0; +const zod_to_json_schema_1 = __nccwpck_require__(8707); +const prompt_js_1 = __nccwpck_require__(8767); +const openai_functions_js_1 = __nccwpck_require__(5552); +const llm_chain_js_1 = __nccwpck_require__(4553); /** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * - * @returns {string} The combined full path + * Function that returns an array of tagging functions. These functions + * are used to extract relevant information from a passage. + * @param schema The schema defining the structure of function parameters. + * @returns An array of tagging functions. */ -function buildFullPath(baseURL, requestedURL) { - if (baseURL && !isAbsoluteURL(requestedURL)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -} - -// EXTERNAL MODULE: ./node_modules/proxy-from-env/index.js -var proxy_from_env = __nccwpck_require__(3329); -// EXTERNAL MODULE: external "http" -var external_http_ = __nccwpck_require__(3685); -// EXTERNAL MODULE: external "https" -var external_https_ = __nccwpck_require__(5687); -// EXTERNAL MODULE: external "util" -var external_util_ = __nccwpck_require__(3837); -// EXTERNAL MODULE: ./node_modules/follow-redirects/index.js -var follow_redirects = __nccwpck_require__(7707); -// EXTERNAL MODULE: external "zlib" -var external_zlib_ = __nccwpck_require__(9796); -;// CONCATENATED MODULE: ./node_modules/axios/lib/env/data.js -const VERSION = "1.5.1"; -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/parseProtocol.js - - -function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; +function getTaggingFunctions(schema) { + return [ + { + name: "information_extraction", + description: "Extracts the relevant information from the passage.", + parameters: schema, + }, + ]; } +const TAGGING_TEMPLATE = `Extract the desired information from the following passage. -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/fromDataURI.js - - - - - - -const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; - +Passage: +{input} +`; /** - * Parse data uri to a Buffer or Blob - * - * @param {String} uri - * @param {?Boolean} asBlob - * @param {?Object} options - * @param {?Function} options.Blob - * - * @returns {Buffer|Blob} + * Function that creates a tagging chain using the provided schema, + * LLM, and options. It constructs the LLM with the necessary + * functions, prompt, output parser, and tags. + * @param schema The schema defining the structure of function parameters. + * @param llm LLM to use in the chain. Must support function calling. + * @param options Options for creating the tagging chain. + * @returns A new instance of LLMChain configured for tagging. */ -function fromDataURI(uri, asBlob, options) { - const _Blob = options && options.Blob || node.classes.Blob; - const protocol = parseProtocol(uri); - - if (asBlob === undefined && _Blob) { - asBlob = true; - } - - if (protocol === 'data') { - uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - - const match = DATA_URL_PATTERN.exec(uri); - - if (!match) { - throw new core_AxiosError('Invalid URL', core_AxiosError.ERR_INVALID_URL); - } - - const mime = match[1]; - const isBase64 = match[2]; - const body = match[3]; - const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); - - if (asBlob) { - if (!_Blob) { - throw new core_AxiosError('Blob is not supported', core_AxiosError.ERR_NOT_SUPPORT); - } - - return new _Blob([buffer], {type: mime}); - } - - return buffer; - } - - throw new core_AxiosError('Unsupported protocol ' + protocol, core_AxiosError.ERR_NOT_SUPPORT); +function createTaggingChain(schema, llm, options = {}) { + const { prompt = prompt_js_1.PromptTemplate.fromTemplate(TAGGING_TEMPLATE), ...rest } = options; + const functions = getTaggingFunctions(schema); + const outputParser = new openai_functions_js_1.JsonOutputFunctionsParser(); + return new llm_chain_js_1.LLMChain({ + llm, + prompt, + llmKwargs: { functions }, + outputParser, + tags: ["openai_functions", "tagging"], + ...rest, + }); } - -// EXTERNAL MODULE: external "stream" -var external_stream_ = __nccwpck_require__(2781); -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/throttle.js - - +exports.createTaggingChain = createTaggingChain; /** - * Throttle decorator - * @param {Function} fn - * @param {Number} freq - * @return {Function} + * Function that creates a tagging chain from a Zod schema. It converts + * the Zod schema to a JSON schema using the zodToJsonSchema function and + * then calls createTaggingChain with the converted schema. + * @param schema The Zod schema which extracted data should match. + * @param llm LLM to use in the chain. Must support function calling. + * @param options Options for creating the tagging chain. + * @returns A new instance of LLMChain configured for tagging. */ -function throttle(fn, freq) { - let timestamp = 0; - const threshold = 1000 / freq; - let timer = null; - return function throttled(force, args) { - const now = Date.now(); - if (force || now - timestamp > threshold) { - if (timer) { - clearTimeout(timer); - timer = null; - } - timestamp = now; - return fn.apply(null, args); - } - if (!timer) { - timer = setTimeout(() => { - timer = null; - timestamp = Date.now(); - return fn.apply(null, args); - }, threshold - (now - timestamp)); - } - }; +function createTaggingChainFromZod( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +schema, llm, options) { + return createTaggingChain((0, zod_to_json_schema_1.zodToJsonSchema)(schema), llm, options); } +exports.createTaggingChainFromZod = createTaggingChainFromZod; + -/* harmony default export */ const helpers_throttle = (throttle); +/***/ }), -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/speedometer.js +/***/ 1614: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OpenAIModerationChain = void 0; +const openai_1 = __nccwpck_require__(47); +const base_js_1 = __nccwpck_require__(6529); +const async_caller_js_1 = __nccwpck_require__(3382); +const env_js_1 = __nccwpck_require__(1548); /** - * Calculate data maxRate - * @param {Number} [samplesCount= 10] - * @param {Number} [min= 1000] - * @returns {Function} + * Class representing a chain for moderating text using the OpenAI + * Moderation API. It extends the BaseChain class and implements the + * OpenAIModerationChainInput interface. */ -function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - - min = min !== undefined ? min : 1000; - - return function push(chunkLength) { - const now = Date.now(); - - const startedAt = timestamps[tail]; - - if (!firstSampleTS) { - firstSampleTS = now; - } - - bytes[head] = chunkLength; - timestamps[head] = now; - - let i = tail; - let bytesCount = 0; - - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } - - head = (head + 1) % samplesCount; - - if (head === tail) { - tail = (tail + 1) % samplesCount; +class OpenAIModerationChain extends base_js_1.BaseChain { + static lc_name() { + return "OpenAIModerationChain"; } - - if (now - firstSampleTS < min) { - return; + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + }; } - - const passed = startedAt && now - startedAt; - - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; - }; -} - -/* harmony default export */ const helpers_speedometer = (speedometer); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/AxiosTransformStream.js - - - - - - - -const kInternals = Symbol('internals'); - -class AxiosTransformStream extends external_stream_.Transform{ - constructor(options) { - options = utils.toFlatObject(options, { - maxRate: 0, - chunkSize: 64 * 1024, - minChunkSize: 100, - timeWindow: 500, - ticksRate: 2, - samplesCount: 15 - }, null, (prop, source) => { - return !utils.isUndefined(source[prop]); - }); - - super({ - readableHighWaterMark: options.chunkSize - }); - - const self = this; - - const internals = this[kInternals] = { - length: options.length, - timeWindow: options.timeWindow, - ticksRate: options.ticksRate, - chunkSize: options.chunkSize, - maxRate: options.maxRate, - minChunkSize: options.minChunkSize, - bytesSeen: 0, - isCaptured: false, - notifiedBytesLoaded: 0, - ts: Date.now(), - bytes: 0, - onReadCallback: null - }; - - const _speedometer = helpers_speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow); - - this.on('newListener', event => { - if (event === 'progress') { - if (!internals.isCaptured) { - internals.isCaptured = true; - } - } - }); - - let bytesNotified = 0; - - internals.updateProgress = helpers_throttle(function throttledHandler() { - const totalBytes = internals.length; - const bytesTransferred = internals.bytesSeen; - const progressBytes = bytesTransferred - bytesNotified; - if (!progressBytes || self.destroyed) return; - - const rate = _speedometer(progressBytes); - - bytesNotified = bytesTransferred; - - process.nextTick(() => { - self.emit('progress', { - 'loaded': bytesTransferred, - 'total': totalBytes, - 'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined, - 'bytes': progressBytes, - 'rate': rate ? rate : undefined, - 'estimated': rate && totalBytes && bytesTransferred <= totalBytes ? - (totalBytes - bytesTransferred) / rate : undefined + constructor(fields) { + super(fields); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input" }); - }); - }, internals.ticksRate); - - const onFinish = () => { - internals.updateProgress(true); - }; - - this.once('end', onFinish); - this.once('error', onFinish); - } - - _read(size) { - const internals = this[kInternals]; - - if (internals.onReadCallback) { - internals.onReadCallback(); - } - - return super._read(size); - } - - _transform(chunk, encoding, callback) { - const self = this; - const internals = this[kInternals]; - const maxRate = internals.maxRate; - - const readableHighWaterMark = this.readableHighWaterMark; - - const timeWindow = internals.timeWindow; - - const divider = 1000 / timeWindow; - const bytesThreshold = (maxRate / divider); - const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - - function pushChunk(_chunk, _callback) { - const bytes = Buffer.byteLength(_chunk); - internals.bytesSeen += bytes; - internals.bytes += bytes; - - if (internals.isCaptured) { - internals.updateProgress(); - } - - if (self.push(_chunk)) { - process.nextTick(_callback); - } else { - internals.onReadCallback = () => { - internals.onReadCallback = null; - process.nextTick(_callback); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + Object.defineProperty(this, "openAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "openAIOrganization", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "throwError", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.throwError = fields?.throwError ?? false; + this.openAIApiKey = + fields?.openAIApiKey ?? (0, env_js_1.getEnvironmentVariable)("OPENAI_API_KEY"); + if (!this.openAIApiKey) { + throw new Error("OpenAI API key not found"); + } + this.openAIOrganization = fields?.openAIOrganization; + this.clientConfig = { + ...fields?.configuration, + apiKey: this.openAIApiKey, + organization: this.openAIOrganization, }; - } + this.client = new openai_1.OpenAI(this.clientConfig); + this.caller = new async_caller_js_1.AsyncCaller(fields ?? {}); } - - const transformChunk = (_chunk, _callback) => { - const chunkSize = Buffer.byteLength(_chunk); - let chunkRemainder = null; - let maxChunkSize = readableHighWaterMark; - let bytesLeft; - let passed = 0; - - if (maxRate) { - const now = Date.now(); - - if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { - internals.ts = now; - bytesLeft = bytesThreshold - internals.bytes; - internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; - passed = 0; + _moderate(text, results) { + if (results.flagged) { + const errorStr = "Text was found that violates OpenAI's content policy."; + if (this.throwError) { + throw new Error(errorStr); + } + else { + return errorStr; + } } - - bytesLeft = bytesThreshold - internals.bytes; - } - - if (maxRate) { - if (bytesLeft <= 0) { - // next time window - return setTimeout(() => { - _callback(null, _chunk); - }, timeWindow - passed); + return text; + } + async _call(values) { + const text = values[this.inputKey]; + const moderationRequest = { + input: text, + }; + let mod; + try { + mod = await this.caller.call(() => this.client.moderations.create(moderationRequest)); } - - if (bytesLeft < maxChunkSize) { - maxChunkSize = bytesLeft; + catch (error) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } } - } + const output = this._moderate(text, mod.results[0]); + return { + [this.outputKey]: output, + results: mod.results, + }; + } + _chainType() { + return "moderation_chain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } +} +exports.OpenAIModerationChain = OpenAIModerationChain; - if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { - chunkRemainder = _chunk.subarray(maxChunkSize); - _chunk = _chunk.subarray(0, maxChunkSize); - } - pushChunk(_chunk, chunkRemainder ? () => { - process.nextTick(_callback, null, chunkRemainder); - } : _callback); - }; +/***/ }), - transformChunk(chunk, function transformNextChunk(err, _chunk) { - if (err) { - return callback(err); - } +/***/ 2664: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (_chunk) { - transformChunk(_chunk, transformNextChunk); - } else { - callback(null); - } - }); - } - setLength(length) { - this[kInternals].length = +length; - return this; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.loadQARefineChain = exports.loadQAMapReduceChain = exports.loadQAStuffChain = exports.loadQAChain = void 0; +const llm_chain_js_1 = __nccwpck_require__(4553); +const combine_docs_chain_js_1 = __nccwpck_require__(3186); +const stuff_prompts_js_1 = __nccwpck_require__(5521); +const map_reduce_prompts_js_1 = __nccwpck_require__(2530); +const refine_prompts_js_1 = __nccwpck_require__(3125); +const loadQAChain = (llm, params = { type: "stuff" }) => { + const { type } = params; + if (type === "stuff") { + return loadQAStuffChain(llm, params); + } + if (type === "map_reduce") { + return loadQAMapReduceChain(llm, params); + } + if (type === "refine") { + return loadQARefineChain(llm, params); + } + throw new Error(`Invalid _type: ${type}`); +}; +exports.loadQAChain = loadQAChain; +/** + * Loads a StuffQAChain based on the provided parameters. It takes an LLM + * instance and StuffQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a StuffQAChain. + * @returns A StuffQAChain instance. + */ +function loadQAStuffChain(llm, params = {}) { + const { prompt = stuff_prompts_js_1.QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; + const llmChain = new llm_chain_js_1.LLMChain({ prompt, llm, verbose }); + const chain = new combine_docs_chain_js_1.StuffDocumentsChain({ llmChain, verbose }); + return chain; } - -/* harmony default export */ const helpers_AxiosTransformStream = (AxiosTransformStream); - -// EXTERNAL MODULE: external "events" -var external_events_ = __nccwpck_require__(2361); -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/readBlob.js -const {asyncIterator} = Symbol; - -const readBlob = async function* (blob) { - if (blob.stream) { - yield* blob.stream() - } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer() - } else if (blob[asyncIterator]) { - yield* blob[asyncIterator](); - } else { - yield blob; - } +exports.loadQAStuffChain = loadQAStuffChain; +/** + * Loads a MapReduceQAChain based on the provided parameters. It takes an + * LLM instance and MapReduceQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a MapReduceQAChain. + * @returns A MapReduceQAChain instance. + */ +function loadQAMapReduceChain(llm, params = {}) { + const { combineMapPrompt = map_reduce_prompts_js_1.COMBINE_QA_PROMPT_SELECTOR.getPrompt(llm), combinePrompt = map_reduce_prompts_js_1.COMBINE_PROMPT_SELECTOR.getPrompt(llm), verbose, combineLLM, returnIntermediateSteps, } = params; + const llmChain = new llm_chain_js_1.LLMChain({ prompt: combineMapPrompt, llm, verbose }); + const combineLLMChain = new llm_chain_js_1.LLMChain({ + prompt: combinePrompt, + llm: combineLLM ?? llm, + verbose, + }); + const combineDocumentChain = new combine_docs_chain_js_1.StuffDocumentsChain({ + llmChain: combineLLMChain, + documentVariableName: "summaries", + verbose, + }); + const chain = new combine_docs_chain_js_1.MapReduceDocumentsChain({ + llmChain, + combineDocumentChain, + returnIntermediateSteps, + verbose, + }); + return chain; } - -/* harmony default export */ const helpers_readBlob = (readBlob); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/formDataToStream.js - - +exports.loadQAMapReduceChain = loadQAMapReduceChain; +/** + * Loads a RefineQAChain based on the provided parameters. It takes an LLM + * instance and RefineQAChainParams as parameters. + * @param llm An instance of BaseLanguageModel. + * @param params Parameters for creating a RefineQAChain. + * @returns A RefineQAChain instance. + */ +function loadQARefineChain(llm, params = {}) { + const { questionPrompt = refine_prompts_js_1.QUESTION_PROMPT_SELECTOR.getPrompt(llm), refinePrompt = refine_prompts_js_1.REFINE_PROMPT_SELECTOR.getPrompt(llm), refineLLM, verbose, } = params; + const llmChain = new llm_chain_js_1.LLMChain({ prompt: questionPrompt, llm, verbose }); + const refineLLMChain = new llm_chain_js_1.LLMChain({ + prompt: refinePrompt, + llm: refineLLM ?? llm, + verbose, + }); + const chain = new combine_docs_chain_js_1.RefineDocumentsChain({ + llmChain, + refineLLMChain, + verbose, + }); + return chain; +} +exports.loadQARefineChain = loadQARefineChain; +/***/ }), -const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_'; +/***/ 2530: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const textEncoder = new external_util_.TextEncoder(); -const CRLF = '\r\n'; -const CRLF_BYTES = textEncoder.encode(CRLF); -const CRLF_BYTES_COUNT = 2; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.COMBINE_PROMPT_SELECTOR = exports.COMBINE_PROMPT = exports.COMBINE_QA_PROMPT_SELECTOR = exports.DEFAULT_COMBINE_QA_PROMPT = void 0; +/* eslint-disable spaced-comment */ +const prompt_js_1 = __nccwpck_require__(8767); +const chat_js_1 = __nccwpck_require__(9568); +const conditional_js_1 = __nccwpck_require__(1867); +const qa_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. +Return any relevant text verbatim. +{context} +Question: {question} +Relevant text, if any:`; +exports.DEFAULT_COMBINE_QA_PROMPT = +/*#__PURE__*/ +prompt_js_1.PromptTemplate.fromTemplate(qa_template); +const system_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. +Return any relevant text verbatim. +---------------- +{context}`; +const messages = [ + /*#__PURE__*/ chat_js_1.SystemMessagePromptTemplate.fromTemplate(system_template), + /*#__PURE__*/ chat_js_1.HumanMessagePromptTemplate.fromTemplate("{question}"), +]; +const CHAT_QA_PROMPT = /*#__PURE__*/ chat_js_1.ChatPromptTemplate.fromMessages(messages); +exports.COMBINE_QA_PROMPT_SELECTOR = +/*#__PURE__*/ new conditional_js_1.ConditionalPromptSelector(exports.DEFAULT_COMBINE_QA_PROMPT, [ + [conditional_js_1.isChatModel, CHAT_QA_PROMPT], +]); +const combine_prompt = `Given the following extracted parts of a long document and a question, create a final answer. +If you don't know the answer, just say that you don't know. Don't try to make up an answer. -class FormDataPart { - constructor(name, value) { - const {escapeName} = this.constructor; - const isStringValue = utils.isString(value); +QUESTION: Which state/country's law governs the interpretation of the contract? +========= +Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. - let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ - !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' - }${CRLF}`; +Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy.\n\n11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement.\n\n11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties.\n\n11.9 No Third-Party Beneficiaries. - if (isStringValue) { - value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); - } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}` - } +Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, +========= +FINAL ANSWER: This Agreement is governed by English law. - this.headers = textEncoder.encode(headers + CRLF); +QUESTION: What did the president say about Michael Jackson? +========= +Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \n\nWith a duty to one another to the American people to the Constitution. \n\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \n\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \n\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \n\nHe met the Ukrainian people. \n\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. \n\nGroups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. - this.contentLength = isStringValue ? value.byteLength : value.size; +Content: And we won’t stop. \n\nWe have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. \n\nLet’s use this moment to reset. Let’s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. \n\nLet’s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. \n\nWe can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n\nI recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n\nThey were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n\nOfficer Mora was 27 years old. \n\nOfficer Rivera was 22. \n\nBoth Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n\nI spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. - this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; +Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. \n\nTo all Americans, I will be honest with you, as I’ve always promised. A Russian dictator, invading a foreign country, has costs around the world. \n\nAnd I’m taking robust action to make sure the pain of our sanctions is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n\nTonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. \n\nAmerica will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. \n\nThese steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n\nBut I want you to know that we are going to be okay. - this.name = name; - this.value = value; - } +Content: More support for patients and families. \n\nTo get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. \n\nIt’s based on DARPA—the Defense Department project that led to the Internet, GPS, and so much more. \n\nARPA-H will have a singular purpose—to drive breakthroughs in cancer, Alzheimer’s, diabetes, and more. \n\nA unity agenda for the nation. \n\nWe can do this. \n\nMy fellow Americans—tonight , we have gathered in a sacred space—the citadel of our democracy. \n\nIn this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. \n\nWe have fought for freedom, expanded liberty, defeated totalitarianism and terror. \n\nAnd built the strongest, freest, and most prosperous nation the world has ever known. \n\nNow is the hour. \n\nOur moment of responsibility. \n\nOur test of resolve and conscience, of history itself. \n\nIt is in this moment that our character is formed. Our purpose is found. Our future is forged. \n\nWell I know this nation. +========= +FINAL ANSWER: The president did not mention Michael Jackson. - async *encode(){ - yield this.headers; +QUESTION: {question} +========= +{summaries} +========= +FINAL ANSWER:`; +exports.COMBINE_PROMPT = +/*#__PURE__*/ prompt_js_1.PromptTemplate.fromTemplate(combine_prompt); +const system_combine_template = `Given the following extracted parts of a long document and a question, create a final answer. +If you don't know the answer, just say that you don't know. Don't try to make up an answer. +---------------- +{summaries}`; +const combine_messages = [ + /*#__PURE__*/ chat_js_1.SystemMessagePromptTemplate.fromTemplate(system_combine_template), + /*#__PURE__*/ chat_js_1.HumanMessagePromptTemplate.fromTemplate("{question}"), +]; +const CHAT_COMBINE_PROMPT = +/*#__PURE__*/ chat_js_1.ChatPromptTemplate.fromMessages(combine_messages); +exports.COMBINE_PROMPT_SELECTOR = +/*#__PURE__*/ new conditional_js_1.ConditionalPromptSelector(exports.COMBINE_PROMPT, [ + [conditional_js_1.isChatModel, CHAT_COMBINE_PROMPT], +]); - const {value} = this; - if(utils.isTypedArray(value)) { - yield value; - } else { - yield* helpers_readBlob(value); - } +/***/ }), - yield CRLF_BYTES; - } +/***/ 3125: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - '\r' : '%0D', - '\n' : '%0A', - '"' : '%22', - }[match])); - } -} -const formDataToStream = (form, headersHandler, options) => { - const { - tag = 'form-data-boundary', - size = 25, - boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET) - } = options || {}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.QUESTION_PROMPT_SELECTOR = exports.CHAT_QUESTION_PROMPT = exports.DEFAULT_TEXT_QA_PROMPT = exports.DEFAULT_TEXT_QA_PROMPT_TMPL = exports.REFINE_PROMPT_SELECTOR = exports.CHAT_REFINE_PROMPT = exports.DEFAULT_REFINE_PROMPT = exports.DEFAULT_REFINE_PROMPT_TMPL = void 0; +/* eslint-disable spaced-comment */ +const index_js_1 = __nccwpck_require__(5019); +const conditional_js_1 = __nccwpck_require__(1867); +exports.DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question} +We have provided an existing answer: {existing_answer} +We have the opportunity to refine the existing answer +(only if needed) with some more context below. +------------ +{context} +------------ +Given the new context, refine the original answer to better answer the question. +If the context isn't useful, return the original answer.`; +exports.DEFAULT_REFINE_PROMPT = new index_js_1.PromptTemplate({ + inputVariables: ["question", "existing_answer", "context"], + template: exports.DEFAULT_REFINE_PROMPT_TMPL, +}); +const refineTemplate = `The original question is as follows: {question} +We have provided an existing answer: {existing_answer} +We have the opportunity to refine the existing answer +(only if needed) with some more context below. +------------ +{context} +------------ +Given the new context, refine the original answer to better answer the question. +If the context isn't useful, return the original answer.`; +const messages = [ + /*#__PURE__*/ index_js_1.HumanMessagePromptTemplate.fromTemplate("{question}"), + /*#__PURE__*/ index_js_1.AIMessagePromptTemplate.fromTemplate("{existing_answer}"), + /*#__PURE__*/ index_js_1.HumanMessagePromptTemplate.fromTemplate(refineTemplate), +]; +exports.CHAT_REFINE_PROMPT = +/*#__PURE__*/ index_js_1.ChatPromptTemplate.fromMessages(messages); +exports.REFINE_PROMPT_SELECTOR = +/*#__PURE__*/ new conditional_js_1.ConditionalPromptSelector(exports.DEFAULT_REFINE_PROMPT, [ + [conditional_js_1.isChatModel, exports.CHAT_REFINE_PROMPT], +]); +exports.DEFAULT_TEXT_QA_PROMPT_TMPL = `Context information is below. +--------------------- +{context} +--------------------- +Given the context information and no prior knowledge, answer the question: {question}`; +exports.DEFAULT_TEXT_QA_PROMPT = new index_js_1.PromptTemplate({ + inputVariables: ["context", "question"], + template: exports.DEFAULT_TEXT_QA_PROMPT_TMPL, +}); +const chat_qa_prompt_template = `Context information is below. +--------------------- +{context} +--------------------- +Given the context information and no prior knowledge, answer any questions`; +const chat_messages = [ + /*#__PURE__*/ index_js_1.SystemMessagePromptTemplate.fromTemplate(chat_qa_prompt_template), + /*#__PURE__*/ index_js_1.HumanMessagePromptTemplate.fromTemplate("{question}"), +]; +exports.CHAT_QUESTION_PROMPT = +/*#__PURE__*/ index_js_1.ChatPromptTemplate.fromMessages(chat_messages); +exports.QUESTION_PROMPT_SELECTOR = +/*#__PURE__*/ new conditional_js_1.ConditionalPromptSelector(exports.DEFAULT_TEXT_QA_PROMPT, [ + [conditional_js_1.isChatModel, exports.CHAT_QUESTION_PROMPT], +]); - if(!utils.isFormData(form)) { - throw TypeError('FormData instance required'); - } - if (boundary.length < 1 || boundary.length > 70) { - throw Error('boundary must be 10-70 characters long') - } +/***/ }), - const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); - const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF); - let contentLength = footerBytes.byteLength; +/***/ 5521: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const parts = Array.from(form.entries()).map(([name, value]) => { - const part = new FormDataPart(name, value); - contentLength += part.size; - return part; - }); - contentLength += boundaryBytes.byteLength * parts.length; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.QA_PROMPT_SELECTOR = exports.DEFAULT_QA_PROMPT = void 0; +/* eslint-disable spaced-comment */ +const prompt_js_1 = __nccwpck_require__(8767); +const chat_js_1 = __nccwpck_require__(9568); +const conditional_js_1 = __nccwpck_require__(1867); +exports.DEFAULT_QA_PROMPT = new prompt_js_1.PromptTemplate({ + template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", + inputVariables: ["context", "question"], +}); +const system_template = `Use the following pieces of context to answer the users question. +If you don't know the answer, just say that you don't know, don't try to make up an answer. +---------------- +{context}`; +const messages = [ + /*#__PURE__*/ chat_js_1.SystemMessagePromptTemplate.fromTemplate(system_template), + /*#__PURE__*/ chat_js_1.HumanMessagePromptTemplate.fromTemplate("{question}"), +]; +const CHAT_PROMPT = /*#__PURE__*/ chat_js_1.ChatPromptTemplate.fromMessages(messages); +exports.QA_PROMPT_SELECTOR = new conditional_js_1.ConditionalPromptSelector(exports.DEFAULT_QA_PROMPT, [[conditional_js_1.isChatModel, CHAT_PROMPT]]); - contentLength = utils.toFiniteNumber(contentLength); - const computedHeaders = { - 'Content-Type': `multipart/form-data; boundary=${boundary}` - } +/***/ }), - if (Number.isFinite(contentLength)) { - computedHeaders['Content-Length'] = contentLength; - } +/***/ 8207: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - headersHandler && headersHandler(computedHeaders); - return external_stream_.Readable.from((async function *() { - for(const part of parts) { - yield boundaryBytes; - yield* part.encode(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RetrievalQAChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const load_js_1 = __nccwpck_require__(2664); +/** + * Class representing a chain for performing question-answering tasks with + * a retrieval component. + */ +class RetrievalQAChain extends base_js_1.BaseChain { + static lc_name() { + return "RetrievalQAChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "query" + }); + Object.defineProperty(this, "retriever", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnSourceDocuments", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.retriever = fields.retriever; + this.combineDocumentsChain = fields.combineDocumentsChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.returnSourceDocuments = + fields.returnSourceDocuments ?? this.returnSourceDocuments; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Question key "${this.inputKey}" not found.`); + } + const question = values[this.inputKey]; + const docs = await this.retriever.getRelevantDocuments(question, runManager?.getChild("retriever")); + const inputs = { question, input_documents: docs, ...values }; + const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); + if (this.returnSourceDocuments) { + return { + ...result, + sourceDocuments: docs, + }; + } + return result; + } + _chainType() { + return "retrieval_qa"; + } + static async deserialize(_data, _values) { + throw new Error("Not implemented"); + } + serialize() { + throw new Error("Not implemented"); + } + /** + * Creates a new instance of RetrievalQAChain using a BaseLanguageModel + * and a BaseRetriever. + * @param llm The BaseLanguageModel used to generate a new question. + * @param retriever The BaseRetriever used to retrieve relevant documents. + * @param options Optional parameters for the RetrievalQAChain. + * @returns A new instance of RetrievalQAChain. + */ + static fromLLM(llm, retriever, options) { + const qaChain = (0, load_js_1.loadQAStuffChain)(llm, { + prompt: options?.prompt, + }); + return new this({ + ...options, + retriever, + combineDocumentsChain: qaChain, + }); } +} +exports.RetrievalQAChain = RetrievalQAChain; - yield footerBytes; - })()); -}; -/* harmony default export */ const helpers_formDataToStream = (formDataToStream); +/***/ }), + +/***/ 5569: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/ZlibHeaderTransformStream.js +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LLMRouterChain = void 0; +const llm_chain_js_1 = __nccwpck_require__(4553); +const multi_route_js_1 = __nccwpck_require__(1111); +/** + * A class that represents an LLM router chain in the LangChain framework. + * It extends the RouterChain class and implements the LLMRouterChainInput + * interface. It provides additional functionality specific to LLMs and + * routing based on LLM predictions. + */ +class LLMRouterChain extends multi_route_js_1.RouterChain { + constructor(fields) { + super(fields); + Object.defineProperty(this, "llmChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmChain = fields.llmChain; + } + get inputKeys() { + return this.llmChain.inputKeys; + } + async _call(values, runManager) { + return this.llmChain.predict(values, runManager?.getChild()); + } + _chainType() { + return "llm_router_chain"; + } + /** + * A static method that creates an instance of LLMRouterChain from a + * BaseLanguageModel and a BasePromptTemplate. It takes in an optional + * options object and returns an instance of LLMRouterChain with the + * specified LLMChain. + * @param llm A BaseLanguageModel instance. + * @param prompt A BasePromptTemplate instance. + * @param options Optional LLMRouterChainInput object, excluding "llmChain". + * @returns An instance of LLMRouterChain. + */ + static fromLLM(llm, prompt, options) { + const llmChain = new llm_chain_js_1.LLMChain({ llm, prompt }); + return new LLMRouterChain({ ...options, llmChain }); + } +} +exports.LLMRouterChain = LLMRouterChain; +/***/ }), -class ZlibHeaderTransformStream extends external_stream_.Transform { - __transform(chunk, encoding, callback) { - this.push(chunk); - callback(); - } +/***/ 8847: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _transform(chunk, encoding, callback) { - if (chunk.length !== 0) { - this._transform = this.__transform; - // Add Default Compression headers if no zlib headers are present - if (chunk[0] !== 120) { // Hex: 78 - const header = Buffer.alloc(2); - header[0] = 120; // Hex: 78 - header[1] = 156; // Hex: 9C - this.push(header, encoding); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MultiPromptChain = void 0; +const zod_1 = __nccwpck_require__(3301); +const multi_route_js_1 = __nccwpck_require__(1111); +const multi_prompt_prompt_js_1 = __nccwpck_require__(1974); +const template_js_1 = __nccwpck_require__(9714); +const llm_chain_js_1 = __nccwpck_require__(4553); +const prompt_js_1 = __nccwpck_require__(8767); +const llm_router_js_1 = __nccwpck_require__(5569); +const conversation_js_1 = __nccwpck_require__(4678); +const utils_js_1 = __nccwpck_require__(3024); +const router_js_1 = __nccwpck_require__(2183); +/** + * A class that represents a multi-prompt chain in the LangChain + * framework. It extends the MultiRouteChain class and provides additional + * functionality specific to multi-prompt chains. + */ +class MultiPromptChain extends multi_route_js_1.MultiRouteChain { + /** + * @deprecated Use `fromLLMAndPrompts` instead + */ + static fromPrompts(llm, promptNames, promptDescriptions, promptTemplates, defaultChain, options) { + return MultiPromptChain.fromLLMAndPrompts(llm, { + promptNames, + promptDescriptions, + promptTemplates, + defaultChain, + multiRouteChainOpts: options, + }); + } + /** + * A static method that creates an instance of MultiPromptChain from a + * BaseLanguageModel and a set of prompts. It takes in optional parameters + * for the default chain and additional options. + * @param llm A BaseLanguageModel instance. + * @param promptNames An array of prompt names. + * @param promptDescriptions An array of prompt descriptions. + * @param promptTemplates An array of prompt templates. + * @param defaultChain An optional BaseChain instance to be used as the default chain. + * @param llmChainOpts Optional parameters for the LLMChainInput, excluding 'llm' and 'prompt'. + * @param conversationChainOpts Optional parameters for the LLMChainInput, excluding 'llm' and 'outputKey'. + * @param multiRouteChainOpts Optional parameters for the MultiRouteChainInput, excluding 'defaultChain'. + * @returns An instance of MultiPromptChain. + */ + static fromLLMAndPrompts(llm, { promptNames, promptDescriptions, promptTemplates, defaultChain, llmChainOpts, conversationChainOpts, multiRouteChainOpts, }) { + const destinations = (0, utils_js_1.zipEntries)(promptNames, promptDescriptions).map(([name, desc]) => `${name}: ${desc}`); + const structuredOutputParserSchema = zod_1.z.object({ + destination: zod_1.z + .string() + .optional() + .describe('name of the question answering system to use or "DEFAULT"'), + next_inputs: zod_1.z + .object({ + input: zod_1.z + .string() + .describe("a potentially modified version of the original input"), + }) + .describe("input to be fed to the next model"), + }); + const outputParser = new router_js_1.RouterOutputParser(structuredOutputParserSchema); + const destinationsStr = destinations.join("\n"); + const routerTemplate = (0, template_js_1.interpolateFString)((0, multi_prompt_prompt_js_1.STRUCTURED_MULTI_PROMPT_ROUTER_TEMPLATE)(outputParser.getFormatInstructions({ interpolationDepth: 4 })), { + destinations: destinationsStr, + }); + const routerPrompt = new prompt_js_1.PromptTemplate({ + template: routerTemplate, + inputVariables: ["input"], + outputParser, + }); + const routerChain = llm_router_js_1.LLMRouterChain.fromLLM(llm, routerPrompt); + const destinationChains = (0, utils_js_1.zipEntries)(promptNames, promptTemplates).reduce((acc, [name, template]) => { + let myPrompt; + if (typeof template === "object") { + myPrompt = template; + } + else if (typeof template === "string") { + myPrompt = new prompt_js_1.PromptTemplate({ + template: template, + inputVariables: ["input"], + }); + } + else { + throw new Error("Invalid prompt template"); + } + acc[name] = new llm_chain_js_1.LLMChain({ + ...llmChainOpts, + llm, + prompt: myPrompt, + }); + return acc; + }, {}); + const convChain = new conversation_js_1.ConversationChain({ + ...conversationChainOpts, + llm, + outputKey: "text", + }); + return new MultiPromptChain({ + ...multiRouteChainOpts, + routerChain, + destinationChains, + defaultChain: defaultChain ?? convChain, + }); + } + _chainType() { + return "multi_prompt_chain"; } - - this.__transform(chunk, encoding, callback); - } -} - -/* harmony default export */ const helpers_ZlibHeaderTransformStream = (ZlibHeaderTransformStream); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/callbackify.js - - -const callbackify = (fn, reducer) => { - return utils.isAsyncFn(fn) ? function (...args) { - const cb = args.pop(); - fn.apply(this, args).then((value) => { - try { - reducer ? cb(null, ...reducer(value)) : cb(null, value); - } catch (err) { - cb(err); - } - }, cb); - } : fn; } +exports.MultiPromptChain = MultiPromptChain; -/* harmony default export */ const helpers_callbackify = (callbackify); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/adapters/http.js +/***/ }), +/***/ 1974: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.STRUCTURED_MULTI_PROMPT_ROUTER_TEMPLATE = exports.MULTI_PROMPT_ROUTER_TEMPLATE = void 0; +exports.MULTI_PROMPT_ROUTER_TEMPLATE = `Given a raw text input to a language model, select the model prompt best suited for the input. You will be given the names of the available prompts and a description of what the prompt is best suited for. You may also revise the original input if you think that revising it will ultimately lead to a better response from the language model. +<< FORMATTING >> +Return a markdown code snippet with a JSON object formatted to look like: +\`\`\`json +{{{{ + "destination": string \\ name of the prompt to use or "DEFAULT" + "next_inputs": string \\ a potentially modified version of the original input +}}}} +\`\`\` +REMEMBER: "destination" MUST be one of the candidate prompt names specified below OR it can be "DEFAULT" if the input is not well suited for any of the candidate prompts. +REMEMBER: "next_inputs" can just be the original input if you don't think any modifications are needed. +<< CANDIDATE PROMPTS >> +{destinations} +<< INPUT >> +{{input}} +<< OUTPUT >> +`; +const STRUCTURED_MULTI_PROMPT_ROUTER_TEMPLATE = (formatting) => `Given a raw text input to a language model, select the model prompt best suited for the input. You will be given the names of the available prompts and a description of what the prompt is best suited for. You may also revise the original input if you think that revising it will ultimately lead to a better response from the language model. +<< FORMATTING >> +${formatting} +REMEMBER: "destination" MUST be one of the candidate prompt names specified below OR it can be "DEFAULT" if the input is not well suited for any of the candidate prompts. +REMEMBER: "next_inputs.input" can just be the original input if you don't think any modifications are needed. +<< CANDIDATE PROMPTS >> +{destinations} +<< INPUT >> +{{input}} +<< OUTPUT >> +`; +exports.STRUCTURED_MULTI_PROMPT_ROUTER_TEMPLATE = STRUCTURED_MULTI_PROMPT_ROUTER_TEMPLATE; +/***/ }), +/***/ 2293: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.STRUCTURED_MULTI_RETRIEVAL_ROUTER_TEMPLATE = exports.MULTI_RETRIEVAL_ROUTER_TEMPLATE = void 0; +exports.MULTI_RETRIEVAL_ROUTER_TEMPLATE = `Given a query to a question answering system, select the system best suited for the input. You will be given the names of the available systems and a description of what questions the system is best suited for. You may also revise the original input if you think that revising it will ultimately lead to a better response. +<< FORMATTING >> +Return a markdown code snippet with a JSON object formatted to look like: +\`\`\`json +{{{{ + "destination": string \\ name of the question answering system to use or "DEFAULT" + "next_inputs": string \\ a potentially modified version of the original input +}}}} +\`\`\` +REMEMBER: "destination" MUST be one of the candidate prompt names specified below OR it can be "DEFAULT" if the input is not well suited for any of the candidate prompts. +REMEMBER: "next_inputs" can just be the original input if you don't think any modifications are needed. +<< CANDIDATE PROMPTS >> +{destinations} +<< INPUT >> +{{input}} +<< OUTPUT >> +`; +const STRUCTURED_MULTI_RETRIEVAL_ROUTER_TEMPLATE = (formatting) => `Given a query to a question answering system, select the system best suited for the input. You will be given the names of the available systems and a description of what questions the system is best suited for. You may also revise the original input if you think that revising it will ultimately lead to a better response. +<< FORMATTING >> +${formatting} +REMEMBER: "destination" MUST be one of the candidate prompt names specified below OR it can be "DEFAULT" if the input is not well suited for any of the candidate prompts. +REMEMBER: "next_inputs.query" can just be the original input if you don't think any modifications are needed. -const zlibOptions = { - flush: external_zlib_.constants.Z_SYNC_FLUSH, - finishFlush: external_zlib_.constants.Z_SYNC_FLUSH -}; +<< CANDIDATE PROMPTS >> +{destinations} -const brotliOptions = { - flush: external_zlib_.constants.BROTLI_OPERATION_FLUSH, - finishFlush: external_zlib_.constants.BROTLI_OPERATION_FLUSH -} +<< INPUT >> +{{input}} -const isBrotliSupported = utils.isFunction(external_zlib_.createBrotliDecompress); +<< OUTPUT >> +`; +exports.STRUCTURED_MULTI_RETRIEVAL_ROUTER_TEMPLATE = STRUCTURED_MULTI_RETRIEVAL_ROUTER_TEMPLATE; -const {http: httpFollow, https: httpsFollow} = follow_redirects; -const isHttps = /https:?/; +/***/ }), -const supportedProtocols = node.protocols.map(protocol => { - return protocol + ':'; -}); +/***/ 6693: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * If the proxy or config beforeRedirects functions are defined, call them with the options - * object. - * - * @param {Object} options - The options object that was passed to the request. - * - * @returns {Object} - */ -function dispatchBeforeRedirect(options) { - if (options.beforeRedirects.proxy) { - options.beforeRedirects.proxy(options); - } - if (options.beforeRedirects.config) { - options.beforeRedirects.config(options); - } -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MultiRetrievalQAChain = void 0; +const zod_1 = __nccwpck_require__(3301); +const multi_route_js_1 = __nccwpck_require__(1111); +const template_js_1 = __nccwpck_require__(9714); +const prompt_js_1 = __nccwpck_require__(8767); +const llm_router_js_1 = __nccwpck_require__(5569); +const conversation_js_1 = __nccwpck_require__(4678); +const multi_retrieval_prompt_js_1 = __nccwpck_require__(2293); +const utils_js_1 = __nccwpck_require__(3024); +const retrieval_qa_js_1 = __nccwpck_require__(8207); +const router_js_1 = __nccwpck_require__(2183); /** - * If the proxy or config afterRedirects functions are defined, call them with the options - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} configProxy configuration from Axios options object - * @param {string} location - * - * @returns {http.ClientRequestArgs} + * A class that represents a multi-retrieval question answering chain in + * the LangChain framework. It extends the MultiRouteChain class and + * provides additional functionality specific to multi-retrieval QA + * chains. */ -function setProxy(options, configProxy, location) { - let proxy = configProxy; - if (!proxy && proxy !== false) { - const proxyUrl = (0,proxy_from_env/* getProxyForUrl */.j)(location); - if (proxyUrl) { - proxy = new URL(proxyUrl); - } - } - if (proxy) { - // Basic proxy authorization - if (proxy.username) { - proxy.auth = (proxy.username || '') + ':' + (proxy.password || ''); - } - - if (proxy.auth) { - // Support proxy auth object form - if (proxy.auth.username || proxy.auth.password) { - proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); - } - const base64 = Buffer - .from(proxy.auth, 'utf8') - .toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } - - options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); - const proxyHost = proxy.hostname || proxy.host; - options.hostname = proxyHost; - // Replace 'host' since options is not a URL object - options.host = proxyHost; - options.port = proxy.port; - options.path = location; - if (proxy.protocol) { - options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`; - } - } - - options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { - // Configure proxy for redirected request, passing the original config proxy to apply - // the exact same logic as if the redirected request was performed by axios directly. - setProxy(redirectOptions, configProxy, redirectOptions.href); - }; -} - -const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process'; - -// temporary hotfix - -const wrapAsync = (asyncExecutor) => { - return new Promise((resolve, reject) => { - let onDone; - let isDone; - - const done = (value, isRejected) => { - if (isDone) return; - isDone = true; - onDone && onDone(value, isRejected); +class MultiRetrievalQAChain extends multi_route_js_1.MultiRouteChain { + get outputKeys() { + return ["result"]; } - - const _resolve = (value) => { - done(value); - resolve(value); - }; - - const _reject = (reason) => { - done(reason, true); - reject(reason); + /** + * @deprecated Use `fromRetrieversAndPrompts` instead + */ + static fromRetrievers(llm, retrieverNames, retrieverDescriptions, retrievers, retrieverPrompts, defaults, options) { + return MultiRetrievalQAChain.fromLLMAndRetrievers(llm, { + retrieverNames, + retrieverDescriptions, + retrievers, + retrieverPrompts, + defaults, + multiRetrievalChainOpts: options, + }); } - - asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); - }) -}; - -/*eslint consistent-return:0*/ -/* harmony default export */ const http = (isHttpAdapterSupported && function httpAdapter(config) { - return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { - let {data, lookup, family} = config; - const {responseType, responseEncoding} = config; - const method = config.method.toUpperCase(); - let isDone; - let rejected = false; - let req; - - if (lookup && utils.isAsyncFn(lookup)) { - lookup = helpers_callbackify(lookup, (entry) => { - if(utils.isString(entry)) { - entry = [entry, entry.indexOf('.') < 0 ? 6 : 4] - } else if (!utils.isArray(entry)) { - throw new TypeError('lookup async function must return an array [ip: string, family: number]]') + /** + * A static method that creates an instance of MultiRetrievalQAChain from + * a BaseLanguageModel and a set of retrievers. It takes in optional + * parameters for the retriever names, descriptions, prompts, defaults, + * and additional options. It is an alternative method to fromRetrievers + * and provides more flexibility in configuring the underlying chains. + * @param llm A BaseLanguageModel instance. + * @param retrieverNames An array of retriever names. + * @param retrieverDescriptions An array of retriever descriptions. + * @param retrievers An array of BaseRetriever instances. + * @param retrieverPrompts An optional array of PromptTemplate instances for the retrievers. + * @param defaults An optional MultiRetrievalDefaults instance. + * @param multiRetrievalChainOpts Additional optional parameters for the multi-retrieval chain. + * @param retrievalQAChainOpts Additional optional parameters for the retrieval QA chain. + * @returns A new instance of MultiRetrievalQAChain. + */ + static fromLLMAndRetrievers(llm, { retrieverNames, retrieverDescriptions, retrievers, retrieverPrompts, defaults, multiRetrievalChainOpts, retrievalQAChainOpts, }) { + const { defaultRetriever, defaultPrompt, defaultChain } = defaults ?? {}; + if (defaultPrompt && !defaultRetriever) { + throw new Error("`default_retriever` must be specified if `default_prompt` is \nprovided. Received only `default_prompt`."); } - return entry; - }) - } - - // temporary internal emitter until the AxiosRequest class will be implemented - const emitter = new external_events_(); - - const onFinished = () => { - if (config.cancelToken) { - config.cancelToken.unsubscribe(abort); - } - - if (config.signal) { - config.signal.removeEventListener('abort', abort); - } - - emitter.removeAllListeners(); - } - - onDone((value, isRejected) => { - isDone = true; - if (isRejected) { - rejected = true; - onFinished(); - } - }); - - function abort(reason) { - emitter.emit('abort', !reason || reason.type ? new cancel_CanceledError(null, config, req) : reason); - } - - emitter.once('abort', reject); - - if (config.cancelToken || config.signal) { - config.cancelToken && config.cancelToken.subscribe(abort); - if (config.signal) { - config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); - } - } - - // Parse url - const fullPath = buildFullPath(config.baseURL, config.url); - const parsed = new URL(fullPath, 'http://localhost'); - const protocol = parsed.protocol || supportedProtocols[0]; - - if (protocol === 'data:') { - let convertedData; - - if (method !== 'GET') { - return settle(resolve, reject, { - status: 405, - statusText: 'method not allowed', - headers: {}, - config + const destinations = (0, utils_js_1.zipEntries)(retrieverNames, retrieverDescriptions).map(([name, desc]) => `${name}: ${desc}`); + const structuredOutputParserSchema = zod_1.z.object({ + destination: zod_1.z + .string() + .optional() + .describe('name of the question answering system to use or "DEFAULT"'), + next_inputs: zod_1.z + .object({ + query: zod_1.z + .string() + .describe("a potentially modified version of the original input"), + }) + .describe("input to be fed to the next model"), }); - } - - try { - convertedData = fromDataURI(config.url, responseType === 'blob', { - Blob: config.env && config.env.Blob + const outputParser = new router_js_1.RouterOutputParser(structuredOutputParserSchema); + const destinationsStr = destinations.join("\n"); + const routerTemplate = (0, template_js_1.interpolateFString)((0, multi_retrieval_prompt_js_1.STRUCTURED_MULTI_RETRIEVAL_ROUTER_TEMPLATE)(outputParser.getFormatInstructions({ interpolationDepth: 4 })), { + destinations: destinationsStr, }); - } catch (err) { - throw core_AxiosError.from(err, core_AxiosError.ERR_BAD_REQUEST, config); - } - - if (responseType === 'text') { - convertedData = convertedData.toString(responseEncoding); - - if (!responseEncoding || responseEncoding === 'utf8') { - convertedData = utils.stripBOM(convertedData); + const routerPrompt = new prompt_js_1.PromptTemplate({ + template: routerTemplate, + inputVariables: ["input"], + outputParser, + }); + const routerChain = llm_router_js_1.LLMRouterChain.fromLLM(llm, routerPrompt); + const prompts = retrieverPrompts ?? retrievers.map(() => null); + const destinationChains = (0, utils_js_1.zipEntries)(retrieverNames, retrievers, prompts).reduce((acc, [name, retriever, prompt]) => { + const opt = retrievalQAChainOpts ?? {}; + if (prompt) { + opt.prompt = prompt; + } + acc[name] = retrieval_qa_js_1.RetrievalQAChain.fromLLM(llm, retriever, opt); + return acc; + }, {}); + let _defaultChain; + if (defaultChain) { + _defaultChain = defaultChain; } - } else if (responseType === 'stream') { - convertedData = external_stream_.Readable.from(convertedData); - } - - return settle(resolve, reject, { - data: convertedData, - status: 200, - statusText: 'OK', - headers: new core_AxiosHeaders(), - config - }); - } - - if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new core_AxiosError( - 'Unsupported protocol ' + protocol, - core_AxiosError.ERR_BAD_REQUEST, - config - )); - } - - const headers = core_AxiosHeaders.from(config.headers).normalize(); - - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - // User-Agent is specified; handle case where no UA header is desired - // Only set header if it hasn't been set in config - headers.set('User-Agent', 'axios/' + VERSION, false); - - const onDownloadProgress = config.onDownloadProgress; - const onUploadProgress = config.onUploadProgress; - const maxRate = config.maxRate; - let maxUploadRate = undefined; - let maxDownloadRate = undefined; - - // support for spec compliant FormData objects - if (utils.isSpecCompliantForm(data)) { - const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); - - data = helpers_formDataToStream(data, (formHeaders) => { - headers.set(formHeaders); - }, { - tag: `axios-${VERSION}-boundary`, - boundary: userBoundary && userBoundary[1] || undefined - }); - // support for https://www.npmjs.com/package/form-data api - } else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) { - headers.set(data.getHeaders()); - - if (!headers.hasContentLength()) { - try { - const knownLength = await external_util_.promisify(data.getLength).call(data); - Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); - /*eslint no-empty:0*/ - } catch (e) { + else if (defaultRetriever) { + _defaultChain = retrieval_qa_js_1.RetrievalQAChain.fromLLM(llm, defaultRetriever, { + ...retrievalQAChainOpts, + prompt: defaultPrompt, + }); } - } - } else if (utils.isBlob(data)) { - data.size && headers.setContentType(data.type || 'application/octet-stream'); - headers.setContentLength(data.size || 0); - data = external_stream_.Readable.from(helpers_readBlob(data)); - } else if (data && !utils.isStream(data)) { - if (Buffer.isBuffer(data)) { - // Nothing to do... - } else if (utils.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(new core_AxiosError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - core_AxiosError.ERR_BAD_REQUEST, - config - )); - } - - // Add Content-Length header if data exists - headers.setContentLength(data.length, false); - - if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { - return reject(new core_AxiosError( - 'Request body larger than maxBodyLength limit', - core_AxiosError.ERR_BAD_REQUEST, - config - )); - } + else { + const promptTemplate = conversation_js_1.DEFAULT_TEMPLATE.replace("input", "query"); + const prompt = new prompt_js_1.PromptTemplate({ + template: promptTemplate, + inputVariables: ["history", "query"], + }); + _defaultChain = new conversation_js_1.ConversationChain({ + llm, + prompt, + outputKey: "result", + }); + } + return new MultiRetrievalQAChain({ + ...multiRetrievalChainOpts, + routerChain, + destinationChains, + defaultChain: _defaultChain, + }); + } + _chainType() { + return "multi_retrieval_qa_chain"; } +} +exports.MultiRetrievalQAChain = MultiRetrievalQAChain; - const contentLength = utils.toFiniteNumber(headers.getContentLength()); - if (utils.isArray(maxRate)) { - maxUploadRate = maxRate[0]; - maxDownloadRate = maxRate[1]; - } else { - maxUploadRate = maxDownloadRate = maxRate; - } +/***/ }), - if (data && (onUploadProgress || maxUploadRate)) { - if (!utils.isStream(data)) { - data = external_stream_.Readable.from(data, {objectMode: false}); - } +/***/ 1111: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - data = external_stream_.pipeline([data, new helpers_AxiosTransformStream({ - length: contentLength, - maxRate: utils.toFiniteNumber(maxUploadRate) - })], utils.noop); - onUploadProgress && data.on('progress', progress => { - onUploadProgress(Object.assign(progress, { - upload: true - })); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MultiRouteChain = exports.RouterChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +/** + * A class that represents a router chain. It + * extends the BaseChain class and provides functionality for routing + * inputs to different chains. + */ +class RouterChain extends base_js_1.BaseChain { + get outputKeys() { + return ["destination", "next_inputs"]; } - - // HTTP basic authentication - let auth = undefined; - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password || ''; - auth = username + ':' + password; + async route(inputs, callbacks) { + const result = await this.call(inputs, callbacks); + return { + destination: result.destination, + nextInputs: result.next_inputs, + }; } - - if (!auth && parsed.username) { - const urlUsername = parsed.username; - const urlPassword = parsed.password; - auth = urlUsername + ':' + urlPassword; +} +exports.RouterChain = RouterChain; +/** + * A class that represents a multi-route chain. + * It extends the BaseChain class and provides functionality for routing + * inputs to different chains based on a router chain. + */ +class MultiRouteChain extends base_js_1.BaseChain { + static lc_name() { + return "MultiRouteChain"; } - - auth && headers.delete('authorization'); - - let path; - - try { - path = buildURL( - parsed.pathname + parsed.search, - config.params, - config.paramsSerializer - ).replace(/^\?/, ''); - } catch (err) { - const customErr = new Error(err.message); - customErr.config = config; - customErr.url = config.url; - customErr.exists = true; - return reject(customErr); + constructor(fields) { + super(fields); + Object.defineProperty(this, "routerChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "destinationChains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "defaultChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "silentErrors", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.routerChain = fields.routerChain; + this.destinationChains = fields.destinationChains; + this.defaultChain = fields.defaultChain; + this.silentErrors = fields.silentErrors ?? this.silentErrors; } - - headers.set( - 'Accept-Encoding', - 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false - ); - - const options = { - path, - method: method, - headers: headers.toJSON(), - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth, - protocol, - family, - beforeRedirect: dispatchBeforeRedirect, - beforeRedirects: {} - }; - - // cacheable-lookup integration hotfix - !utils.isUndefined(lookup) && (options.lookup = lookup); - - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname; - options.port = parsed.port; - setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + get inputKeys() { + return this.routerChain.inputKeys; } - - let transport; - const isHttpsRequest = isHttps.test(options.protocol); - options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsRequest ? external_https_ : external_http_; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirects.config = config.beforeRedirect; - } - transport = isHttpsRequest ? httpsFollow : httpFollow; + get outputKeys() { + return []; } - - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } else { - // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited - options.maxBodyLength = Infinity; + async _call(values, runManager) { + const { destination, nextInputs } = await this.routerChain.route(values, runManager?.getChild()); + await runManager?.handleText(`${destination}: ${JSON.stringify(nextInputs)}`); + if (!destination) { + return this.defaultChain + .call(nextInputs, runManager?.getChild()) + .catch((err) => { + throw new Error(`Error in default chain: ${err}`); + }); + } + if (destination in this.destinationChains) { + return this.destinationChains[destination] + .call(nextInputs, runManager?.getChild()) + .catch((err) => { + throw new Error(`Error in ${destination} chain: ${err}`); + }); + } + if (this.silentErrors) { + return this.defaultChain + .call(nextInputs, runManager?.getChild()) + .catch((err) => { + throw new Error(`Error in default chain: ${err}`); + }); + } + throw new Error(`Destination ${destination} not found in destination chains with keys ${Object.keys(this.destinationChains)}`); } - - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; + _chainType() { + return "multi_route_chain"; } +} +exports.MultiRouteChain = MultiRouteChain; - // Create the request - req = transport.request(options, function handleResponse(res) { - if (req.destroyed) return; - - const streams = [res]; - - const responseLength = +res.headers['content-length']; - - if (onDownloadProgress) { - const transformStream = new helpers_AxiosTransformStream({ - length: utils.toFiniteNumber(responseLength), - maxRate: utils.toFiniteNumber(maxDownloadRate) - }); - - onDownloadProgress && transformStream.on('progress', progress => { - onDownloadProgress(Object.assign(progress, { - download: true - })); - }); - streams.push(transformStream); - } +/***/ }), - // decompress the response body transparently if required - let responseStream = res; +/***/ 3024: +/***/ ((__unused_webpack_module, exports) => { - // return the last request in case of redirects - const lastRequest = res.req || req; - // if decompress disabled we should not decompress - if (config.decompress !== false && res.headers['content-encoding']) { - // if no content, but headers still say that it is encoded, - // remove the header not confuse downstream operations - if (method === 'HEAD' || res.statusCode === 204) { - delete res.headers['content-encoding']; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.zipEntries = void 0; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function zipEntries(...arrays) { + // Check for empty input + if (arrays.length === 0) { + return []; + } + // Find the length of the first input array + const firstArrayLength = arrays[0].length; + // Ensure all input arrays have the same length + for (const array of arrays) { + if (array.length !== firstArrayLength) { + throw new Error("All input arrays must have the same length."); } - - switch ((res.headers['content-encoding'] || '').toLowerCase()) { - /*eslint default-case:0*/ - case 'gzip': - case 'x-gzip': - case 'compress': - case 'x-compress': - // add the unzipper to the body stream processing pipeline - streams.push(external_zlib_.createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'deflate': - streams.push(new helpers_ZlibHeaderTransformStream()); - - // add the unzipper to the body stream processing pipeline - streams.push(external_zlib_.createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'br': - if (isBrotliSupported) { - streams.push(external_zlib_.createBrotliDecompress(brotliOptions)); - delete res.headers['content-encoding']; - } + } + // Create an empty array to store the zipped arrays + const zipped = []; + // Iterate through each element of the first input array + for (let i = 0; i < firstArrayLength; i += 1) { + // Create an array to store the zipped elements at the current index + const zippedElement = []; + // Iterate through each input array + for (const array of arrays) { + // Add the element at the current index to the zipped element array + zippedElement.push(array[i]); } - } - - responseStream = streams.length > 1 ? external_stream_.pipeline(streams, utils.noop) : streams[0]; + // Add the zipped element array to the zipped array + zipped.push(zippedElement); + } + return zipped; +} +exports.zipEntries = zipEntries; - const offListeners = external_stream_.finished(responseStream, () => { - offListeners(); - onFinished(); - }); - const response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: new core_AxiosHeaders(res.headers), - config, - request: lastRequest - }; +/***/ }), - if (responseType === 'stream') { - response.data = responseStream; - settle(resolve, reject, response); - } else { - const responseBuffer = []; - let totalResponseBytes = 0; +/***/ 1078: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - responseStream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { - // stream.destroy() emit aborted event before calling reject() on Node.js v16 - rejected = true; - responseStream.destroy(); - reject(new core_AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - core_AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SimpleSequentialChain = exports.SequentialChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const set_js_1 = __nccwpck_require__(4803); +function formatSet(input) { + return Array.from(input) + .map((i) => `"${i}"`) + .join(", "); +} +/** + * Chain where the outputs of one chain feed directly into next. + */ +class SequentialChain extends base_js_1.BaseChain { + static lc_name() { + return "SequentialChain"; + } + get inputKeys() { + return this.inputVariables; + } + get outputKeys() { + return this.outputVariables; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "chains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - - responseStream.on('aborted', function handlerStreamAborted() { - if (rejected) { - return; - } - - const err = new core_AxiosError( - 'maxContentLength size of ' + config.maxContentLength + ' exceeded', - core_AxiosError.ERR_BAD_RESPONSE, - config, - lastRequest - ); - responseStream.destroy(err); - reject(err); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - - responseStream.on('error', function handleStreamError(err) { - if (req.destroyed) return; - reject(core_AxiosError.from(err, null, config, lastRequest)); + Object.defineProperty(this, "outputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - - responseStream.on('end', function handleStreamEnd() { - try { - let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (responseType !== 'arraybuffer') { - responseData = responseData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === 'utf8') { - responseData = utils.stripBOM(responseData); - } + Object.defineProperty(this, "returnAll", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chains = fields.chains; + this.inputVariables = fields.inputVariables; + this.outputVariables = fields.outputVariables ?? []; + if (this.outputVariables.length > 0 && fields.returnAll) { + throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."); + } + this.returnAll = fields.returnAll ?? false; + this._validateChains(); + } + /** @ignore */ + _validateChains() { + if (this.chains.length === 0) { + throw new Error("Sequential chain must have at least one chain."); + } + const memoryKeys = this.memory?.memoryKeys ?? []; + const inputKeysSet = new Set(this.inputKeys); + const memoryKeysSet = new Set(memoryKeys); + const keysIntersection = (0, set_js_1.intersection)(inputKeysSet, memoryKeysSet); + if (keysIntersection.size > 0) { + throw new Error(`The following keys: ${formatSet(keysIntersection)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`); + } + const availableKeys = (0, set_js_1.union)(inputKeysSet, memoryKeysSet); + for (const chain of this.chains) { + let missingKeys = (0, set_js_1.difference)(new Set(chain.inputKeys), availableKeys); + if (chain.memory) { + missingKeys = (0, set_js_1.difference)(missingKeys, new Set(chain.memory.memoryKeys)); } - response.data = responseData; - } catch (err) { - reject(core_AxiosError.from(err, null, config, response.request, response)); - } - settle(resolve, reject, response); + if (missingKeys.size > 0) { + throw new Error(`Missing variables for chain "${chain._chainType()}": ${formatSet(missingKeys)}. Only got the following variables: ${formatSet(availableKeys)}.`); + } + const outputKeysSet = new Set(chain.outputKeys); + const overlappingOutputKeys = (0, set_js_1.intersection)(availableKeys, outputKeysSet); + if (overlappingOutputKeys.size > 0) { + throw new Error(`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(overlappingOutputKeys)}. This can lead to unexpected behaviour.`); + } + for (const outputKey of outputKeysSet) { + availableKeys.add(outputKey); + } + } + if (this.outputVariables.length === 0) { + if (this.returnAll) { + const outputKeys = (0, set_js_1.difference)(availableKeys, inputKeysSet); + this.outputVariables = Array.from(outputKeys); + } + else { + this.outputVariables = this.chains[this.chains.length - 1].outputKeys; + } + } + else { + const missingKeys = (0, set_js_1.difference)(new Set(this.outputVariables), new Set(availableKeys)); + if (missingKeys.size > 0) { + throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${formatSet(missingKeys)}.`); + } + } + } + /** @ignore */ + async _call(values, runManager) { + let input = {}; + const allChainValues = values; + let i = 0; + for (const chain of this.chains) { + i += 1; + input = await chain.call(allChainValues, runManager?.getChild(`step_${i}`)); + for (const key of Object.keys(input)) { + allChainValues[key] = input[key]; + } + } + const output = {}; + for (const key of this.outputVariables) { + output[key] = allChainValues[key]; + } + return output; + } + _chainType() { + return "sequential_chain"; + } + static async deserialize(data) { + const chains = []; + const inputVariables = data.input_variables; + const outputVariables = data.output_variables; + const serializedChains = data.chains; + for (const serializedChain of serializedChains) { + const deserializedChain = await base_js_1.BaseChain.deserialize(serializedChain); + chains.push(deserializedChain); + } + return new SequentialChain({ chains, inputVariables, outputVariables }); + } + serialize() { + const chains = []; + for (const chain of this.chains) { + chains.push(chain.serialize()); + } + return { + _type: this._chainType(), + input_variables: this.inputVariables, + output_variables: this.outputVariables, + chains, + }; + } +} +exports.SequentialChain = SequentialChain; +/** + * Simple chain where a single string output of one chain is fed directly into the next. + * @augments BaseChain + * @augments SimpleSequentialChainInput + * + * @example + * ```ts + * import { SimpleSequentialChain, LLMChain } from "langchain/chains"; + * import { OpenAI } from "langchain/llms/openai"; + * import { PromptTemplate } from "langchain/prompts"; + * + * // This is an LLMChain to write a synopsis given a title of a play. + * const llm = new OpenAI({ temperature: 0 }); + * const template = `You are a playwright. Given the title of play, it is your job to write a synopsis for that title. + * + * Title: {title} + * Playwright: This is a synopsis for the above play:` + * const promptTemplate = new PromptTemplate({ template, inputVariables: ["title"] }); + * const synopsisChain = new LLMChain({ llm, prompt: promptTemplate }); + * + * + * // This is an LLMChain to write a review of a play given a synopsis. + * const reviewLLM = new OpenAI({ temperature: 0 }) + * const reviewTemplate = `You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play. + * + * Play Synopsis: + * {synopsis} + * Review from a New York Times play critic of the above play:` + * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] }); + * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate }); + * + * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true}) + * const review = await overallChain.run("Tragedy at sunset on the beach") + * // the variable review contains resulting play review. + * ``` + */ +class SimpleSequentialChain extends base_js_1.BaseChain { + static lc_name() { + return "SimpleSequentialChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return [this.outputKey]; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "chains", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } - - emitter.once('abort', err => { - if (!responseStream.destroyed) { - responseStream.emit('error', err); - responseStream.destroy(); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "input" + }); + Object.defineProperty(this, "outputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "output" + }); + Object.defineProperty(this, "trimOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.chains = fields.chains; + this.trimOutputs = fields.trimOutputs ?? false; + this._validateChains(); + } + /** @ignore */ + _validateChains() { + for (const chain of this.chains) { + if (chain.inputKeys.filter((k) => !chain.memory?.memoryKeys.includes(k) ?? true).length !== 1) { + throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${chain.inputKeys.length} for ${chain._chainType()}.`); + } + if (chain.outputKeys.length !== 1) { + throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${chain.outputKeys.length} for ${chain._chainType()}.`); + } } - }); - }); - - emitter.once('abort', err => { - reject(err); - req.destroy(err); - }); - - // Handle errors - req.on('error', function handleRequestError(err) { - // @todo remove - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; - reject(core_AxiosError.from(err, null, config, req)); - }); + } + /** @ignore */ + async _call(values, runManager) { + let input = values[this.inputKey]; + let i = 0; + for (const chain of this.chains) { + i += 1; + input = (await chain.call({ [chain.inputKeys[0]]: input, signal: values.signal }, runManager?.getChild(`step_${i}`)))[chain.outputKeys[0]]; + if (this.trimOutputs) { + input = input.trim(); + } + await runManager?.handleText(input); + } + return { [this.outputKey]: input }; + } + _chainType() { + return "simple_sequential_chain"; + } + static async deserialize(data) { + const chains = []; + const serializedChains = data.chains; + for (const serializedChain of serializedChains) { + const deserializedChain = await base_js_1.BaseChain.deserialize(serializedChain); + chains.push(deserializedChain); + } + return new SimpleSequentialChain({ chains }); + } + serialize() { + const chains = []; + for (const chain of this.chains) { + chains.push(chain.serialize()); + } + return { + _type: this._chainType(), + chains, + }; + } +} +exports.SimpleSequentialChain = SimpleSequentialChain; - // set tcp keep alive to prevent drop connection by peer - req.on('socket', function handleRequestSocket(socket) { - // default interval of sending ack packet is 1 minute - socket.setKeepAlive(true, 1000 * 60); - }); - // Handle request timeout - if (config.timeout) { - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. - const timeout = parseInt(config.timeout, 10); +/***/ }), - if (Number.isNaN(timeout)) { - reject(new core_AxiosError( - 'error trying to parse `config.timeout` to int', - core_AxiosError.ERR_BAD_OPTION_VALUE, - config, - req - )); +/***/ 3528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return; - } - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devouring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(timeout, function handleRequestTimeout() { - if (isDone) return; - let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = config.transitional || defaults_transitional; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new core_AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? core_AxiosError.ETIMEDOUT : core_AxiosError.ECONNABORTED, - config, - req - )); - abort(); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.loadSummarizationChain = void 0; +const llm_chain_js_1 = __nccwpck_require__(4553); +const combine_docs_chain_js_1 = __nccwpck_require__(3186); +const stuff_prompts_js_1 = __nccwpck_require__(1576); +const refine_prompts_js_1 = __nccwpck_require__(5624); +const loadSummarizationChain = (llm, params = { type: "map_reduce" }) => { + const { verbose } = params; + if (params.type === "stuff") { + const { prompt = stuff_prompts_js_1.DEFAULT_PROMPT } = params; + const llmChain = new llm_chain_js_1.LLMChain({ prompt, llm, verbose }); + const chain = new combine_docs_chain_js_1.StuffDocumentsChain({ + llmChain, + documentVariableName: "text", + verbose, + }); + return chain; + } + if (params.type === "map_reduce") { + const { combineMapPrompt = stuff_prompts_js_1.DEFAULT_PROMPT, combinePrompt = stuff_prompts_js_1.DEFAULT_PROMPT, combineLLM, returnIntermediateSteps, } = params; + const llmChain = new llm_chain_js_1.LLMChain({ prompt: combineMapPrompt, llm, verbose }); + const combineLLMChain = new llm_chain_js_1.LLMChain({ + prompt: combinePrompt, + llm: combineLLM ?? llm, + verbose, + }); + const combineDocumentChain = new combine_docs_chain_js_1.StuffDocumentsChain({ + llmChain: combineLLMChain, + documentVariableName: "text", + verbose, + }); + const chain = new combine_docs_chain_js_1.MapReduceDocumentsChain({ + llmChain, + combineDocumentChain, + documentVariableName: "text", + returnIntermediateSteps, + verbose, + }); + return chain; + } + if (params.type === "refine") { + const { refinePrompt = refine_prompts_js_1.REFINE_PROMPT, refineLLM, questionPrompt = stuff_prompts_js_1.DEFAULT_PROMPT, } = params; + const llmChain = new llm_chain_js_1.LLMChain({ prompt: questionPrompt, llm, verbose }); + const refineLLMChain = new llm_chain_js_1.LLMChain({ + prompt: refinePrompt, + llm: refineLLM ?? llm, + verbose, + }); + const chain = new combine_docs_chain_js_1.RefineDocumentsChain({ + llmChain, + refineLLMChain, + documentVariableName: "text", + verbose, + }); + return chain; } + throw new Error(`Invalid _type: ${params.type}`); +}; +exports.loadSummarizationChain = loadSummarizationChain; - // Send the request - if (utils.isStream(data)) { - let ended = false; - let errored = false; +/***/ }), - data.on('end', () => { - ended = true; - }); +/***/ 5624: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - data.once('error', err => { - errored = true; - req.destroy(err); - }); - data.on('close', () => { - if (!ended && !errored) { - abort(new cancel_CanceledError('Request stream has been aborted', config, req)); - } - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.REFINE_PROMPT = void 0; +const prompt_js_1 = __nccwpck_require__(8767); +const refinePromptTemplate = `Your job is to produce a final summary +We have provided an existing summary up to a certain point: "{existing_answer}" +We have the opportunity to refine the existing summary +(only if needed) with some more context below. +------------ +"{text}" +------------ - data.pipe(req); - } else { - req.end(data); - } - }); +Given the new context, refine the original summary +If the context isn't useful, return the original summary. + +REFINED SUMMARY:`; +exports.REFINE_PROMPT = new prompt_js_1.PromptTemplate({ + template: refinePromptTemplate, + inputVariables: ["existing_answer", "text"], }); -const __setProxy = (/* unused pure expression or super */ null && (setProxy)); -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/cookies.js +/***/ }), +/***/ 1576: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_PROMPT = void 0; +/* eslint-disable spaced-comment */ +const prompt_js_1 = __nccwpck_require__(8767); +const template = `Write a concise summary of the following: -/* harmony default export */ const cookies = (node.isStandardBrowserEnv ? +"{text}" -// Standard browser envs support document.cookie - (function standardBrowserEnv() { - return { - write: function write(name, value, expires, path, domain, secure) { - const cookie = []; - cookie.push(name + '=' + encodeURIComponent(value)); - if (utils.isNumber(expires)) { - cookie.push('expires=' + new Date(expires).toGMTString()); - } +CONCISE SUMMARY:`; +exports.DEFAULT_PROMPT = new prompt_js_1.PromptTemplate({ + template, + inputVariables: ["text"], +}); - if (utils.isString(path)) { - cookie.push('path=' + path); - } - if (utils.isString(domain)) { - cookie.push('domain=' + domain); - } +/***/ }), - if (secure === true) { - cookie.push('secure'); - } +/***/ 142: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - document.cookie = cookie.join('; '); - }, - read: function read(name) { - const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); - return (match ? decodeURIComponent(match[3]) : null); - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.TransformChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +/** + * Class that represents a transform chain. It extends the `BaseChain` + * class and implements the `TransformChainFields` interface. It provides + * a way to transform input values to output values using a specified + * transform function. + */ +class TransformChain extends base_js_1.BaseChain { + static lc_name() { + return "TransformChain"; + } + _chainType() { + return "transform"; + } + get inputKeys() { + return this.inputVariables; + } + get outputKeys() { + return this.outputVariables; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "transformFunc", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputVariables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.transformFunc = fields.transform; + this.inputVariables = fields.inputVariables; + this.outputVariables = fields.outputVariables; + } + async _call(values, runManager) { + return this.transformFunc(values, runManager?.getChild("transform")); + } +} +exports.TransformChain = TransformChain; - remove: function remove(name) { - this.write(name, '', Date.now() - 86400000); - } - }; - })() : -// Non standard browser env (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return { - write: function write() {}, - read: function read() { return null; }, - remove: function remove() {} - }; - })()); +/***/ }), -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/isURLSameOrigin.js +/***/ 6266: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VectorDBQAChain = void 0; +const base_js_1 = __nccwpck_require__(6529); +const load_js_1 = __nccwpck_require__(2664); +/** + * Class that represents a VectorDBQAChain. It extends the `BaseChain` + * class and implements the `VectorDBQAChainInput` interface. It performs + * a similarity search using a vector store and combines the search + * results using a specified combine documents chain. + */ +class VectorDBQAChain extends base_js_1.BaseChain { + static lc_name() { + return "VectorDBQAChain"; + } + get inputKeys() { + return [this.inputKey]; + } + get outputKeys() { + return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "k", { + enumerable: true, + configurable: true, + writable: true, + value: 4 + }); + Object.defineProperty(this, "inputKey", { + enumerable: true, + configurable: true, + writable: true, + value: "query" + }); + Object.defineProperty(this, "vectorstore", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "combineDocumentsChain", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnSourceDocuments", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.vectorstore = fields.vectorstore; + this.combineDocumentsChain = fields.combineDocumentsChain; + this.inputKey = fields.inputKey ?? this.inputKey; + this.k = fields.k ?? this.k; + this.returnSourceDocuments = + fields.returnSourceDocuments ?? this.returnSourceDocuments; + } + /** @ignore */ + async _call(values, runManager) { + if (!(this.inputKey in values)) { + throw new Error(`Question key ${this.inputKey} not found.`); + } + const question = values[this.inputKey]; + const docs = await this.vectorstore.similaritySearch(question, this.k, values.filter, runManager?.getChild("vectorstore")); + const inputs = { question, input_documents: docs }; + const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); + if (this.returnSourceDocuments) { + return { + ...result, + sourceDocuments: docs, + }; + } + return result; + } + _chainType() { + return "vector_db_qa"; + } + static async deserialize(data, values) { + if (!("vectorstore" in values)) { + throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); + } + const { vectorstore } = values; + if (!data.combine_documents_chain) { + throw new Error(`VectorDBQAChain must have combine_documents_chain in serialized data`); + } + return new VectorDBQAChain({ + combineDocumentsChain: await base_js_1.BaseChain.deserialize(data.combine_documents_chain), + k: data.k, + vectorstore, + }); + } + serialize() { + return { + _type: this._chainType(), + combine_documents_chain: this.combineDocumentsChain.serialize(), + k: this.k, + }; + } + /** + * Static method that creates a VectorDBQAChain instance from a + * BaseLanguageModel and a vector store. It also accepts optional options + * to customize the chain. + * @param llm The BaseLanguageModel instance. + * @param vectorstore The vector store used for similarity search. + * @param options Optional options to customize the chain. + * @returns A new instance of VectorDBQAChain. + */ + static fromLLM(llm, vectorstore, options) { + const qaChain = (0, load_js_1.loadQAStuffChain)(llm); + return new this({ + vectorstore, + combineDocumentsChain: qaChain, + ...options, + }); + } +} +exports.VectorDBQAChain = VectorDBQAChain; +/***/ }), -/* harmony default export */ const isURLSameOrigin = (node.isStandardBrowserEnv ? +/***/ 3023: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Standard browser envs have full support of the APIs needed to test -// whether the request URL is of the same origin as current location. - (function standardBrowserEnv() { - const msie = /(msie|trident)/i.test(navigator.userAgent); - const urlParsingNode = document.createElement('a'); - let originURL; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SimpleChatModel = exports.BaseChatModel = exports.createChatMessageChunkEncoderStream = void 0; +const index_js_1 = __nccwpck_require__(1445); +const index_js_2 = __nccwpck_require__(6691); +const manager_js_1 = __nccwpck_require__(5128); +/** + * Creates a transform stream for encoding chat message chunks. + * @deprecated Use {@link BytesOutputParser} instead + * @returns A TransformStream instance that encodes chat message chunks. + */ +function createChatMessageChunkEncoderStream() { + const textEncoder = new TextEncoder(); + return new TransformStream({ + transform(chunk, controller) { + controller.enqueue(textEncoder.encode(chunk.content)); + }, + }); +} +exports.createChatMessageChunkEncoderStream = createChatMessageChunkEncoderStream; +/** + * Base class for chat models. It extends the BaseLanguageModel class and + * provides methods for generating chat based on input messages. + */ +class BaseChatModel extends index_js_2.BaseLanguageModel { + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "chat_models", this._llmType()] + }); + } + _separateRunnableConfigFromCallOptions(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + if (callOptions?.timeout && !callOptions.signal) { + callOptions.signal = AbortSignal.timeout(callOptions.timeout); + } + return [runnableConfig, callOptions]; + } /** - * Parse a URL to discover it's components - * - * @param {String} url The URL to be parsed - * @returns {Object} - */ - function resolveURL(url) { - let href = url; - - if (msie) { - // IE needs attribute set twice to normalize properties - urlParsingNode.setAttribute('href', href); - href = urlParsingNode.href; - } - - urlParsingNode.setAttribute('href', href); - - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - return { - href: urlParsingNode.href, - protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', - host: urlParsingNode.host, - search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', - hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') ? - urlParsingNode.pathname : - '/' + urlParsingNode.pathname - }; + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = BaseChatModel._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + const chatGeneration = result.generations[0][0]; + // TODO: Remove cast after figuring out inheritance + return chatGeneration.message; + } + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); + } + async *_streamIterator(input, options) { + // Subclass check required to avoid double callbacks with default implementation + if (this._streamResponseChunks === + BaseChatModel.prototype._streamResponseChunks) { + yield this.invoke(input, options); + } + else { + const prompt = BaseChatModel._convertInputToPromptValue(input); + const messages = prompt.toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); + const callbackManager_ = await manager_js_1.CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [messages], undefined, undefined, extra); + let generationChunk; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + yield chunk.message; + if (!generationChunk) { + generationChunk = chunk; + } + else { + generationChunk = generationChunk.concat(chunk); + } + } + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + // TODO: Remove cast after figuring out inheritance + generations: [[generationChunk]], + }))); + } + } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions) { + const baseMessages = messages.map((messageList) => messageList.map(index_js_1.coerceMessageLikeToMessage)); + // create callback manager and start run + const callbackManager_ = await manager_js_1.CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages, undefined, undefined, extra); + // generate results + const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); + // handle results + const generations = []; + const llmOutputs = []; + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput, + }); + } + else { + // status === "rejected" + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); + } + })); + // create combined output + const output = { + generations, + llmOutput: llmOutputs.length + ? this._combineLLMOutput?.(...llmOutputs) + : undefined, + }; + Object.defineProperty(output, index_js_1.RUN_KEY, { + value: runManagers + ? { runIds: runManagers?.map((manager) => manager.runId) } + : undefined, + configurable: true, + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + // parse call options + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } + else { + parsedOptions = options; + } + const baseMessages = messages.map((messageList) => messageList.map(index_js_1.coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(baseMessages, callOptions, runnableConfig); + } + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const missingPromptIndices = []; + const generations = await Promise.all(baseMessages.map(async (baseMessage, index) => { + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache.lookup(prompt, llmStringKey); + if (!result) { + missingPromptIndices.push(index); + } + return result; + })); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; + } + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; + } + _modelType() { + return "base_chat_model"; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this.invocationParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); + } + /** + * Makes a single call to the chat model. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async call(messages, options, callbacks) { + const result = await this.generate([messages.map(index_js_1.coerceMessageLikeToMessage)], options, callbacks); + const generations = result.generations; + return generations[0][0].message; + } + /** + * Makes a single call to the chat model with a prompt value. + * @param promptValue The value of the prompt. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async callPrompt(promptValue, options, callbacks) { + const promptMessages = promptValue.toChatMessages(); + return this.call(promptMessages, options, callbacks); } - - originURL = resolveURL(window.location.href); - /** - * Determine if a URL shares the same origin as the current location - * - * @param {String} requestURL The URL to test - * @returns {boolean} True if URL shares the same origin, otherwise false - */ - return function isURLSameOrigin(requestURL) { - const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; - return (parsed.protocol === originURL.protocol && - parsed.host === originURL.host); - }; - })() : - - // Non standard browser envs (web workers, react-native) lack needed support. - (function nonStandardBrowserEnv() { - return function isURLSameOrigin() { - return true; - }; - })()); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/adapters/xhr.js - - - - - - - - - - - - - - - - -function progressEventReducer(listener, isDownloadStream) { - let bytesNotified = 0; - const _speedometer = helpers_speedometer(50, 250); + * Predicts the next message based on the input messages. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async predictMessages(messages, options, callbacks) { + return this.call(messages, options, callbacks); + } + /** + * Predicts the next message based on a text input. + * @param text The text input. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a string. + */ + async predict(text, options, callbacks) { + const message = new index_js_1.HumanMessage(text); + const result = await this.call([message], options, callbacks); + return result.content; + } +} +exports.BaseChatModel = BaseChatModel; +/** + * An abstract class that extends BaseChatModel and provides a simple + * implementation of _generate. + */ +class SimpleChatModel extends BaseChatModel { + async _generate(messages, options, runManager) { + const text = await this._call(messages, options, runManager); + const message = new index_js_1.AIMessage(text); + return { + generations: [ + { + text: message.content, + message, + }, + ], + }; + } +} +exports.SimpleChatModel = SimpleChatModel; - return e => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : undefined; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; - bytesNotified = loaded; +/***/ }), - const data = { - loaded, - total, - progress: total ? (loaded / total) : undefined, - bytes: progressBytes, - rate: rate ? rate : undefined, - estimated: rate && total && inRange ? (total - loaded) / rate : undefined, - event: e - }; +/***/ 2453: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - data[isDownloadStream ? 'download' : 'upload'] = true; - listener(data); - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PromptLayerChatOpenAI = exports.ChatOpenAI = void 0; +const openai_1 = __nccwpck_require__(47); +const count_tokens_js_1 = __nccwpck_require__(6092); +const index_js_1 = __nccwpck_require__(1445); +const convert_to_openai_js_1 = __nccwpck_require__(1847); +const azure_js_1 = __nccwpck_require__(559); +const env_js_1 = __nccwpck_require__(1548); +const prompt_layer_js_1 = __nccwpck_require__(6738); +const base_js_1 = __nccwpck_require__(3023); +const openai_js_1 = __nccwpck_require__(8734); +function extractGenericMessageCustomRole(message) { + if (message.role !== "system" && + message.role !== "assistant" && + message.role !== "user" && + message.role !== "function") { + console.warn(`Unknown message role: ${message.role}`); + } + return message.role; } - -const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; - -/* harmony default export */ const xhr = (isXHRAdapterSupported && function (config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - let requestData = config.data; - const requestHeaders = core_AxiosHeaders.from(config.headers).normalize(); - const responseType = config.responseType; - let onCanceled; - function done() { - if (config.cancelToken) { - config.cancelToken.unsubscribe(onCanceled); - } - - if (config.signal) { - config.signal.removeEventListener('abort', onCanceled); - } +function messageToOpenAIRole(message) { + const type = message._getType(); + switch (type) { + case "system": + return "system"; + case "ai": + return "assistant"; + case "human": + return "user"; + case "function": + return "function"; + case "generic": { + if (!index_js_1.ChatMessage.isInstance(message)) + throw new Error("Invalid generic chat message"); + return extractGenericMessageCustomRole(message); + } + default: + throw new Error(`Unknown message type: ${type}`); } - - let contentType; - - if (utils.isFormData(requestData)) { - if (node.isStandardBrowserEnv || node.isStandardBrowserWebWorkerEnv) { - requestHeaders.setContentType(false); // Let the browser set it - } else if(!requestHeaders.getContentType(/^\s*multipart\/form-data/)){ - requestHeaders.setContentType('multipart/form-data'); // mobile/desktop app frameworks - } else if(utils.isString(contentType = requestHeaders.getContentType())){ - // fix semicolon duplication issue for ReactNative FormData implementation - requestHeaders.setContentType(contentType.replace(/^\s*(multipart\/form-data);+/, '$1')) - } +} +function openAIResponseToChatMessage(message) { + switch (message.role) { + case "user": + return new index_js_1.HumanMessage(message.content || ""); + case "assistant": + return new index_js_1.AIMessage(message.content || "", { + function_call: message.function_call, + }); + case "system": + return new index_js_1.SystemMessage(message.content || ""); + default: + return new index_js_1.ChatMessage(message.content || "", message.role ?? "unknown"); } - - let request = new XMLHttpRequest(); - - // HTTP basic authentication - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; - requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password)); +} +function _convertDeltaToMessageChunk( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +delta, defaultRole) { + const role = delta.role ?? defaultRole; + const content = delta.content ?? ""; + let additional_kwargs; + if (delta.function_call) { + additional_kwargs = { + function_call: delta.function_call, + }; } - - const fullPath = buildFullPath(config.baseURL, config.url); - - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); - - // Set the request timeout in MS - request.timeout = config.timeout; - - function onloadend() { - if (!request) { - return; - } - // Prepare the response - const responseHeaders = core_AxiosHeaders.from( - 'getAllResponseHeaders' in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; - - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); - - // Clean up request - request = null; + else { + additional_kwargs = {}; + } + if (role === "user") { + return new index_js_1.HumanMessageChunk({ content }); + } + else if (role === "assistant") { + return new index_js_1.AIMessageChunk({ content, additional_kwargs }); + } + else if (role === "system") { + return new index_js_1.SystemMessageChunk({ content }); + } + else if (role === "function") { + return new index_js_1.FunctionMessageChunk({ + content, + additional_kwargs, + name: delta.name, + }); + } + else { + return new index_js_1.ChatMessageChunk({ content, role }); + } +} +/** + * Wrapper around OpenAI large language models that use the Chat endpoint. + * + * To use you should have the `openai` package installed, with the + * `OPENAI_API_KEY` environment variable set. + * + * To use with Azure you should have the `openai` package installed, with the + * `AZURE_OPENAI_API_KEY`, + * `AZURE_OPENAI_API_INSTANCE_NAME`, + * `AZURE_OPENAI_API_DEPLOYMENT_NAME` + * and `AZURE_OPENAI_API_VERSION` environment variable set. + * `AZURE_OPENAI_BASE_PATH` is optional and will override `AZURE_OPENAI_API_INSTANCE_NAME` if you need to use a custom endpoint. + * + * @remarks + * Any parameters that are valid to be passed to {@link + * https://platform.openai.com/docs/api-reference/chat/create | + * `openai.createChatCompletion`} can be passed through {@link modelKwargs}, even + * if not explicitly available on this class. + */ +class ChatOpenAI extends base_js_1.BaseChatModel { + static lc_name() { + return "ChatOpenAI"; + } + get callKeys() { + return [ + ...super.callKeys, + "options", + "function_call", + "functions", + "tools", + "promptIndex", + ]; + } + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION", + }; + } + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + azureOpenAIApiVersion: "azure_openai_api_version", + azureOpenAIApiKey: "azure_openai_api_key", + azureOpenAIApiInstanceName: "azure_openai_api_instance_name", + azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", + }; + } + constructor(fields, + /** @deprecated */ + configuration) { + super(fields ?? {}); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "temperature", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "topP", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "frequencyPenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "presencePenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "n", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "logitBias", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelName", { + enumerable: true, + configurable: true, + writable: true, + value: "gpt-3.5-turbo" + }); + Object.defineProperty(this, "modelKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stop", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "user", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "streaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "openAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiVersion", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiInstanceName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiDeploymentName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIBasePath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "organization", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.openAIApiKey = + fields?.openAIApiKey ?? (0, env_js_1.getEnvironmentVariable)("OPENAI_API_KEY"); + this.azureOpenAIApiKey = + fields?.azureOpenAIApiKey ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_KEY"); + if (!this.azureOpenAIApiKey && !this.openAIApiKey) { + throw new Error("OpenAI or Azure OpenAI API key not found"); + } + this.azureOpenAIApiInstanceName = + fields?.azureOpenAIApiInstanceName ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = + fields?.azureOpenAIApiDeploymentName ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_DEPLOYMENT_NAME"); + this.azureOpenAIApiVersion = + fields?.azureOpenAIApiVersion ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = + fields?.azureOpenAIBasePath ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_BASE_PATH"); + this.organization = + fields?.configuration?.organization ?? + (0, env_js_1.getEnvironmentVariable)("OPENAI_ORGANIZATION"); + this.modelName = fields?.modelName ?? this.modelName; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.maxTokens = fields?.maxTokens; + this.n = fields?.n ?? this.n; + this.logitBias = fields?.logitBias; + this.stop = fields?.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.azureOpenAIApiKey) { + if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { + throw new Error("Azure OpenAI API instance name not found"); + } + if (!this.azureOpenAIApiDeploymentName) { + throw new Error("Azure OpenAI API deployment name not found"); + } + if (!this.azureOpenAIApiVersion) { + throw new Error("Azure OpenAI API version not found"); + } + this.openAIApiKey = this.openAIApiKey ?? ""; + } + this.clientConfig = { + apiKey: this.openAIApiKey, + organization: this.organization, + baseURL: configuration?.basePath ?? fields?.configuration?.basePath, + dangerouslyAllowBrowser: true, + defaultHeaders: configuration?.baseOptions?.headers ?? + fields?.configuration?.baseOptions?.headers, + defaultQuery: configuration?.baseOptions?.params ?? + fields?.configuration?.baseOptions?.params, + ...configuration, + ...fields?.configuration, + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.modelName, + temperature: this.temperature, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens, + n: this.n, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stop, + user: this.user, + stream: this.streaming, + functions: options?.functions ?? + (options?.tools + ? options?.tools.map(convert_to_openai_js_1.formatToOpenAIFunction) + : undefined), + function_call: options?.function_call, + ...this.modelKwargs, + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; } - - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; + async *_streamResponseChunks(messages, options, runManager) { + const messagesMapped = messages.map((message) => ({ + role: messageToOpenAIRole(message), + content: message.content, + name: message.name, + function_call: message.additional_kwargs + .function_call, + })); + const params = { + ...this.invocationParams(options), + messages: messagesMapped, + stream: true, + }; + let defaultRole; + const streamIterable = await this.completionWithRetry(params, options); + for await (const data of streamIterable) { + const choice = data?.choices[0]; + if (!choice) { + continue; + } + const { delta } = choice; + const chunk = _convertDeltaToMessageChunk(delta, defaultRole); + defaultRole = delta.role ?? defaultRole; + const newTokenIndices = { + prompt: options.promptIndex ?? 0, + completion: choice.index ?? 0, + }; + const generationChunk = new index_js_1.ChatGenerationChunk({ + message: chunk, + text: chunk.content, + generationInfo: newTokenIndices, + }); + yield generationChunk; + // eslint-disable-next-line no-void + void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, undefined, undefined, undefined, { chunk: generationChunk }); } - - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; + if (options.signal?.aborted) { + throw new Error("AbortError"); } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } - - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } - - reject(new core_AxiosError('Request aborted', core_AxiosError.ECONNABORTED, config, request)); - - // Clean up request - request = null; - }; - - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(new core_AxiosError('Network Error', core_AxiosError.ERR_NETWORK, config, request)); - - // Clean up request - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = config.transitional || defaults_transitional; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - reject(new core_AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? core_AxiosError.ETIMEDOUT : core_AxiosError.ECONNABORTED, - config, - request)); - - // Clean up request - request = null; - }; - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (node.isStandardBrowserEnv) { - // Add xsrf header - const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) - && config.xsrfCookieName && cookies.read(config.xsrfCookieName); - - if (xsrfValue) { - requestHeaders.set(config.xsrfHeaderName, xsrfValue); - } - } - - // Remove Content-Type if data is undefined - requestData === undefined && requestHeaders.setContentType(null); - - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); } - - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); } - - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = config.responseType; + /** @ignore */ + async _generate(messages, options, runManager) { + const tokenUsage = {}; + const params = this.invocationParams(options); + const messagesMapped = messages.map((message) => ({ + role: messageToOpenAIRole(message), + content: message.content, + name: message.name, + function_call: message.additional_kwargs + .function_call, + })); + if (params.stream) { + const stream = await this._streamResponseChunks(messages, options, runManager); + const finalChunks = {}; + for await (const chunk of stream) { + const index = chunk.generationInfo?.completion ?? 0; + if (finalChunks[index] === undefined) { + finalChunks[index] = chunk; + } + else { + finalChunks[index] = finalChunks[index].concat(chunk); + } + } + const generations = Object.entries(finalChunks) + .sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)) + .map(([_, value]) => value); + return { generations }; + } + else { + const data = await this.completionWithRetry({ + ...params, + stream: false, + messages: messagesMapped, + }, { + signal: options?.signal, + ...options?.options, + }); + const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data?.usage ?? {}; + if (completionTokens) { + tokenUsage.completionTokens = + (tokenUsage.completionTokens ?? 0) + completionTokens; + } + if (promptTokens) { + tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; + } + if (totalTokens) { + tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; + } + const generations = []; + for (const part of data?.choices ?? []) { + const text = part.message?.content ?? ""; + const generation = { + text, + message: openAIResponseToChatMessage(part.message ?? { role: "assistant" }), + }; + if (part.finish_reason) { + generation.generationInfo = { finish_reason: part.finish_reason }; + } + generations.push(generation); + } + return { + generations, + llmOutput: { tokenUsage }, + }; + } } - - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true)); + async getNumTokensFromMessages(messages) { + let totalCount = 0; + let tokensPerMessage = 0; + let tokensPerName = 0; + // From: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb + if ((0, count_tokens_js_1.getModelNameForTiktoken)(this.modelName) === "gpt-3.5-turbo") { + tokensPerMessage = 4; + tokensPerName = -1; + } + else if ((0, count_tokens_js_1.getModelNameForTiktoken)(this.modelName).startsWith("gpt-4")) { + tokensPerMessage = 3; + tokensPerName = 1; + } + const countPerMessage = await Promise.all(messages.map(async (message) => { + const textCount = await this.getNumTokens(message.content); + const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); + const nameCount = message.name !== undefined + ? tokensPerName + (await this.getNumTokens(message.name)) + : 0; + const count = textCount + tokensPerMessage + roleCount + nameCount; + totalCount += count; + return count; + })); + totalCount += 3; // every reply is primed with <|start|>assistant<|message|> + return { totalCount, countPerMessage }; } - - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress)); + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.chat.completions.create(request, requestOptions); + return res; + } + catch (e) { + const error = (0, openai_js_1.wrapOpenAIClientError)(e); + throw error; + } + }); } - - if (config.cancelToken || config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = cancel => { - if (!request) { - return; + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + baseURL: this.clientConfig.baseURL, + }; + const endpoint = (0, azure_js_1.getEndpoint)(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0, + }; + if (!params.baseURL) { + delete params.baseURL; + } + this.client = new openai_1.OpenAI(params); } - reject(!cancel || cancel.type ? new cancel_CanceledError(null, config, request) : cancel); - request.abort(); - request = null; - }; - - config.cancelToken && config.cancelToken.subscribe(onCanceled); - if (config.signal) { - config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled); - } + const requestOptions = { + ...this.clientConfig, + ...options, + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers, + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query, + }; + } + return requestOptions; } - - const protocol = parseProtocol(fullPath); - - if (protocol && node.protocols.indexOf(protocol) === -1) { - reject(new core_AxiosError('Unsupported protocol ' + protocol + ':', core_AxiosError.ERR_BAD_REQUEST, config)); - return; + _llmType() { + return "openai"; + } + /** @ignore */ + _combineLLMOutput(...llmOutputs) { + return llmOutputs.reduce((acc, llmOutput) => { + if (llmOutput && llmOutput.tokenUsage) { + acc.tokenUsage.completionTokens += + llmOutput.tokenUsage.completionTokens ?? 0; + acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; + acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; + } + return acc; + }, { + tokenUsage: { + completionTokens: 0, + promptTokens: 0, + totalTokens: 0, + }, + }); } - - - // Send the request - request.send(requestData || null); - }); -}); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/adapters/adapters.js - - - - - -const knownAdapters = { - http: http, - xhr: xhr } - -utils.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, 'name', {value}); - } catch (e) { - // eslint-disable-next-line no-empty +exports.ChatOpenAI = ChatOpenAI; +class PromptLayerChatOpenAI extends ChatOpenAI { + constructor(fields) { + super(fields); + Object.defineProperty(this, "promptLayerApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "plTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnPromptLayerId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.promptLayerApiKey = + fields?.promptLayerApiKey ?? + (typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.PROMPTLAYER_API_KEY + : undefined); + this.plTags = fields?.plTags ?? []; + this.returnPromptLayerId = fields?.returnPromptLayerId ?? false; } - Object.defineProperty(fn, 'adapterName', {value}); - } -}); - -const renderReason = (reason) => `- ${reason}`; - -const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false; - -/* harmony default export */ const adapters = ({ - getAdapter: (adapters) => { - adapters = utils.isArray(adapters) ? adapters : [adapters]; - - const {length} = adapters; - let nameOrAdapter; - let adapter; - - const rejectedReasons = {}; - - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id; - - adapter = nameOrAdapter; - - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; - - if (adapter === undefined) { - throw new core_AxiosError(`Unknown adapter '${id}'`); + async _generate(messages, options, runManager) { + const requestStartTime = Date.now(); + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; } - } - - if (adapter) { - break; - } - - rejectedReasons[id || '#' + i] = adapter; - } - - if (!adapter) { - - const reasons = Object.entries(rejectedReasons) - .map(([id, state]) => `adapter ${id} ` + - (state === false ? 'is not supported by the environment' : 'is not available in the build') - ); - - let s = length ? - (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : - 'as no adapter specified'; - - throw new core_AxiosError( - `There is no suitable adapter to dispatch the request ` + s, - 'ERR_NOT_SUPPORT' - ); - } - - return adapter; - }, - adapters: knownAdapters -}); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/dispatchRequest.js - - - - - - - - - -/** - * Throws a `CanceledError` if cancellation has been requested. - * - * @param {Object} config The config that is to be used for the request - * - * @returns {void} - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } - - if (config.signal && config.signal.aborted) { - throw new cancel_CanceledError(null, config); - } -} - -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * - * @returns {Promise} The Promise to be fulfilled - */ -function dispatchRequest(config) { - throwIfCancellationRequested(config); - - config.headers = core_AxiosHeaders.from(config.headers); - - // Transform request data - config.data = transformData.call( - config, - config.transformRequest - ); - - if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { - config.headers.setContentType('application/x-www-form-urlencoded', false); - } - - const adapter = adapters.getAdapter(config.adapter || lib_defaults.adapter); - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); - - // Transform response data - response.data = transformData.call( - config, - config.transformResponse, - response - ); - - response.headers = core_AxiosHeaders.from(response.headers); - - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = core_AxiosHeaders.from(reason.response.headers); - } + else if (options?.timeout && !options.signal) { + parsedOptions = { + ...options, + signal: AbortSignal.timeout(options.timeout), + }; + } + else { + parsedOptions = options ?? {}; + } + const generatedResponses = await super._generate(messages, parsedOptions, runManager); + const requestEndTime = Date.now(); + const _convertMessageToDict = (message) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let messageDict; + if (message._getType() === "human") { + messageDict = { role: "user", content: message.content }; + } + else if (message._getType() === "ai") { + messageDict = { role: "assistant", content: message.content }; + } + else if (message._getType() === "function") { + messageDict = { role: "assistant", content: message.content }; + } + else if (message._getType() === "system") { + messageDict = { role: "system", content: message.content }; + } + else if (message._getType() === "generic") { + messageDict = { + role: message.role, + content: message.content, + }; + } + else { + throw new Error(`Got unknown type ${message}`); + } + return messageDict; + }; + const _createMessageDicts = (messages, callOptions) => { + const params = { + ...this.invocationParams(), + model: this.modelName, + }; + if (callOptions?.stop) { + if (Object.keys(params).includes("stop")) { + throw new Error("`stop` found in both the input and default params."); + } + } + const messageDicts = messages.map((message) => _convertMessageToDict(message)); + return messageDicts; + }; + for (let i = 0; i < generatedResponses.generations.length; i += 1) { + const generation = generatedResponses.generations[i]; + const messageDicts = _createMessageDicts(messages, parsedOptions); + let promptLayerRequestId; + const parsedResp = [ + { + content: generation.text, + role: messageToOpenAIRole(generation.message), + }, + ]; + const promptLayerRespBody = await (0, prompt_layer_js_1.promptLayerTrackRequest)(this.caller, "langchain.PromptLayerChatOpenAI", { ...this._identifyingParams(), messages: messageDicts, stream: false }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); + if (this.returnPromptLayerId === true) { + if (promptLayerRespBody.success === true) { + promptLayerRequestId = promptLayerRespBody.request_id; + } + if (!generation.generationInfo || + typeof generation.generationInfo !== "object") { + generation.generationInfo = {}; + } + generation.generationInfo.promptLayerRequestId = promptLayerRequestId; + } + } + return generatedResponses; } - - return Promise.reject(reason); - }); } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/mergeConfig.js - +exports.PromptLayerChatOpenAI = PromptLayerChatOpenAI; +/***/ }), +/***/ 4848: +/***/ ((__unused_webpack_module, exports) => { -const headersToObject = (thing) => thing instanceof core_AxiosHeaders ? thing.toJSON() : thing; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Document = void 0; /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * - * @returns {Object} New object resulting from merging config2 to config1 + * Interface for interacting with a document. */ -function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - const config = {}; - - function getMergedValue(target, source, caseless) { - if (utils.isPlainObject(target) && utils.isPlainObject(source)) { - return utils.merge.call({caseless}, target, source); - } else if (utils.isPlainObject(source)) { - return utils.merge({}, source); - } else if (utils.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(a, b, caseless) { - if (!utils.isUndefined(b)) { - return getMergedValue(a, b, caseless); - } else if (!utils.isUndefined(a)) { - return getMergedValue(undefined, a, caseless); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(a, b) { - if (!utils.isUndefined(b)) { - return getMergedValue(undefined, b); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(a, b) { - if (!utils.isUndefined(b)) { - return getMergedValue(undefined, b); - } else if (!utils.isUndefined(a)) { - return getMergedValue(undefined, a); - } - } - - // eslint-disable-next-line consistent-return - function mergeDirectKeys(a, b, prop) { - if (prop in config2) { - return getMergedValue(a, b); - } else if (prop in config1) { - return getMergedValue(undefined, a); +class Document { + constructor(fields) { + Object.defineProperty(this, "pageContent", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.pageContent = fields.pageContent + ? fields.pageContent.toString() + : this.pageContent; + this.metadata = fields.metadata ?? {}; } - } - - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true) - }; - - utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) { - const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; } - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/validator.js - - +exports.Document = Document; +/***/ }), -const validators = {}; - -// eslint-disable-next-line func-names -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { - validators[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; -}); +/***/ 9892: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const deprecatedWarnings = {}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LLM = exports.BaseLLM = void 0; +const index_js_1 = __nccwpck_require__(1445); +const index_js_2 = __nccwpck_require__(6691); +const manager_js_1 = __nccwpck_require__(5128); +const base_js_1 = __nccwpck_require__(4235); /** - * Transitional option validator - * - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * - * @returns {function} + * LLM Wrapper. Provides an {@link call} (an {@link generate}) function that takes in a prompt (or prompts) and returns a string. */ -validators.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } - - // eslint-disable-next-line func-names - return (value, opt, opts) => { - if (validator === false) { - throw new core_AxiosError( - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - core_AxiosError.ERR_DEPRECATED - ); +class BaseLLM extends index_js_2.BaseLanguageModel { + constructor({ concurrency, ...rest }) { + super(concurrency ? { maxConcurrency: concurrency, ...rest } : rest); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain", "llms", this._llmType()] + }); } - - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) - ); + /** + * This method takes an input and options, and returns a string. It + * converts the input to a prompt value and generates a result based on + * the prompt. + * @param input Input for the LLM. + * @param options Options for the LLM call. + * @returns A string result based on the prompt. + */ + async invoke(input, options) { + const promptValue = BaseLLM._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + return result.generations[0][0].text; } - - return validator ? validator(value, opt, opts) : true; - }; -}; - -/** - * Assert object's properties type - * - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - * - * @returns {object} - */ - -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new core_AxiosError('options must be an object', core_AxiosError.ERR_BAD_OPTION_VALUE); - } - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator = schema[opt]; - if (validator) { - const value = options[opt]; - const result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new core_AxiosError('option ' + opt + ' must be ' + result, core_AxiosError.ERR_BAD_OPTION_VALUE); - } - continue; + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_input, _options, _runManager) { + throw new Error("Not implemented."); } - if (allowUnknown !== true) { - throw new core_AxiosError('Unknown option ' + opt, core_AxiosError.ERR_BAD_OPTION); + _separateRunnableConfigFromCallOptions(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + if (callOptions?.timeout && !callOptions.signal) { + callOptions.signal = AbortSignal.timeout(callOptions.timeout); + } + return [runnableConfig, callOptions]; } - } -} - -/* harmony default export */ const validator = ({ - assertOptions, - validators -}); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/core/Axios.js - - - - - - - - - - - -const Axios_validators = validator.validators; - -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - * - * @return {Axios} A new instance of Axios - */ -class Axios { - constructor(instanceConfig) { - this.defaults = instanceConfig; - this.interceptors = { - request: new core_InterceptorManager(), - response: new core_InterceptorManager() - }; - } - - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - request(configOrUrl, config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof configOrUrl === 'string') { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; + async *_streamIterator(input, options) { + // Subclass check required to avoid double callbacks with default implementation + if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) { + yield this.invoke(input, options); + } + else { + const prompt = BaseLLM._convertInputToPromptValue(input); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(options); + const callbackManager_ = await manager_js_1.CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], undefined, undefined, extra); + let generation = new index_js_1.GenerationChunk({ + text: "", + }); + try { + for await (const chunk of this._streamResponseChunks(input.toString(), callOptions, runManagers?.[0])) { + if (!generation) { + generation = chunk; + } + else { + generation = generation.concat(chunk); + } + if (typeof chunk.text === "string") { + yield chunk.text; + } + } + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + generations: [[generation]], + }))); + } } - - config = mergeConfig(this.defaults, config); - - const {transitional, paramsSerializer, headers} = config; - - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: Axios_validators.transitional(Axios_validators.boolean), - forcedJSONParsing: Axios_validators.transitional(Axios_validators.boolean), - clarifyTimeoutError: Axios_validators.transitional(Axios_validators.boolean) - }, false); + /** + * This method takes prompt values, options, and callbacks, and generates + * a result based on the prompts. + * @param promptValues Prompt values for the LLM. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns An LLMResult based on the prompts. + */ + async generatePrompt(promptValues, options, callbacks) { + const prompts = promptValues.map((promptValue) => promptValue.toString()); + return this.generate(prompts, options, callbacks); } - - if (paramsSerializer != null) { - if (utils.isFunction(paramsSerializer)) { - config.paramsSerializer = { - serialize: paramsSerializer + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; + } + _flattenLLMResult(llmResult) { + const llmResults = []; + for (let i = 0; i < llmResult.generations.length; i += 1) { + const genList = llmResult.generations[i]; + if (i === 0) { + llmResults.push({ + generations: [genList], + llmOutput: llmResult.llmOutput, + }); + } + else { + const llmOutput = llmResult.llmOutput + ? { ...llmResult.llmOutput, tokenUsage: {} } + : undefined; + llmResults.push({ + generations: [genList], + llmOutput, + }); + } } - } else { - validator.assertOptions(paramsSerializer, { - encode: Axios_validators.function, - serialize: Axios_validators.function - }, true); - } + return llmResults; } - - // Set config.method - config.method = (config.method || this.defaults.method || 'get').toLowerCase(); - - // Flatten headers - let contextHeaders = headers && utils.merge( - headers.common, - headers[config.method] - ); - - headers && utils.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - (method) => { - delete headers[method]; - } - ); - - config.headers = core_AxiosHeaders.concat(contextHeaders, headers); - - // filter out skipped interceptors - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; - - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); - - let promise; - let i = 0; - let len; - - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), undefined]; - chain.unshift.apply(chain, requestInterceptorChain); - chain.push.apply(chain, responseInterceptorChain); - len = chain.length; - - promise = Promise.resolve(config); - - while (i < len) { - promise = promise.then(chain[i++], chain[i++]); - } - - return promise; + /** @ignore */ + async _generateUncached(prompts, parsedOptions, handledOptions) { + const callbackManager_ = await manager_js_1.CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, undefined, undefined, extra); + let output; + try { + output = await this._generate(prompts, parsedOptions, runManagers?.[0]); + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + const flattenedOutputs = this._flattenLLMResult(output); + await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); + const runIds = runManagers?.map((manager) => manager.runId) || undefined; + // This defines RUN_KEY as a non-enumerable property on the output object + // so that it is not serialized when the output is stringified, and so that + // it isnt included when listing the keys of the output object. + Object.defineProperty(output, index_js_1.RUN_KEY, { + value: runIds ? { runIds } : undefined, + configurable: true, + }); + return output; + } + /** + * Run the LLM on the given prompts and input, handling caching. + */ + async generate(prompts, options, callbacks) { + if (!Array.isArray(prompts)) { + throw new Error("Argument 'prompts' is expected to be a string[]"); + } + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; + } + else { + parsedOptions = options; + } + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptions(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(prompts, callOptions, runnableConfig); + } + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const missingPromptIndices = []; + const generations = await Promise.all(prompts.map(async (prompt, index) => { + const result = await cache.lookup(prompt, llmStringKey); + if (!result) { + missingPromptIndices.push(index); + } + return result; + })); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + return cache.update(prompts[promptIndex], llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; } - - len = requestInterceptorChain.length; - - let newConfig = config; - - i = 0; - - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; - } + /** + * Convenience wrapper for {@link generate} that takes in a single string prompt and returns a single string output. + */ + async call(prompt, options, callbacks) { + const { generations } = await this.generate([prompt], options, callbacks); + return generations[0][0].text; } - - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); + /** + * This method is similar to `call`, but it's used for making predictions + * based on the input text. + * @param text Input text for the prediction. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns A prediction based on the input text. + */ + async predict(text, options, callbacks) { + return this.call(text, options, callbacks); } - - i = 0; - len = responseInterceptorChain.length; - - while (i < len) { - promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); + /** + * This method takes a list of messages, options, and callbacks, and + * returns a predicted message. + * @param messages A list of messages for the prediction. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns A predicted message based on the list of messages. + */ + async predictMessages(messages, options, callbacks) { + const text = (0, base_js_1.getBufferString)(messages); + const prediction = await this.call(text, options, callbacks); + return new index_js_1.AIMessage(prediction); + } + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + _modelType() { + return "base_llm"; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(data) { + const { _type, _model, ...rest } = data; + if (_model && _model !== "base_llm") { + throw new Error(`Cannot load LLM with model ${_model}`); + } + const Cls = { + openai: (await Promise.all(/* import() */[__nccwpck_require__.e(657), __nccwpck_require__.e(679), __nccwpck_require__.e(366), __nccwpck_require__.e(624)]).then(__nccwpck_require__.bind(__nccwpck_require__, 4624))).OpenAI, + }[_type]; + if (Cls === undefined) { + throw new Error(`Cannot load LLM with type ${_type}`); + } + return new Cls(rest); } - - return promise; - } - - getUri(config) { - config = mergeConfig(this.defaults, config); - const fullPath = buildFullPath(config.baseURL, config.url); - return buildURL(fullPath, config.params, config.paramsSerializer); - } } - -// Provide aliases for supported request methods -utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: (config || {}).data - })); - }; -}); - -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url, - data - })); - }; - } - - Axios.prototype[method] = generateHTTPMethod(); - - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); -}); - -/* harmony default export */ const core_Axios = (Axios); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/cancel/CancelToken.js - - - - +exports.BaseLLM = BaseLLM; /** - * A `CancelToken` is an object that can be used to request cancellation of an operation. + * LLM class that provides a simpler interface to subclass than {@link BaseLLM}. * - * @param {Function} executor The executor function. + * Requires only implementing a simpler {@link _call} method instead of {@link _generate}. * - * @returns {CancelToken} + * @augments BaseLLM */ -class CancelToken { - constructor(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); +class LLM extends BaseLLM { + async _generate(prompts, options, runManager) { + const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { ...options, promptIndex }, runManager).then((text) => [{ text }]))); + return { generations }; } +} +exports.LLM = LLM; - let resolvePromise; - - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - - const token = this; - - // eslint-disable-next-line func-names - this.promise.then(cancel => { - if (!token._listeners) return; - - let i = token._listeners.length; - - while (i-- > 0) { - token._listeners[i](cancel); - } - token._listeners = null; - }); - - // eslint-disable-next-line func-names - this.promise.then = onfulfilled => { - let _resolve; - // eslint-disable-next-line func-names - const promise = new Promise(resolve => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; - return promise; - }; +/***/ }), - executor(function cancel(message, config, request) { - if (token.reason) { - // Cancellation has already been requested - return; - } +/***/ 5547: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - token.reason = new cancel_CanceledError(message, config, request); - resolvePromise(token.reason); - }); - } - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) { - throw this.reason; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PromptLayerOpenAIChat = exports.OpenAIChat = void 0; +const openai_1 = __nccwpck_require__(47); +const index_js_1 = __nccwpck_require__(1445); +const azure_js_1 = __nccwpck_require__(559); +const env_js_1 = __nccwpck_require__(1548); +const prompt_layer_js_1 = __nccwpck_require__(6738); +const base_js_1 = __nccwpck_require__(9892); +const openai_js_1 = __nccwpck_require__(8734); +/** + * Wrapper around OpenAI large language models that use the Chat endpoint. + * + * To use you should have the `openai` package installed, with the + * `OPENAI_API_KEY` environment variable set. + * + * To use with Azure you should have the `openai` package installed, with the + * `AZURE_OPENAI_API_KEY`, + * `AZURE_OPENAI_API_INSTANCE_NAME`, + * `AZURE_OPENAI_API_DEPLOYMENT_NAME` + * and `AZURE_OPENAI_API_VERSION` environment variable set. + * + * @remarks + * Any parameters that are valid to be passed to {@link + * https://platform.openai.com/docs/api-reference/chat/create | + * `openai.createCompletion`} can be passed through {@link modelKwargs}, even + * if not explicitly available on this class. + * + * @augments BaseLLM + * @augments OpenAIInput + * @augments AzureOpenAIChatInput + */ +class OpenAIChat extends base_js_1.LLM { + static lc_name() { + return "OpenAIChat"; + } + get callKeys() { + return [...super.callKeys, "options", "promptIndex"]; + } + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION", + }; + } + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + azureOpenAIApiVersion: "azure_openai_api_version", + azureOpenAIApiKey: "azure_openai_api_key", + azureOpenAIApiInstanceName: "azure_openai_api_instance_name", + azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", + }; + } + constructor(fields, + /** @deprecated */ + configuration) { + super(fields ?? {}); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "temperature", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "topP", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "frequencyPenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "presencePenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "n", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "logitBias", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelName", { + enumerable: true, + configurable: true, + writable: true, + value: "gpt-3.5-turbo" + }); + Object.defineProperty(this, "prefixMessages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "modelKwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stop", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "user", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "streaming", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "openAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiVersion", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiInstanceName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIApiDeploymentName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "azureOpenAIBasePath", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "organization", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.openAIApiKey = + fields?.openAIApiKey ?? (0, env_js_1.getEnvironmentVariable)("OPENAI_API_KEY"); + this.azureOpenAIApiKey = + fields?.azureOpenAIApiKey ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_KEY"); + if (!this.azureOpenAIApiKey && !this.openAIApiKey) { + throw new Error("OpenAI or Azure OpenAI API key not found"); + } + this.azureOpenAIApiInstanceName = + fields?.azureOpenAIApiInstanceName ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = + (fields?.azureOpenAIApiCompletionsDeploymentName || + fields?.azureOpenAIApiDeploymentName) ?? + ((0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_DEPLOYMENT_NAME")); + this.azureOpenAIApiVersion = + fields?.azureOpenAIApiVersion ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = + fields?.azureOpenAIBasePath ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_BASE_PATH"); + this.organization = + fields?.configuration?.organization ?? + (0, env_js_1.getEnvironmentVariable)("OPENAI_ORGANIZATION"); + this.modelName = fields?.modelName ?? this.modelName; + this.prefixMessages = fields?.prefixMessages ?? this.prefixMessages; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.n = fields?.n ?? this.n; + this.logitBias = fields?.logitBias; + this.maxTokens = fields?.maxTokens; + this.stop = fields?.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.n > 1) { + throw new Error("Cannot use n > 1 in OpenAIChat LLM. Use ChatOpenAI Chat Model instead."); + } + if (this.azureOpenAIApiKey) { + if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { + throw new Error("Azure OpenAI API instance name not found"); + } + if (!this.azureOpenAIApiDeploymentName) { + throw new Error("Azure OpenAI API deployment name not found"); + } + if (!this.azureOpenAIApiVersion) { + throw new Error("Azure OpenAI API version not found"); + } + this.openAIApiKey = this.openAIApiKey ?? ""; + } + this.clientConfig = { + apiKey: this.openAIApiKey, + organization: this.organization, + baseURL: configuration?.basePath ?? fields?.configuration?.basePath, + dangerouslyAllowBrowser: true, + defaultHeaders: configuration?.baseOptions?.headers ?? + fields?.configuration?.baseOptions?.headers, + defaultQuery: configuration?.baseOptions?.params ?? + fields?.configuration?.baseOptions?.params, + ...configuration, + ...fields?.configuration, + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.modelName, + temperature: this.temperature, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + n: this.n, + logit_bias: this.logitBias, + max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens, + stop: options?.stop ?? this.stop, + user: this.user, + stream: this.streaming, + ...this.modelKwargs, + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + /** + * Formats the messages for the OpenAI API. + * @param prompt The prompt to be formatted. + * @returns Array of formatted messages. + */ + formatMessages(prompt) { + const message = { + role: "user", + content: prompt, + }; + return this.prefixMessages ? [...this.prefixMessages, message] : [message]; } - } - - /** - * Subscribe to the cancel signal - */ - - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; + async *_streamResponseChunks(prompt, options, runManager) { + const params = { + ...this.invocationParams(options), + messages: this.formatMessages(prompt), + stream: true, + }; + const stream = await this.completionWithRetry(params, options); + for await (const data of stream) { + const choice = data?.choices[0]; + if (!choice) { + continue; + } + const { delta } = choice; + const generationChunk = new index_js_1.GenerationChunk({ + text: delta.content ?? "", + }); + yield generationChunk; + const newTokenIndices = { + prompt: options.promptIndex ?? 0, + completion: choice.index ?? 0, + }; + // eslint-disable-next-line no-void + void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices); + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; + /** @ignore */ + async _call(prompt, options, runManager) { + const params = this.invocationParams(options); + if (params.stream) { + const stream = await this._streamResponseChunks(prompt, options, runManager); + let finalChunk; + for await (const chunk of stream) { + if (finalChunk === undefined) { + finalChunk = chunk; + } + else { + finalChunk = finalChunk.concat(chunk); + } + } + return finalChunk?.text ?? ""; + } + else { + const response = await this.completionWithRetry({ + ...params, + stream: false, + messages: this.formatMessages(prompt), + }, { + signal: options.signal, + ...options.options, + }); + return response?.choices[0]?.message?.content ?? ""; + } } - } - - /** - * Unsubscribe from the cancel signal - */ - - unsubscribe(listener) { - if (!this._listeners) { - return; + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.chat.completions.create(request, requestOptions); + return res; + } + catch (e) { + const error = (0, openai_js_1.wrapOpenAIClientError)(e); + throw error; + } + }); } - const index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); + /** @ignore */ + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + baseURL: this.clientConfig.baseURL, + }; + const endpoint = (0, azure_js_1.getEndpoint)(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0, + }; + if (!params.baseURL) { + delete params.baseURL; + } + this.client = new openai_1.OpenAI(params); + } + const requestOptions = { + ...this.clientConfig, + ...options, + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers, + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query, + }; + } + return requestOptions; + } + _llmType() { + return "openai"; } - } - - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - const token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token, - cancel - }; - } } - -/* harmony default export */ const cancel_CancelToken = (CancelToken); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/spread.js - - +exports.OpenAIChat = OpenAIChat; /** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * - * @returns {Function} + * PromptLayer wrapper to OpenAIChat */ -function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; +class PromptLayerOpenAIChat extends OpenAIChat { + get lc_secrets() { + return { + promptLayerApiKey: "PROMPTLAYER_API_KEY", + }; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "promptLayerApiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "plTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "returnPromptLayerId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.plTags = fields?.plTags ?? []; + this.returnPromptLayerId = fields?.returnPromptLayerId ?? false; + this.promptLayerApiKey = + fields?.promptLayerApiKey ?? + (0, env_js_1.getEnvironmentVariable)("PROMPTLAYER_API_KEY"); + if (!this.promptLayerApiKey) { + throw new Error("Missing PromptLayer API key"); + } + } + async _generate(prompts, options, runManager) { + let choice; + const generations = await Promise.all(prompts.map(async (prompt) => { + const requestStartTime = Date.now(); + const text = await this._call(prompt, options, runManager); + const requestEndTime = Date.now(); + choice = [{ text }]; + const parsedResp = { + text, + }; + const promptLayerRespBody = await (0, prompt_layer_js_1.promptLayerTrackRequest)(this.caller, "langchain.PromptLayerOpenAIChat", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { ...this._identifyingParams(), prompt }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); + if (this.returnPromptLayerId === true && + promptLayerRespBody.success === true) { + choice[0].generationInfo = { + promptLayerRequestId: promptLayerRespBody.request_id, + }; + } + return choice; + })); + return { generations }; + } } +exports.PromptLayerOpenAIChat = PromptLayerOpenAIChat; -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/isAxiosError.js +/***/ }), +/***/ 361: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PromptLayerOpenAIChat = exports.OpenAIChat = exports.PromptLayerOpenAI = exports.OpenAI = void 0; +const openai_1 = __nccwpck_require__(47); +const count_tokens_js_1 = __nccwpck_require__(6092); +const index_js_1 = __nccwpck_require__(1445); +const azure_js_1 = __nccwpck_require__(559); +const chunk_js_1 = __nccwpck_require__(1769); +const env_js_1 = __nccwpck_require__(1548); +const prompt_layer_js_1 = __nccwpck_require__(6738); +const base_js_1 = __nccwpck_require__(9892); +const openai_chat_js_1 = __nccwpck_require__(5547); +const openai_js_1 = __nccwpck_require__(8734); /** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test + * Wrapper around OpenAI large language models. * - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -function isAxiosError(payload) { - return utils.isObject(payload) && (payload.isAxiosError === true); -} - -;// CONCATENATED MODULE: ./node_modules/axios/lib/helpers/HttpStatusCode.js -const HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511, -}; - -Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; -}); - -/* harmony default export */ const helpers_HttpStatusCode = (HttpStatusCode); - -;// CONCATENATED MODULE: ./node_modules/axios/lib/axios.js - - - - - - - - - - - - - - - - - - - - -/** - * Create an instance of Axios + * To use you should have the `openai` package installed, with the + * `OPENAI_API_KEY` environment variable set. * - * @param {Object} defaultConfig The default config for the instance + * To use with Azure you should have the `openai` package installed, with the + * `AZURE_OPENAI_API_KEY`, + * `AZURE_OPENAI_API_INSTANCE_NAME`, + * `AZURE_OPENAI_API_DEPLOYMENT_NAME` + * and `AZURE_OPENAI_API_VERSION` environment variable set. * - * @returns {Axios} A new instance of Axios + * @remarks + * Any parameters that are valid to be passed to {@link + * https://platform.openai.com/docs/api-reference/completions/create | + * `openai.createCompletion`} can be passed through {@link modelKwargs}, even + * if not explicitly available on this class. */ -function createInstance(defaultConfig) { - const context = new core_Axios(defaultConfig); - const instance = bind(core_Axios.prototype.request, context); - - // Copy axios.prototype to instance - utils.extend(instance, core_Axios.prototype, context, {allOwnKeys: true}); - - // Copy context to instance - utils.extend(instance, context, null, {allOwnKeys: true}); - - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; - - return instance; -} - -// Create the default instance to be exported -const axios = createInstance(lib_defaults); - -// Expose Axios class to allow class inheritance -axios.Axios = core_Axios; - -// Expose Cancel & CancelToken -axios.CanceledError = cancel_CanceledError; -axios.CancelToken = cancel_CancelToken; -axios.isCancel = isCancel; -axios.VERSION = VERSION; -axios.toFormData = helpers_toFormData; - -// Expose AxiosError class -axios.AxiosError = core_AxiosError; - -// alias for CanceledError for backward compatibility -axios.Cancel = axios.CanceledError; - -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; - -axios.spread = spread; - -// Expose isAxiosError -axios.isAxiosError = isAxiosError; - -// Expose mergeConfig -axios.mergeConfig = mergeConfig; - -axios.AxiosHeaders = core_AxiosHeaders; - -axios.formToJSON = thing => helpers_formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing); - -axios.getAdapter = adapters.getAdapter; - -axios.HttpStatusCode = helpers_HttpStatusCode; - -axios.default = axios; - -// this module should only have a default export -/* harmony default export */ const lib_axios = (axios); - -;// CONCATENATED MODULE: ./src/utils.ts - -class Logger { - static log(...args) { - const message = args.map(arg => JSON.stringify(arg)).join(' '); - core.info(message); - } - static warn(message) { - core.warning(message); +class OpenAI extends base_js_1.BaseLLM { + static lc_name() { + return "OpenAI"; } - static error(message, ...args) { - const formattedArgs = args.map(arg => JSON.stringify(arg)).join(' '); - core.error(`${message}: ${formattedArgs}`); + get callKeys() { + return [...super.callKeys, "options"]; } -} - -;// CONCATENATED MODULE: ./src/steps/get-changes.ts - - - - -async function getChanges(pullRequestNumber) { - try { - Logger.log('getting changes', pullRequestNumber); - const githubToken = core.getInput('token'); - const octokit = github.getOctokit(githubToken); - const repo = github.context.repo; - const { data: files } = await octokit.rest.pulls.get({ - ...repo, - pull_number: pullRequestNumber, - mediaType: { - format: 'diff' - } - }); - Logger.log('got changes diff', files); - const response = await lib_axios.get(files.diff_url); - Logger.log('diff', response.data); - return response.data; + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION", + }; } - catch (error) { - Logger.error('error getting changes'); + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + azureOpenAIApiVersion: "azure_openai_api_version", + azureOpenAIApiKey: "azure_openai_api_key", + azureOpenAIApiInstanceName: "azure_openai_api_instance_name", + azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name", + }; } -} - -;// CONCATENATED MODULE: ./src/steps/post-comment.ts - - - -async function postComment(pullRequestNumber, summary) { - const githubToken = core.getInput('token'); - const octokit = github.getOctokit(githubToken); - const repo = github.context.repo; - Logger.log('posted comment', github.context); - const { data } = await octokit.rest.pulls.update({ - ...repo, - pull_number: pullRequestNumber, - body: summary - }); - Logger.log('posted comment', data.body); -} - -// EXTERNAL MODULE: ./node_modules/langchain/dist/llms/openai.js + 3 modules -var openai = __nccwpck_require__(4624); -;// CONCATENATED MODULE: ./node_modules/langchain/llms/openai.js - -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/base.js -var base = __nccwpck_require__(3197); -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/llm_chain.js + 1 modules -var llm_chain = __nccwpck_require__(7287); -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/api/api_chain.js + 1 modules -var api_chain = __nccwpck_require__(6159); -// EXTERNAL MODULE: ./node_modules/langchain/dist/prompts/prompt.js -var prompts_prompt = __nccwpck_require__(3379); -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/index.js -var schema = __nccwpck_require__(8102); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/stores/message/in_memory.js - -/** - * Class for storing chat message history in-memory. It extends the - * BaseListChatMessageHistory class and provides methods to get, add, and - * clear messages. - */ -class in_memory_ChatMessageHistory extends (/* unused pure expression or super */ null && (BaseListChatMessageHistory)) { - constructor(messages) { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { + constructor(fields, + /** @deprecated */ + configuration) { + if ((fields?.modelName?.startsWith("gpt-3.5-turbo") || + fields?.modelName?.startsWith("gpt-4")) && + !fields?.modelName?.includes("-instruct")) { + // eslint-disable-next-line no-constructor-return + return new openai_chat_js_1.OpenAIChat(fields, configuration); + } + super(fields ?? {}); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "temperature", { + enumerable: true, + configurable: true, + writable: true, + value: 0.7 + }); + Object.defineProperty(this, "maxTokens", { + enumerable: true, + configurable: true, + writable: true, + value: 256 + }); + Object.defineProperty(this, "topP", { + enumerable: true, + configurable: true, + writable: true, + value: 1 + }); + Object.defineProperty(this, "frequencyPenalty", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "presencePenalty", { enumerable: true, configurable: true, writable: true, - value: ["langchain", "stores", "message", "in_memory"] + value: 0 }); - Object.defineProperty(this, "messages", { + Object.defineProperty(this, "n", { enumerable: true, configurable: true, writable: true, - value: [] + value: 1 }); - this.messages = messages ?? []; - } - /** - * Method to get all the messages stored in the ChatMessageHistory - * instance. - * @returns Array of stored BaseMessage instances. - */ - async getMessages() { - return this.messages; - } - /** - * Method to add a new message to the ChatMessageHistory instance. - * @param message The BaseMessage instance to add. - * @returns A promise that resolves when the message has been added. - */ - async addMessage(message) { - this.messages.push(message); - } - /** - * Method to clear all the messages from the ChatMessageHistory instance. - * @returns A promise that resolves when all messages have been cleared. - */ - async clear() { - this.messages = []; - } -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/memory/chat_memory.js - - -/** - * Abstract class that provides a base for implementing different types of - * memory systems. It is designed to maintain the state of an application, - * specifically the history of a conversation. This class is typically - * extended by other classes to create specific types of memory systems. - */ -class chat_memory_BaseChatMemory extends (/* unused pure expression or super */ null && (BaseMemory)) { - constructor(fields) { - super(); - Object.defineProperty(this, "chatHistory", { + Object.defineProperty(this, "bestOf", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "returnMessages", { + Object.defineProperty(this, "logitBias", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - Object.defineProperty(this, "inputKey", { + Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: "text-davinci-003" }); - Object.defineProperty(this, "outputKey", { + Object.defineProperty(this, "modelKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.chatHistory = fields?.chatHistory ?? new ChatMessageHistory(); - this.returnMessages = fields?.returnMessages ?? this.returnMessages; - this.inputKey = fields?.inputKey ?? this.inputKey; - this.outputKey = fields?.outputKey ?? this.outputKey; - } - /** - * Method to add user and AI messages to the chat history in sequence. - * @param inputValues The input values from the user. - * @param outputValues The output values from the AI. - * @returns Promise that resolves when the context has been saved. - */ - async saveContext(inputValues, outputValues) { - // this is purposefully done in sequence so they're saved in order - await this.chatHistory.addUserMessage(getInputValue(inputValues, this.inputKey)); - await this.chatHistory.addAIChatMessage(getOutputValue(outputValues, this.outputKey)); - } - /** - * Method to clear the chat history. - * @returns Promise that resolves when the chat history has been cleared. - */ - async clear() { - await this.chatHistory.clear(); - } -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/memory/buffer_memory.js - - -/** - * The `BufferMemory` class is a type of memory component used for storing - * and managing previous chat messages. It is a wrapper around - * `ChatMessageHistory` that extracts the messages into an input variable. - * This class is particularly useful in applications like chatbots where - * it is essential to remember previous interactions. Note: The memory - * instance represents the history of a single conversation. Therefore, it - * is not recommended to share the same history or memory instance between - * two different chains. If you deploy your LangChain app on a serverless - * environment, do not store memory instances in a variable, as your - * hosting provider may reset it by the next time the function is called. - */ -class buffer_memory_BufferMemory extends (/* unused pure expression or super */ null && (BaseChatMemory)) { - constructor(fields) { - super({ - chatHistory: fields?.chatHistory, - returnMessages: fields?.returnMessages ?? false, - inputKey: fields?.inputKey, - outputKey: fields?.outputKey, + Object.defineProperty(this, "batchSize", { + enumerable: true, + configurable: true, + writable: true, + value: 20 }); - Object.defineProperty(this, "humanPrefix", { + Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, - value: "Human" + value: void 0 }); - Object.defineProperty(this, "aiPrefix", { + Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, - value: "AI" + value: void 0 }); - Object.defineProperty(this, "memoryKey", { + Object.defineProperty(this, "user", { enumerable: true, configurable: true, writable: true, - value: "history" + value: void 0 }); - this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix; - this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix; - this.memoryKey = fields?.memoryKey ?? this.memoryKey; - } - get memoryKeys() { - return [this.memoryKey]; - } - /** - * Loads the memory variables. It takes an `InputValues` object as a - * parameter and returns a `Promise` that resolves with a - * `MemoryVariables` object. - * @param _values `InputValues` object. - * @returns A `Promise` that resolves with a `MemoryVariables` object. - */ - async loadMemoryVariables(_values) { - const messages = await this.chatHistory.getMessages(); - if (this.returnMessages) { - const result = { - [this.memoryKey]: messages, - }; - return result; - } - const result = { - [this.memoryKey]: getBufferString(messages, this.humanPrefix, this.aiPrefix), - }; - return result; - } -} - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/conversation.js - - - -const conversation_DEFAULT_TEMPLATE = (/* unused pure expression or super */ null && (`The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know. - -Current conversation: -{history} -Human: {input} -AI:`)); -/** - * A class for conducting conversations between a human and an AI. It - * extends the {@link LLMChain} class. - */ -class conversation_ConversationChain extends (/* unused pure expression or super */ null && (LLMChain)) { - static lc_name() { - return "ConversationChain"; - } - constructor({ prompt, outputKey, memory, ...rest }) { - super({ - prompt: prompt ?? - new PromptTemplate({ - template: conversation_DEFAULT_TEMPLATE, - inputVariables: ["history", "input"], - }), - outputKey: outputKey ?? "response", - memory: memory ?? new BufferMemory(), - ...rest, + Object.defineProperty(this, "streaming", { + enumerable: true, + configurable: true, + writable: true, + value: false }); - } -} - -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/sequential_chain.js + 1 modules -var sequential_chain = __nccwpck_require__(7210); -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/combine_docs_chain.js -var combine_docs_chain = __nccwpck_require__(3608); -// EXTERNAL MODULE: ./node_modules/langchain/dist/chains/question_answering/load.js + 4 modules -var load = __nccwpck_require__(3504); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/chains/chat_vector_db_chain.js - - - - -const question_generator_template = (/* unused pure expression or super */ null && (`Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question. - -Chat History: -{chat_history} -Follow Up Input: {question} -Standalone question:`)); -const qa_template = (/* unused pure expression or super */ null && (`Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. - -{context} - -Question: {question} -Helpful Answer:`)); -/** @deprecated use `ConversationalRetrievalQAChain` instead. */ -class ChatVectorDBQAChain extends (/* unused pure expression or super */ null && (BaseChain)) { - get inputKeys() { - return [this.inputKey, this.chatHistoryKey]; - } - get outputKeys() { - return [this.outputKey]; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "k", { + Object.defineProperty(this, "openAIApiKey", { enumerable: true, configurable: true, writable: true, - value: 4 + value: void 0 }); - Object.defineProperty(this, "inputKey", { + Object.defineProperty(this, "azureOpenAIApiVersion", { enumerable: true, configurable: true, writable: true, - value: "question" + value: void 0 }); - Object.defineProperty(this, "chatHistoryKey", { + Object.defineProperty(this, "azureOpenAIApiKey", { enumerable: true, configurable: true, writable: true, - value: "chat_history" + value: void 0 }); - Object.defineProperty(this, "outputKey", { + Object.defineProperty(this, "azureOpenAIApiInstanceName", { enumerable: true, configurable: true, writable: true, - value: "result" + value: void 0 }); - Object.defineProperty(this, "vectorstore", { + Object.defineProperty(this, "azureOpenAIApiDeploymentName", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "combineDocumentsChain", { + Object.defineProperty(this, "azureOpenAIBasePath", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "questionGeneratorChain", { + Object.defineProperty(this, "organization", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "returnSourceDocuments", { + Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, - value: false + value: void 0 }); - this.vectorstore = fields.vectorstore; - this.combineDocumentsChain = fields.combineDocumentsChain; - this.questionGeneratorChain = fields.questionGeneratorChain; - this.inputKey = fields.inputKey ?? this.inputKey; - this.outputKey = fields.outputKey ?? this.outputKey; - this.k = fields.k ?? this.k; - this.returnSourceDocuments = - fields.returnSourceDocuments ?? this.returnSourceDocuments; + Object.defineProperty(this, "clientConfig", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.openAIApiKey = + fields?.openAIApiKey ?? (0, env_js_1.getEnvironmentVariable)("OPENAI_API_KEY"); + this.azureOpenAIApiKey = + fields?.azureOpenAIApiKey ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_KEY"); + if (!this.azureOpenAIApiKey && !this.openAIApiKey) { + throw new Error("OpenAI or Azure OpenAI API key not found"); + } + this.azureOpenAIApiInstanceName = + fields?.azureOpenAIApiInstanceName ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = + (fields?.azureOpenAIApiCompletionsDeploymentName || + fields?.azureOpenAIApiDeploymentName) ?? + ((0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_DEPLOYMENT_NAME")); + this.azureOpenAIApiVersion = + fields?.azureOpenAIApiVersion ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = + fields?.azureOpenAIBasePath ?? + (0, env_js_1.getEnvironmentVariable)("AZURE_OPENAI_BASE_PATH"); + this.organization = + fields?.configuration?.organization ?? + (0, env_js_1.getEnvironmentVariable)("OPENAI_ORGANIZATION"); + this.modelName = fields?.modelName ?? this.modelName; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.batchSize = fields?.batchSize ?? this.batchSize; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.maxTokens = fields?.maxTokens ?? this.maxTokens; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.n = fields?.n ?? this.n; + this.bestOf = fields?.bestOf ?? this.bestOf; + this.logitBias = fields?.logitBias; + this.stop = fields?.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.streaming && this.bestOf && this.bestOf > 1) { + throw new Error("Cannot stream results when bestOf > 1"); + } + if (this.azureOpenAIApiKey) { + if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) { + throw new Error("Azure OpenAI API instance name not found"); + } + if (!this.azureOpenAIApiDeploymentName) { + throw new Error("Azure OpenAI API deployment name not found"); + } + if (!this.azureOpenAIApiVersion) { + throw new Error("Azure OpenAI API version not found"); + } + this.openAIApiKey = this.openAIApiKey ?? ""; + } + this.clientConfig = { + apiKey: this.openAIApiKey, + organization: this.organization, + baseURL: configuration?.basePath ?? fields?.configuration?.basePath, + dangerouslyAllowBrowser: true, + defaultHeaders: configuration?.baseOptions?.headers ?? + fields?.configuration?.baseOptions?.headers, + defaultQuery: configuration?.baseOptions?.params ?? + fields?.configuration?.baseOptions?.params, + ...configuration, + ...fields?.configuration, + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.modelName, + temperature: this.temperature, + max_tokens: this.maxTokens, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + n: this.n, + best_of: this.bestOf, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stop, + user: this.user, + stream: this.streaming, + ...this.modelKwargs, + }; } /** @ignore */ - async _call(values, runManager) { - if (!(this.inputKey in values)) { - throw new Error(`Question key ${this.inputKey} not found.`); - } - if (!(this.chatHistoryKey in values)) { - throw new Error(`chat history key ${this.inputKey} not found.`); + _identifyingParams() { + return { + model_name: this.modelName, + ...this.invocationParams(), + ...this.clientConfig, + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); + } + /** + * Call out to OpenAI's endpoint with k unique prompts + * + * @param [prompts] - The prompts to pass into the model. + * @param [options] - Optional list of stop words to use when generating. + * @param [runManager] - Optional callback manager to use when generating. + * + * @returns The full LLM output. + * + * @example + * ```ts + * import { OpenAI } from "langchain/llms/openai"; + * const openai = new OpenAI(); + * const response = await openai.generate(["Tell me a joke."]); + * ``` + */ + async _generate(prompts, options, runManager) { + const subPrompts = (0, chunk_js_1.chunkArray)(prompts, this.batchSize); + const choices = []; + const tokenUsage = {}; + const params = this.invocationParams(options); + if (params.max_tokens === -1) { + if (prompts.length !== 1) { + throw new Error("max_tokens set to -1 not supported for multiple inputs"); + } + params.max_tokens = await (0, count_tokens_js_1.calculateMaxTokens)({ + prompt: prompts[0], + // Cast here to allow for other models that may not fit the union + modelName: this.modelName, + }); } - const question = values[this.inputKey]; - const chatHistory = values[this.chatHistoryKey]; - let newQuestion = question; - if (chatHistory.length > 0) { - const result = await this.questionGeneratorChain.call({ - question, - chat_history: chatHistory, - }, runManager?.getChild("question_generator")); - const keys = Object.keys(result); - console.log("_call", values, keys); - if (keys.length === 1) { - newQuestion = result[keys[0]]; + for (let i = 0; i < subPrompts.length; i += 1) { + const data = params.stream + ? await (async () => { + const choices = []; + let response; + const stream = await this.completionWithRetry({ + ...params, + stream: true, + prompt: subPrompts[i], + }, options); + for await (const message of stream) { + // on the first message set the response properties + if (!response) { + response = { + id: message.id, + object: message.object, + created: message.created, + model: message.model, + }; + } + // on all messages, update choice + for (const part of message.choices) { + if (!choices[part.index]) { + choices[part.index] = part; + } + else { + const choice = choices[part.index]; + choice.text += part.text; + choice.finish_reason = part.finish_reason; + choice.logprobs = part.logprobs; + } + void runManager?.handleLLMNewToken(part.text, { + prompt: Math.floor(part.index / this.n), + completion: part.index % this.n, + }); + } + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } + return { ...response, choices }; + })() + : await this.completionWithRetry({ + ...params, + stream: false, + prompt: subPrompts[i], + }, { + signal: options.signal, + ...options.options, + }); + choices.push(...data.choices); + const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage + ? data.usage + : { + completion_tokens: undefined, + prompt_tokens: undefined, + total_tokens: undefined, + }; + if (completionTokens) { + tokenUsage.completionTokens = + (tokenUsage.completionTokens ?? 0) + completionTokens; } - else { - throw new Error("Return from llm chain has multiple values, only single values supported."); + if (promptTokens) { + tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; + } + if (totalTokens) { + tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; } } - const docs = await this.vectorstore.similaritySearch(newQuestion, this.k, undefined, runManager?.getChild("vectorstore")); - const inputs = { - question: newQuestion, - input_documents: docs, - chat_history: chatHistory, + const generations = (0, chunk_js_1.chunkArray)(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ + text: choice.text ?? "", + generationInfo: { + finishReason: choice.finish_reason, + logprobs: choice.logprobs, + }, + }))); + return { + generations, + llmOutput: { tokenUsage }, }; - const result = await this.combineDocumentsChain.call(inputs, runManager?.getChild("combine_documents")); - if (this.returnSourceDocuments) { - return { - ...result, - sourceDocuments: docs, + } + // TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation? + async *_streamResponseChunks(input, options, runManager) { + const params = { + ...this.invocationParams(options), + prompt: input, + stream: true, + }; + const stream = await this.completionWithRetry(params, options); + for await (const data of stream) { + const choice = data?.choices[0]; + if (!choice) { + continue; + } + const chunk = new index_js_1.GenerationChunk({ + text: choice.text, + generationInfo: { + finishReason: choice.finish_reason, + }, + }); + yield chunk; + // eslint-disable-next-line no-void + void runManager?.handleLLMNewToken(chunk.text ?? ""); + } + if (options.signal?.aborted) { + throw new Error("AbortError"); + } + } + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.completions.create(request, requestOptions); + return res; + } + catch (e) { + const error = (0, openai_js_1.wrapOpenAIClientError)(e); + throw error; + } + }); + } + /** + * Calls the OpenAI API with retry logic in case of failures. + * @param request The request to send to the OpenAI API. + * @param options Optional configuration for the API call. + * @returns The response from the OpenAI API. + */ + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + baseURL: this.clientConfig.baseURL, + }; + const endpoint = (0, azure_js_1.getEndpoint)(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0, }; + if (!params.baseURL) { + delete params.baseURL; + } + this.client = new openai_1.OpenAI(params); } - return result; - } - _chainType() { - return "chat-vector-db"; - } - static async deserialize(data, values) { - if (!("vectorstore" in values)) { - throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); - } - const { vectorstore } = values; - return new ChatVectorDBQAChain({ - combineDocumentsChain: await BaseChain.deserialize(data.combine_documents_chain), - questionGeneratorChain: await LLMChain.deserialize(data.question_generator), - k: data.k, - vectorstore, - }); - } - serialize() { - return { - _type: this._chainType(), - combine_documents_chain: this.combineDocumentsChain.serialize(), - question_generator: this.questionGeneratorChain.serialize(), - k: this.k, + const requestOptions = { + ...this.clientConfig, + ...options, }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers, + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query, + }; + } + return requestOptions; } - /** - * Creates an instance of ChatVectorDBQAChain using a BaseLanguageModel - * and other options. - * @param llm Instance of BaseLanguageModel used to generate a new question. - * @param vectorstore Instance of VectorStore used for vector operations. - * @param options (Optional) Additional options for creating the ChatVectorDBQAChain instance. - * @returns New instance of ChatVectorDBQAChain. - */ - static fromLLM(llm, vectorstore, options = {}) { - const { questionGeneratorTemplate, qaTemplate, verbose, ...rest } = options; - const question_generator_prompt = PromptTemplate.fromTemplate(questionGeneratorTemplate || question_generator_template); - const qa_prompt = PromptTemplate.fromTemplate(qaTemplate || qa_template); - const qaChain = loadQAStuffChain(llm, { prompt: qa_prompt, verbose }); - const questionGeneratorChain = new LLMChain({ - prompt: question_generator_prompt, - llm, - verbose, - }); - const instance = new this({ - vectorstore, - combineDocumentsChain: qaChain, - questionGeneratorChain, - ...rest, - }); - return instance; + _llmType() { + return "openai"; } } - -;// CONCATENATED MODULE: ./node_modules/langchain/dist/document.js +exports.OpenAI = OpenAI; /** - * Interface for interacting with a document. + * PromptLayer wrapper to OpenAI + * @augments OpenAI */ -class Document { +class PromptLayerOpenAI extends OpenAI { + get lc_secrets() { + return { + promptLayerApiKey: "PROMPTLAYER_API_KEY", + }; + } constructor(fields) { - Object.defineProperty(this, "pageContent", { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "promptLayerApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "metadata", { + Object.defineProperty(this, "plTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.pageContent = fields.pageContent - ? fields.pageContent.toString() - : this.pageContent; - this.metadata = fields.metadata ?? {}; - } -} - -// EXTERNAL MODULE: ./node_modules/langchain/dist/util/tiktoken.js + 3 modules -var tiktoken = __nccwpck_require__(7573); -// EXTERNAL MODULE: ./node_modules/langchain/dist/schema/runnable/index.js + 10 modules -var runnable = __nccwpck_require__(1972); -;// CONCATENATED MODULE: ./node_modules/langchain/dist/schema/document.js - -/** - * Abstract base class for document transformation systems. - * - * A document transformation system takes an array of Documents and returns an - * array of transformed Documents. These arrays do not necessarily have to have - * the same length. - * - * One example of this is a text splitter that splits a large document into - * many smaller documents. - */ -class BaseDocumentTransformer extends runnable/* Runnable */.eq { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_namespace", { + Object.defineProperty(this, "returnPromptLayerId", { enumerable: true, configurable: true, writable: true, - value: ["langchain", "document_transformers"] + value: void 0 }); + this.plTags = fields?.plTags ?? []; + this.promptLayerApiKey = + fields?.promptLayerApiKey ?? + (0, env_js_1.getEnvironmentVariable)("PROMPTLAYER_API_KEY"); + this.returnPromptLayerId = fields?.returnPromptLayerId; + if (!this.promptLayerApiKey) { + throw new Error("Missing PromptLayer API key"); + } } - /** - * Method to invoke the document transformation. This method calls the - * transformDocuments method with the provided input. - * @param input The input documents to be transformed. - * @param _options Optional configuration object to customize the behavior of callbacks. - * @returns A Promise that resolves to the transformed documents. - */ - invoke(input, _options) { - return this.transformDocuments(input); + async _generate(prompts, options, runManager) { + const requestStartTime = Date.now(); + const generations = await super._generate(prompts, options, runManager); + for (let i = 0; i < generations.generations.length; i += 1) { + const requestEndTime = Date.now(); + const parsedResp = { + text: generations.generations[i][0].text, + llm_output: generations.llmOutput, + }; + const promptLayerRespBody = await (0, prompt_layer_js_1.promptLayerTrackRequest)(this.caller, "langchain.PromptLayerOpenAI", + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { ...this._identifyingParams(), prompt: prompts[i] }, this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); + let promptLayerRequestId; + if (this.returnPromptLayerId === true) { + if (promptLayerRespBody && promptLayerRespBody.success === true) { + promptLayerRequestId = promptLayerRespBody.request_id; + } + generations.generations[i][0].generationInfo = { + ...generations.generations[i][0].generationInfo, + promptLayerRequestId, + }; + } + } + return generations; } } -/** - * Class for document transformers that return exactly one transformed document - * for each input document. - */ -class MappingDocumentTransformer extends (/* unused pure expression or super */ null && (BaseDocumentTransformer)) { - async transformDocuments(documents) { - const newDocuments = []; - for (const document of documents) { - const transformedDocument = await this._transformDocument(document); - newDocuments.push(transformedDocument); +exports.PromptLayerOpenAI = PromptLayerOpenAI; +var openai_chat_js_2 = __nccwpck_require__(5547); +Object.defineProperty(exports, "OpenAIChat", ({ enumerable: true, get: function () { return openai_chat_js_2.OpenAIChat; } })); +Object.defineProperty(exports, "PromptLayerOpenAIChat", ({ enumerable: true, get: function () { return openai_chat_js_2.PromptLayerOpenAIChat; } })); + + +/***/ }), + +/***/ 9368: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.mapKeys = exports.keyFromJson = exports.keyToJson = void 0; +const decamelize_1 = __importDefault(__nccwpck_require__(159)); +const camelcase_1 = __importDefault(__nccwpck_require__(996)); +function keyToJson(key, map) { + return map?.[key] || (0, decamelize_1.default)(key); +} +exports.keyToJson = keyToJson; +function keyFromJson(key, map) { + return map?.[key] || (0, camelcase_1.default)(key); +} +exports.keyFromJson = keyFromJson; +function mapKeys(fields, mapper, map) { + const mapped = {}; + for (const key in fields) { + if (Object.hasOwn(fields, key)) { + mapped[mapper(key, map)] = fields[key]; } - return newDocuments; } + return mapped; } +exports.mapKeys = mapKeys; -;// CONCATENATED MODULE: ./node_modules/langchain/dist/text_splitter.js +/***/ }), +/***/ 5335: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -class TextSplitter extends BaseDocumentTransformer { - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "document_transformers", "text_splitters"] - }); - Object.defineProperty(this, "chunkSize", { - enumerable: true, - configurable: true, - writable: true, - value: 1000 - }); - Object.defineProperty(this, "chunkOverlap", { - enumerable: true, - configurable: true, - writable: true, - value: 200 - }); - Object.defineProperty(this, "keepSeparator", { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Serializable = exports.get_lc_unique_name = void 0; +const map_keys_js_1 = __nccwpck_require__(9368); +function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; +} +function replaceSecrets(root, secretsMap) { + const result = shallowCopy(root); + for (const [path, secretId] of Object.entries(secretsMap)) { + const [last, ...partsReverse] = path.split(".").reverse(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let current = result; + for (const part of partsReverse.reverse()) { + if (current[part] === undefined) { + break; + } + current[part] = shallowCopy(current[part]); + current = current[part]; + } + if (current[last] !== undefined) { + current[last] = { + lc: 1, + type: "secret", + id: [secretId], + }; + } + } + return result; +} +/** + * Get a unique name for the module, rather than parent class implementations. + * Should not be subclassed, subclass lc_name above instead. + */ +function get_lc_unique_name( +// eslint-disable-next-line @typescript-eslint/no-use-before-define +serializableClass) { + // "super" here would refer to the parent class of Serializable, + // when we want the parent class of the module actually calling this method. + const parentClass = Object.getPrototypeOf(serializableClass); + const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && + (typeof parentClass.lc_name !== "function" || + serializableClass.lc_name() !== parentClass.lc_name()); + if (lcNameIsSubclassed) { + return serializableClass.lc_name(); + } + else { + return serializableClass.name; + } +} +exports.get_lc_unique_name = get_lc_unique_name; +class Serializable { + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor), + ]; + } + /** + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. + */ + get lc_secrets() { + return undefined; + } + /** + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. + */ + get lc_attributes() { + return undefined; + } + /** + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. + */ + get lc_aliases() { + return undefined; + } + constructor(kwargs, ..._args) { + Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); - Object.defineProperty(this, "lengthFunction", { + Object.defineProperty(this, "lc_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.chunkSize = fields?.chunkSize ?? this.chunkSize; - this.chunkOverlap = fields?.chunkOverlap ?? this.chunkOverlap; - this.keepSeparator = fields?.keepSeparator ?? this.keepSeparator; - this.lengthFunction = - fields?.lengthFunction ?? ((text) => text.length); - if (this.chunkOverlap >= this.chunkSize) { - throw new Error("Cannot have chunkOverlap >= chunkSize"); - } - } - async transformDocuments(documents, chunkHeaderOptions = {}) { - return this.splitDocuments(documents, chunkHeaderOptions); + this.lc_kwargs = kwargs || {}; } - splitOnSeparator(text, separator) { - let splits; - if (separator) { - if (this.keepSeparator) { - const regexEscapedSeparator = separator.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&"); - splits = text.split(new RegExp(`(?=${regexEscapedSeparator})`)); - } - else { - splits = text.split(separator); - } + toJSON() { + if (!this.lc_serializable) { + return this.toJSONNotImplemented(); } - else { - splits = text.split(""); + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + this.lc_kwargs instanceof Serializable || + typeof this.lc_kwargs !== "object" || + Array.isArray(this.lc_kwargs)) { + // We do not support serialization of classes with arg not a POJO + // I'm aware the check above isn't as strict as it could be + return this.toJSONNotImplemented(); } - return splits.filter((s) => s !== ""); - } - async createDocuments(texts, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - metadatas = [], chunkHeaderOptions = {}) { - // if no metadata is provided, we create an empty one for each text - const _metadatas = metadatas.length > 0 ? metadatas : new Array(texts.length).fill({}); - const { chunkHeader = "", chunkOverlapHeader = "(cont'd) ", appendChunkOverlapHeader = false, } = chunkHeaderOptions; - const documents = new Array(); - for (let i = 0; i < texts.length; i += 1) { - const text = texts[i]; - let lineCounterIndex = 1; - let prevChunk = null; - for (const chunk of await this.splitText(text)) { - let pageContent = chunkHeader; - // we need to count the \n that are in the text before getting removed by the splitting - let numberOfIntermediateNewLines = 0; - if (prevChunk) { - const indexChunk = text.indexOf(chunk); - const indexEndPrevChunk = text.indexOf(prevChunk) + (await this.lengthFunction(prevChunk)); - const removedNewlinesFromSplittingText = text.slice(indexEndPrevChunk, indexChunk); - numberOfIntermediateNewLines = (removedNewlinesFromSplittingText.match(/\n/g) || []).length; - if (appendChunkOverlapHeader) { - pageContent += chunkOverlapHeader; + const aliases = {}; + const secrets = {}; + const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { + acc[key] = key in this ? this[key] : this.lc_kwargs[key]; + return acc; + }, {}); + // get secrets, attributes and aliases from all superclasses + for ( + // eslint-disable-next-line @typescript-eslint/no-this-alias + let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { + Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); + Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); + Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + } + // include all secrets used, even if not in kwargs, + // will be replaced with sentinel value in replaceSecrets + Object.keys(secrets).forEach((keyPath) => { + // eslint-disable-next-line @typescript-eslint/no-this-alias, @typescript-eslint/no-explicit-any + let read = this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let write = kwargs; + const [last, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === undefined) + return; + if (!(key in write) || write[key] === undefined) { + if (typeof read[key] === "object" && read[key] != null) { + write[key] = {}; + } + else if (Array.isArray(read[key])) { + write[key] = []; } } - lineCounterIndex += numberOfIntermediateNewLines; - const newLinesCount = (chunk.match(/\n/g) || []).length; - const loc = _metadatas[i].loc && typeof _metadatas[i].loc === "object" - ? { ..._metadatas[i].loc } - : {}; - loc.lines = { - from: lineCounterIndex, - to: lineCounterIndex + newLinesCount, - }; - const metadataWithLinesNumber = { - ..._metadatas[i], - loc, - }; - pageContent += chunk; - documents.push(new Document({ - pageContent, - metadata: metadataWithLinesNumber, - })); - lineCounterIndex += newLinesCount; - prevChunk = chunk; + read = read[key]; + write = write[key]; } - } - return documents; + if (last in read && read[last] !== undefined) { + write[last] = write[last] || read[last]; + } + }); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: (0, map_keys_js_1.mapKeys)(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, map_keys_js_1.keyToJson, aliases), + }; } - async splitDocuments(documents, chunkHeaderOptions = {}) { - const selectedDocuments = documents.filter((doc) => doc.pageContent !== undefined); - const texts = selectedDocuments.map((doc) => doc.pageContent); - const metadatas = selectedDocuments.map((doc) => doc.metadata); - return this.createDocuments(texts, metadatas, chunkHeaderOptions); + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id, + }; } - joinDocs(docs, separator) { - const text = docs.join(separator).trim(); - return text === "" ? null : text; +} +exports.Serializable = Serializable; + + +/***/ }), + +/***/ 4235: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getPromptInputKey = exports.getBufferString = exports.getOutputValue = exports.getInputValue = exports.BaseMemory = void 0; +/** + * Abstract base class for memory in LangChain's Chains. Memory refers to + * the state in Chains. It can be used to store information about past + * executions of a Chain and inject that information into the inputs of + * future executions of the Chain. + */ +class BaseMemory { +} +exports.BaseMemory = BaseMemory; +const getValue = (values, key) => { + if (key !== undefined) { + return values[key]; } - async mergeSplits(splits, separator) { - const docs = []; - const currentDoc = []; - let total = 0; - for (const d of splits) { - const _len = await this.lengthFunction(d); - if (total + _len + (currentDoc.length > 0 ? separator.length : 0) > - this.chunkSize) { - if (total > this.chunkSize) { - console.warn(`Created a chunk of size ${total}, + -which is longer than the specified ${this.chunkSize}`); - } - if (currentDoc.length > 0) { - const doc = this.joinDocs(currentDoc, separator); - if (doc !== null) { - docs.push(doc); - } - // Keep on popping if: - // - we have a larger chunk than in the chunk overlap - // - or if we still have any chunks and the length is long - while (total > this.chunkOverlap || - (total + _len > this.chunkSize && total > 0)) { - total -= await this.lengthFunction(currentDoc[0]); - currentDoc.shift(); - } - } - } - currentDoc.push(d); - total += _len; + const keys = Object.keys(values); + if (keys.length === 1) { + return values[keys[0]]; + } +}; +/** + * This function is used by memory classes to select the input value + * to use for the memory. If there is only one input value, it is used. + * If there are multiple input values, the inputKey must be specified. + */ +const getInputValue = (inputValues, inputKey) => { + const value = getValue(inputValues, inputKey); + if (!value) { + const keys = Object.keys(inputValues); + throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); + } + return value; +}; +exports.getInputValue = getInputValue; +/** + * This function is used by memory classes to select the output value + * to use for the memory. If there is only one output value, it is used. + * If there are multiple output values, the outputKey must be specified. + * If no outputKey is specified, an error is thrown. + */ +const getOutputValue = (outputValues, outputKey) => { + const value = getValue(outputValues, outputKey); + if (!value) { + const keys = Object.keys(outputValues); + throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); + } + return value; +}; +exports.getOutputValue = getOutputValue; +/** + * This function is used by memory classes to get a string representation + * of the chat message history, based on the message content and role. + */ +function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m of messages) { + let role; + if (m._getType() === "human") { + role = humanPrefix; } - const doc = this.joinDocs(currentDoc, separator); - if (doc !== null) { - docs.push(doc); + else if (m._getType() === "ai") { + role = aiPrefix; } - return docs; + else if (m._getType() === "system") { + role = "System"; + } + else if (m._getType() === "function") { + role = "Function"; + } + else if (m._getType() === "generic") { + role = m.role; + } + else { + throw new Error(`Got unsupported message type: ${m}`); + } + const nameStr = m.name ? `${m.name}, ` : ""; + string_messages.push(`${role}: ${nameStr}${m.content}`); } + return string_messages.join("\n"); } -class CharacterTextSplitter extends (/* unused pure expression or super */ null && (TextSplitter)) { - static lc_name() { - return "CharacterTextSplitter"; +exports.getBufferString = getBufferString; +/** + * Function used by memory classes to get the key of the prompt input, + * excluding any keys that are memory variables or the "stop" key. If + * there is not exactly one prompt input key, an error is thrown. + */ +function getPromptInputKey(inputs, memoryVariables) { + const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); + if (promptInputKeys.length !== 1) { + throw new Error(`One input key expected, but got ${promptInputKeys.length}`); } + return promptInputKeys[0]; +} +exports.getPromptInputKey = getPromptInputKey; + + +/***/ }), + +/***/ 9666: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BufferMemory = void 0; +const base_js_1 = __nccwpck_require__(4235); +const chat_memory_js_1 = __nccwpck_require__(7990); +/** + * The `BufferMemory` class is a type of memory component used for storing + * and managing previous chat messages. It is a wrapper around + * `ChatMessageHistory` that extracts the messages into an input variable. + * This class is particularly useful in applications like chatbots where + * it is essential to remember previous interactions. Note: The memory + * instance represents the history of a single conversation. Therefore, it + * is not recommended to share the same history or memory instance between + * two different chains. If you deploy your LangChain app on a serverless + * environment, do not store memory instances in a variable, as your + * hosting provider may reset it by the next time the function is called. + */ +class BufferMemory extends chat_memory_js_1.BaseChatMemory { constructor(fields) { - super(fields); - Object.defineProperty(this, "separator", { + super({ + chatHistory: fields?.chatHistory, + returnMessages: fields?.returnMessages ?? false, + inputKey: fields?.inputKey, + outputKey: fields?.outputKey, + }); + Object.defineProperty(this, "humanPrefix", { enumerable: true, configurable: true, writable: true, - value: "\n\n" + value: "Human" }); - this.separator = fields?.separator ?? this.separator; - } - async splitText(text) { - // First we naively split the large input into a bunch of smaller ones. - const splits = this.splitOnSeparator(text, this.separator); - return this.mergeSplits(splits, this.keepSeparator ? "" : this.separator); - } -} -const SupportedTextSplitterLanguages = (/* unused pure expression or super */ null && ([ - "cpp", - "go", - "java", - "js", - "php", - "proto", - "python", - "rst", - "ruby", - "rust", - "scala", - "swift", - "markdown", - "latex", - "html", - "sol", -])); -class text_splitter_RecursiveCharacterTextSplitter extends TextSplitter { - static lc_name() { - return "RecursiveCharacterTextSplitter"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "separators", { + Object.defineProperty(this, "aiPrefix", { enumerable: true, configurable: true, writable: true, - value: ["\n\n", "\n", " ", ""] + value: "AI" }); - this.separators = fields?.separators ?? this.separators; - this.keepSeparator = fields?.keepSeparator ?? true; - } - async _splitText(text, separators) { - const finalChunks = []; - // Get appropriate separator to use - let separator = separators[separators.length - 1]; - let newSeparators; - for (let i = 0; i < separators.length; i += 1) { - const s = separators[i]; - if (s === "") { - separator = s; - break; - } - if (text.includes(s)) { - separator = s; - newSeparators = separators.slice(i + 1); - break; - } - } - // Now that we have the separator, split the text - const splits = this.splitOnSeparator(text, separator); - // Now go merging things, recursively splitting longer texts. - let goodSplits = []; - const _separator = this.keepSeparator ? "" : separator; - for (const s of splits) { - if ((await this.lengthFunction(s)) < this.chunkSize) { - goodSplits.push(s); - } - else { - if (goodSplits.length) { - const mergedText = await this.mergeSplits(goodSplits, _separator); - finalChunks.push(...mergedText); - goodSplits = []; - } - if (!newSeparators) { - finalChunks.push(s); - } - else { - const otherInfo = await this._splitText(s, newSeparators); - finalChunks.push(...otherInfo); - } - } - } - if (goodSplits.length) { - const mergedText = await this.mergeSplits(goodSplits, _separator); - finalChunks.push(...mergedText); - } - return finalChunks; - } - async splitText(text) { - return this._splitText(text, this.separators); - } - static fromLanguage(language, options) { - return new text_splitter_RecursiveCharacterTextSplitter({ - ...options, - separators: text_splitter_RecursiveCharacterTextSplitter.getSeparatorsForLanguage(language), + Object.defineProperty(this, "memoryKey", { + enumerable: true, + configurable: true, + writable: true, + value: "history" }); + this.humanPrefix = fields?.humanPrefix ?? this.humanPrefix; + this.aiPrefix = fields?.aiPrefix ?? this.aiPrefix; + this.memoryKey = fields?.memoryKey ?? this.memoryKey; } - static getSeparatorsForLanguage(language) { - if (language === "cpp") { - return [ - // Split along class definitions - "\nclass ", - // Split along function definitions - "\nvoid ", - "\nint ", - "\nfloat ", - "\ndouble ", - // Split along control flow statements - "\nif ", - "\nfor ", - "\nwhile ", - "\nswitch ", - "\ncase ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "go") { - return [ - // Split along function definitions - "\nfunc ", - "\nvar ", - "\nconst ", - "\ntype ", - // Split along control flow statements - "\nif ", - "\nfor ", - "\nswitch ", - "\ncase ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "java") { - return [ - // Split along class definitions - "\nclass ", - // Split along method definitions - "\npublic ", - "\nprotected ", - "\nprivate ", - "\nstatic ", - // Split along control flow statements - "\nif ", - "\nfor ", - "\nwhile ", - "\nswitch ", - "\ncase ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "js") { - return [ - // Split along function definitions - "\nfunction ", - "\nconst ", - "\nlet ", - "\nvar ", - "\nclass ", - // Split along control flow statements - "\nif ", - "\nfor ", - "\nwhile ", - "\nswitch ", - "\ncase ", - "\ndefault ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "php") { - return [ - // Split along function definitions - "\nfunction ", - // Split along class definitions - "\nclass ", - // Split along control flow statements - "\nif ", - "\nforeach ", - "\nwhile ", - "\ndo ", - "\nswitch ", - "\ncase ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "proto") { - return [ - // Split along message definitions - "\nmessage ", - // Split along service definitions - "\nservice ", - // Split along enum definitions - "\nenum ", - // Split along option definitions - "\noption ", - // Split along import statements - "\nimport ", - // Split along syntax declarations - "\nsyntax ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "python") { - return [ - // First, try to split along class definitions - "\nclass ", - "\ndef ", - "\n\tdef ", - // Now split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "rst") { - return [ - // Split along section titles - "\n===\n", - "\n---\n", - "\n***\n", - // Split along directive markers - "\n.. ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "ruby") { - return [ - // Split along method definitions - "\ndef ", - "\nclass ", - // Split along control flow statements - "\nif ", - "\nunless ", - "\nwhile ", - "\nfor ", - "\ndo ", - "\nbegin ", - "\nrescue ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "rust") { - return [ - // Split along function definitions - "\nfn ", - "\nconst ", - "\nlet ", - // Split along control flow statements - "\nif ", - "\nwhile ", - "\nfor ", - "\nloop ", - "\nmatch ", - "\nconst ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "scala") { - return [ - // Split along class definitions - "\nclass ", - "\nobject ", - // Split along method definitions - "\ndef ", - "\nval ", - "\nvar ", - // Split along control flow statements - "\nif ", - "\nfor ", - "\nwhile ", - "\nmatch ", - "\ncase ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "swift") { - return [ - // Split along function definitions - "\nfunc ", - // Split along class definitions - "\nclass ", - "\nstruct ", - "\nenum ", - // Split along control flow statements - "\nif ", - "\nfor ", - "\nwhile ", - "\ndo ", - "\nswitch ", - "\ncase ", - // Split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "markdown") { - return [ - // First, try to split along Markdown headings (starting with level 2) - "\n## ", - "\n### ", - "\n#### ", - "\n##### ", - "\n###### ", - // Note the alternative syntax for headings (below) is not handled here - // Heading level 2 - // --------------- - // End of code block - "```\n\n", - // Horizontal lines - "\n\n***\n\n", - "\n\n---\n\n", - "\n\n___\n\n", - // Note that this splitter doesn't handle horizontal lines defined - // by *three or more* of ***, ---, or ___, but this is not handled - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "latex") { - return [ - // First, try to split along Latex sections - "\n\\chapter{", - "\n\\section{", - "\n\\subsection{", - "\n\\subsubsection{", - // Now split by environments - "\n\\begin{enumerate}", - "\n\\begin{itemize}", - "\n\\begin{description}", - "\n\\begin{list}", - "\n\\begin{quote}", - "\n\\begin{quotation}", - "\n\\begin{verse}", - "\n\\begin{verbatim}", - // Now split by math environments - "\n\\begin{align}", - "$$", - "$", - // Now split by the normal type of lines - "\n\n", - "\n", - " ", - "", - ]; - } - else if (language === "html") { - return [ - // First, try to split along HTML tags - "", - "
", - "

", - "
", - "

  • ", - "

    ", - "

    ", - "

    ", - "

    ", - "

    ", - "
    ", - "", - "", - "", - "
    ", - "", - "
      ", - "
        ", - "
        ", - "