'use strict'; var fs$c = require('node:fs/promises'); var path$h = require('node:path'); var crypto$2 = require('crypto'); var tty = require('node:tty'); var util$5 = require('node:util'); var require$$1 = require('os'); var require$$0$3 = require('path'); var require$$0$4 = require('util'); var require$$0$5 = require('stream'); var require$$0$7 = require('events'); var require$$0$6 = require('fs'); var require$$3 = require('node:url'); var require$$0$8 = require('buffer'); var fs$e = require('fs/promises'); var http = require('http'); var https = require('https'); var require$$7$1 = require('url'); var openai$1 = require('@langchain/openai'); var groq = require('@langchain/groq'); var prompts = require('@langchain/core/prompts'); var output_parsers = require('langchain/output_parsers'); var fs$d = require('node:fs'); var require$$0$9 = require('child_process'); var require$$8 = require('node:events'); var typeorm = require('typeorm'); var process$1 = require('node:process'); var require$$1$1 = require('node:module'); var require$$0$a = require('node:os'); var require$$4$1 = require('node:assert'); var require$$7 = require('node:v8'); var require$$9 = require('node:crypto'); var require$$11 = require('node:perf_hooks'); var require$$12 = require('node:vm'); var require$$0$b = require('assert'); var require$$2$1 = require('module'); var require$$5 = require('process'); var require$$6 = require('tty'); var require$$9$1 = require('v8'); var require$$0$c = require('dns'); var require$$0$d = require('net'); var require$$1$2 = require('tls'); var require$$1$3 = require('string_decoder'); var tools = require('@langchain/core/tools'); var agents = require('langchain/agents'); var messages$2 = require('@langchain/core/messages'); var googleGenai = require('@langchain/google-genai'); var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } /*! ***************************************************************************** Copyright (C) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var Reflect$1; (function (Reflect) { // Metadata Proposal // https://rbuckton.github.io/reflect-metadata/ (function (factory) { var root = typeof globalThis === "object" ? globalThis : typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis(); var exporter = makeExporter(Reflect); if (typeof root.Reflect !== "undefined") { exporter = makeExporter(root.Reflect, exporter); } factory(exporter, root); if (typeof root.Reflect === "undefined") { root.Reflect = Reflect; } function makeExporter(target, previous) { return function (key, value) { Object.defineProperty(target, key, { configurable: true, writable: true, value: value }); if (previous) previous(key, value); }; } function functionThis() { try { return Function("return this;")(); } catch (_) { } } function indirectEvalThis() { try { return (void 0, eval)("(function() { return this; })()"); } catch (_) { } } function sloppyModeThis() { return functionThis() || indirectEvalThis(); } })(function (exporter, root) { var hasOwn = Object.prototype.hasOwnProperty; // feature test for Symbol support var supportsSymbol = typeof Symbol === "function"; var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; var supportsCreate = typeof Object.create === "function"; // feature test for Object.create support var supportsProto = { __proto__: [] } instanceof Array; // feature test for __proto__ support var downLevel = !supportsCreate && !supportsProto; var HashMap = { // create an object in dictionary mode (a.k.a. "slow" mode in v8) create: supportsCreate ? function () { return MakeDictionary(Object.create(null)); } : supportsProto ? function () { return MakeDictionary({ __proto__: null }); } : function () { return MakeDictionary({}); }, has: downLevel ? function (map, key) { return hasOwn.call(map, key); } : function (map, key) { return key in map; }, get: downLevel ? function (map, key) { return hasOwn.call(map, key) ? map[key] : undefined; } : function (map, key) { return map[key]; }, }; // Load global or shim versions of Map, Set, and WeakMap var functionPrototype = Object.getPrototypeOf(Function); var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : undefined; var metadataRegistry = GetOrCreateMetadataRegistry(); var metadataProvider = CreateMetadataProvider(metadataRegistry); /** * Applies a set of decorators to a property of a target object. * @param decorators An array of decorators. * @param target The target object. * @param propertyKey (Optional) The property key to decorate. * @param attributes (Optional) The property descriptor for the target key. * @remarks Decorators are applied in reverse order. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * Example = Reflect.decorate(decoratorsArray, Example); * * // property (on constructor) * Reflect.decorate(decoratorsArray, Example, "staticProperty"); * * // property (on prototype) * Reflect.decorate(decoratorsArray, Example.prototype, "property"); * * // method (on constructor) * Object.defineProperty(Example, "staticMethod", * Reflect.decorate(decoratorsArray, Example, "staticMethod", * Object.getOwnPropertyDescriptor(Example, "staticMethod"))); * * // method (on prototype) * Object.defineProperty(Example.prototype, "method", * Reflect.decorate(decoratorsArray, Example.prototype, "method", * Object.getOwnPropertyDescriptor(Example.prototype, "method"))); * */ function decorate(decorators, target, propertyKey, attributes) { if (!IsUndefined(propertyKey)) { if (!IsArray(decorators)) throw new TypeError(); if (!IsObject(target)) throw new TypeError(); if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) throw new TypeError(); if (IsNull(attributes)) attributes = undefined; propertyKey = ToPropertyKey(propertyKey); return DecorateProperty(decorators, target, propertyKey, attributes); } else { if (!IsArray(decorators)) throw new TypeError(); if (!IsConstructor(target)) throw new TypeError(); return DecorateConstructor(decorators, target); } } exporter("decorate", decorate); // 4.1.2 Reflect.metadata(metadataKey, metadataValue) // https://rbuckton.github.io/reflect-metadata/#reflect.metadata /** * A default metadata decorator factory that can be used on a class, class member, or parameter. * @param metadataKey The key for the metadata entry. * @param metadataValue The value for the metadata entry. * @returns A decorator function. * @remarks * If `metadataKey` is already defined for the target and target key, the * metadataValue for that key will be overwritten. * @example * * // constructor * @Reflect.metadata(key, value) * class Example { * } * * // property (on constructor, TypeScript only) * class Example { * @Reflect.metadata(key, value) * static staticProperty; * } * * // property (on prototype, TypeScript only) * class Example { * @Reflect.metadata(key, value) * property; * } * * // method (on constructor) * class Example { * @Reflect.metadata(key, value) * static staticMethod() { } * } * * // method (on prototype) * class Example { * @Reflect.metadata(key, value) * method() { } * } * */ function metadata(metadataKey, metadataValue) { function decorator(target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) throw new TypeError(); OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } return decorator; } exporter("metadata", metadata); /** * Define a unique metadata entry on the target. * @param metadataKey A key used to store and retrieve metadata. * @param metadataValue A value that contains attached metadata. * @param target The target object on which to define metadata. * @param propertyKey (Optional) The property key for the target. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * Reflect.defineMetadata("custom:annotation", options, Example); * * // property (on constructor) * Reflect.defineMetadata("custom:annotation", options, Example, "staticProperty"); * * // property (on prototype) * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "property"); * * // method (on constructor) * Reflect.defineMetadata("custom:annotation", options, Example, "staticMethod"); * * // method (on prototype) * Reflect.defineMetadata("custom:annotation", options, Example.prototype, "method"); * * // decorator factory as metadata-producing annotation. * function MyAnnotation(options): Decorator { * return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key); * } * */ function defineMetadata(metadataKey, metadataValue, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); } exporter("defineMetadata", defineMetadata); /** * Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.hasMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method"); * */ function hasMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryHasMetadata(metadataKey, target, propertyKey); } exporter("hasMetadata", hasMetadata); /** * Gets a value indicating whether the target object has the provided metadata key defined. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata key was defined on the target object; otherwise, `false`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.hasOwnMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method"); * */ function hasOwnMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); } exporter("hasOwnMetadata", hasOwnMetadata); /** * Gets the metadata value for the provided metadata key on the target object or its prototype chain. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadata("custom:annotation", Example.prototype, "method"); * */ function getMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryGetMetadata(metadataKey, target, propertyKey); } exporter("getMetadata", getMetadata); /** * Gets the metadata value for the provided metadata key on the target object. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns The metadata value for the metadata key if found; otherwise, `undefined`. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getOwnMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method"); * */ function getOwnMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); } exporter("getOwnMetadata", getOwnMetadata); /** * Gets the metadata keys defined on the target object or its prototype chain. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getMetadataKeys(Example); * * // property (on constructor) * result = Reflect.getMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getMetadataKeys(Example.prototype, "method"); * */ function getMetadataKeys(target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryMetadataKeys(target, propertyKey); } exporter("getMetadataKeys", getMetadataKeys); /** * Gets the unique metadata keys defined on the target object. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns An array of unique metadata keys. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.getOwnMetadataKeys(Example); * * // property (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticProperty"); * * // property (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "property"); * * // method (on constructor) * result = Reflect.getOwnMetadataKeys(Example, "staticMethod"); * * // method (on prototype) * result = Reflect.getOwnMetadataKeys(Example.prototype, "method"); * */ function getOwnMetadataKeys(target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); return OrdinaryOwnMetadataKeys(target, propertyKey); } exporter("getOwnMetadataKeys", getOwnMetadataKeys); /** * Deletes the metadata entry from the target object with the provided key. * @param metadataKey A key used to store and retrieve metadata. * @param target The target object on which the metadata is defined. * @param propertyKey (Optional) The property key for the target. * @returns `true` if the metadata entry was found and deleted; otherwise, false. * @example * * class Example { * // property declarations are not part of ES6, though they are valid in TypeScript: * // static staticProperty; * // property; * * constructor(p) { } * static staticMethod(p) { } * method(p) { } * } * * // constructor * result = Reflect.deleteMetadata("custom:annotation", Example); * * // property (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty"); * * // property (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property"); * * // method (on constructor) * result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod"); * * // method (on prototype) * result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method"); * */ function deleteMetadata(metadataKey, target, propertyKey) { if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); if (!IsObject(target)) throw new TypeError(); if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey); var provider = GetMetadataProvider(target, propertyKey, /*Create*/ false); if (IsUndefined(provider)) return false; return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey); } exporter("deleteMetadata", deleteMetadata); function DecorateConstructor(decorators, target) { for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; var decorated = decorator(target); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsConstructor(decorated)) throw new TypeError(); target = decorated; } } return target; } function DecorateProperty(decorators, target, propertyKey, descriptor) { for (var i = decorators.length - 1; i >= 0; --i) { var decorator = decorators[i]; var decorated = decorator(target, propertyKey, descriptor); if (!IsUndefined(decorated) && !IsNull(decorated)) { if (!IsObject(decorated)) throw new TypeError(); descriptor = decorated; } } return descriptor; } // 3.1.1.1 OrdinaryHasMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasmetadata function OrdinaryHasMetadata(MetadataKey, O, P) { var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return true; var parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) return OrdinaryHasMetadata(MetadataKey, parent, P); return false; } // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata function OrdinaryHasOwnMetadata(MetadataKey, O, P) { var provider = GetMetadataProvider(O, P, /*Create*/ false); if (IsUndefined(provider)) return false; return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O, P)); } // 3.1.3.1 OrdinaryGetMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetmetadata function OrdinaryGetMetadata(MetadataKey, O, P) { var hasOwn = OrdinaryHasOwnMetadata(MetadataKey, O, P); if (hasOwn) return OrdinaryGetOwnMetadata(MetadataKey, O, P); var parent = OrdinaryGetPrototypeOf(O); if (!IsNull(parent)) return OrdinaryGetMetadata(MetadataKey, parent, P); return undefined; } // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata function OrdinaryGetOwnMetadata(MetadataKey, O, P) { var provider = GetMetadataProvider(O, P, /*Create*/ false); if (IsUndefined(provider)) return; return provider.OrdinaryGetOwnMetadata(MetadataKey, O, P); } // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { var provider = GetMetadataProvider(O, P, /*Create*/ true); provider.OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P); } // 3.1.6.1 OrdinaryMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarymetadatakeys function OrdinaryMetadataKeys(O, P) { var ownKeys = OrdinaryOwnMetadataKeys(O, P); var parent = OrdinaryGetPrototypeOf(O); if (parent === null) return ownKeys; var parentKeys = OrdinaryMetadataKeys(parent, P); if (parentKeys.length <= 0) return ownKeys; if (ownKeys.length <= 0) return parentKeys; var set = new _Set(); var keys = []; for (var _i = 0, ownKeys_1 = ownKeys; _i < ownKeys_1.length; _i++) { var key = ownKeys_1[_i]; var hasKey = set.has(key); if (!hasKey) { set.add(key); keys.push(key); } } for (var _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) { var key = parentKeys_1[_a]; var hasKey = set.has(key); if (!hasKey) { set.add(key); keys.push(key); } } return keys; } // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys function OrdinaryOwnMetadataKeys(O, P) { var provider = GetMetadataProvider(O, P, /*create*/ false); if (!provider) { return []; } return provider.OrdinaryOwnMetadataKeys(O, P); } // 6 ECMAScript Data Types and Values // https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values function Type(x) { if (x === null) return 1 /* Null */; switch (typeof x) { case "undefined": return 0 /* Undefined */; case "boolean": return 2 /* Boolean */; case "string": return 3 /* String */; case "symbol": return 4 /* Symbol */; case "number": return 5 /* Number */; case "object": return x === null ? 1 /* Null */ : 6 /* Object */; default: return 6 /* Object */; } } // 6.1.1 The Undefined Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-undefined-type function IsUndefined(x) { return x === undefined; } // 6.1.2 The Null Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-null-type function IsNull(x) { return x === null; } // 6.1.5 The Symbol Type // https://tc39.github.io/ecma262/#sec-ecmascript-language-types-symbol-type function IsSymbol(x) { return typeof x === "symbol"; } // 6.1.7 The Object Type // https://tc39.github.io/ecma262/#sec-object-type function IsObject(x) { return typeof x === "object" ? x !== null : typeof x === "function"; } // 7.1 Type Conversion // https://tc39.github.io/ecma262/#sec-type-conversion // 7.1.1 ToPrimitive(input [, PreferredType]) // https://tc39.github.io/ecma262/#sec-toprimitive function ToPrimitive(input, PreferredType) { switch (Type(input)) { case 0 /* Undefined */: return input; case 1 /* Null */: return input; case 2 /* Boolean */: return input; case 3 /* String */: return input; case 4 /* Symbol */: return input; case 5 /* Number */: return input; } var hint = "string" ; var exoticToPrim = GetMethod(input, toPrimitiveSymbol); if (exoticToPrim !== undefined) { var result = exoticToPrim.call(input, hint); if (IsObject(result)) throw new TypeError(); return result; } return OrdinaryToPrimitive(input); } // 7.1.1.1 OrdinaryToPrimitive(O, hint) // https://tc39.github.io/ecma262/#sec-ordinarytoprimitive function OrdinaryToPrimitive(O, hint) { var valueOf, result; { var toString_1 = O.toString; if (IsCallable(toString_1)) { var result = toString_1.call(O); if (!IsObject(result)) return result; } var valueOf = O.valueOf; if (IsCallable(valueOf)) { var result = valueOf.call(O); if (!IsObject(result)) return result; } } throw new TypeError(); } // 7.1.2 ToBoolean(argument) // https://tc39.github.io/ecma262/2016/#sec-toboolean function ToBoolean(argument) { return !!argument; } // 7.1.12 ToString(argument) // https://tc39.github.io/ecma262/#sec-tostring function ToString(argument) { return "" + argument; } // 7.1.14 ToPropertyKey(argument) // https://tc39.github.io/ecma262/#sec-topropertykey function ToPropertyKey(argument) { var key = ToPrimitive(argument); if (IsSymbol(key)) return key; return ToString(key); } // 7.2 Testing and Comparison Operations // https://tc39.github.io/ecma262/#sec-testing-and-comparison-operations // 7.2.2 IsArray(argument) // https://tc39.github.io/ecma262/#sec-isarray function IsArray(argument) { return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]"; } // 7.2.3 IsCallable(argument) // https://tc39.github.io/ecma262/#sec-iscallable function IsCallable(argument) { // NOTE: This is an approximation as we cannot check for [[Call]] internal method. return typeof argument === "function"; } // 7.2.4 IsConstructor(argument) // https://tc39.github.io/ecma262/#sec-isconstructor function IsConstructor(argument) { // NOTE: This is an approximation as we cannot check for [[Construct]] internal method. return typeof argument === "function"; } // 7.2.7 IsPropertyKey(argument) // https://tc39.github.io/ecma262/#sec-ispropertykey function IsPropertyKey(argument) { switch (Type(argument)) { case 3 /* String */: return true; case 4 /* Symbol */: return true; default: return false; } } function SameValueZero(x, y) { return x === y || x !== x && y !== y; } // 7.3 Operations on Objects // https://tc39.github.io/ecma262/#sec-operations-on-objects // 7.3.9 GetMethod(V, P) // https://tc39.github.io/ecma262/#sec-getmethod function GetMethod(V, P) { var func = V[P]; if (func === undefined || func === null) return undefined; if (!IsCallable(func)) throw new TypeError(); return func; } // 7.4 Operations on Iterator Objects // https://tc39.github.io/ecma262/#sec-operations-on-iterator-objects function GetIterator(obj) { var method = GetMethod(obj, iteratorSymbol); if (!IsCallable(method)) throw new TypeError(); // from Call var iterator = method.call(obj); if (!IsObject(iterator)) throw new TypeError(); return iterator; } // 7.4.4 IteratorValue(iterResult) // https://tc39.github.io/ecma262/2016/#sec-iteratorvalue function IteratorValue(iterResult) { return iterResult.value; } // 7.4.5 IteratorStep(iterator) // https://tc39.github.io/ecma262/#sec-iteratorstep function IteratorStep(iterator) { var result = iterator.next(); return result.done ? false : result; } // 7.4.6 IteratorClose(iterator, completion) // https://tc39.github.io/ecma262/#sec-iteratorclose function IteratorClose(iterator) { var f = iterator["return"]; if (f) f.call(iterator); } // 9.1 Ordinary Object Internal Methods and Internal Slots // https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots // 9.1.1.1 OrdinaryGetPrototypeOf(O) // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof function OrdinaryGetPrototypeOf(O) { var proto = Object.getPrototypeOf(O); if (typeof O !== "function" || O === functionPrototype) return proto; // TypeScript doesn't set __proto__ in ES5, as it's non-standard. // Try to determine the superclass constructor. Compatible implementations // must either set __proto__ on a subclass constructor to the superclass constructor, // or ensure each class has a valid `constructor` property on its prototype that // points back to the constructor. // If this is not the same as Function.[[Prototype]], then this is definately inherited. // This is the case when in ES6 or when using __proto__ in a compatible browser. if (proto !== functionPrototype) return proto; // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage. var prototype = O.prototype; var prototypeProto = prototype && Object.getPrototypeOf(prototype); if (prototypeProto == null || prototypeProto === Object.prototype) return proto; // If the constructor was not a function, then we cannot determine the heritage. var constructor = prototypeProto.constructor; if (typeof constructor !== "function") return proto; // If we have some kind of self-reference, then we cannot determine the heritage. if (constructor === O) return proto; // we have a pretty good guess at the heritage. return constructor; } // Global metadata registry // - Allows `import "reflect-metadata"` and `import "reflect-metadata/no-conflict"` to interoperate. // - Uses isolated metadata if `Reflect` is frozen before the registry can be installed. /** * Creates a registry used to allow multiple `reflect-metadata` providers. */ function CreateMetadataRegistry() { var fallback; if (!IsUndefined(registrySymbol) && typeof root.Reflect !== "undefined" && !(registrySymbol in root.Reflect) && typeof root.Reflect.defineMetadata === "function") { // interoperate with older version of `reflect-metadata` that did not support a registry. fallback = CreateFallbackProvider(root.Reflect); } var first; var second; var rest; var targetProviderMap = new _WeakMap(); var registry = { registerProvider: registerProvider, getProvider: getProvider, setProvider: setProvider, }; return registry; function registerProvider(provider) { if (!Object.isExtensible(registry)) { throw new Error("Cannot add provider to a frozen registry."); } switch (true) { case fallback === provider: break; case IsUndefined(first): first = provider; break; case first === provider: break; case IsUndefined(second): second = provider; break; case second === provider: break; default: if (rest === undefined) rest = new _Set(); rest.add(provider); break; } } function getProviderNoCache(O, P) { if (!IsUndefined(first)) { if (first.isProviderFor(O, P)) return first; if (!IsUndefined(second)) { if (second.isProviderFor(O, P)) return first; if (!IsUndefined(rest)) { var iterator = GetIterator(rest); while (true) { var next = IteratorStep(iterator); if (!next) { return undefined; } var provider = IteratorValue(next); if (provider.isProviderFor(O, P)) { IteratorClose(iterator); return provider; } } } } } if (!IsUndefined(fallback) && fallback.isProviderFor(O, P)) { return fallback; } return undefined; } function getProvider(O, P) { var providerMap = targetProviderMap.get(O); var provider; if (!IsUndefined(providerMap)) { provider = providerMap.get(P); } if (!IsUndefined(provider)) { return provider; } provider = getProviderNoCache(O, P); if (!IsUndefined(provider)) { if (IsUndefined(providerMap)) { providerMap = new _Map(); targetProviderMap.set(O, providerMap); } providerMap.set(P, provider); } return provider; } function hasProvider(provider) { if (IsUndefined(provider)) throw new TypeError(); return first === provider || second === provider || !IsUndefined(rest) && rest.has(provider); } function setProvider(O, P, provider) { if (!hasProvider(provider)) { throw new Error("Metadata provider not registered."); } var existingProvider = getProvider(O, P); if (existingProvider !== provider) { if (!IsUndefined(existingProvider)) { return false; } var providerMap = targetProviderMap.get(O); if (IsUndefined(providerMap)) { providerMap = new _Map(); targetProviderMap.set(O, providerMap); } providerMap.set(P, provider); } return true; } } /** * Gets or creates the shared registry of metadata providers. */ function GetOrCreateMetadataRegistry() { var metadataRegistry; if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) { metadataRegistry = root.Reflect[registrySymbol]; } if (IsUndefined(metadataRegistry)) { metadataRegistry = CreateMetadataRegistry(); } if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) { Object.defineProperty(root.Reflect, registrySymbol, { enumerable: false, configurable: false, writable: false, value: metadataRegistry }); } return metadataRegistry; } function CreateMetadataProvider(registry) { // [[Metadata]] internal slot // https://rbuckton.github.io/reflect-metadata/#ordinary-object-internal-methods-and-internal-slots var metadata = new _WeakMap(); var provider = { isProviderFor: function (O, P) { var targetMetadata = metadata.get(O); if (IsUndefined(targetMetadata)) return false; return targetMetadata.has(P); }, OrdinaryDefineOwnMetadata: OrdinaryDefineOwnMetadata, OrdinaryHasOwnMetadata: OrdinaryHasOwnMetadata, OrdinaryGetOwnMetadata: OrdinaryGetOwnMetadata, OrdinaryOwnMetadataKeys: OrdinaryOwnMetadataKeys, OrdinaryDeleteMetadata: OrdinaryDeleteMetadata, }; metadataRegistry.registerProvider(provider); return provider; function GetOrCreateMetadataMap(O, P, Create) { var targetMetadata = metadata.get(O); var createdTargetMetadata = false; if (IsUndefined(targetMetadata)) { if (!Create) return undefined; targetMetadata = new _Map(); metadata.set(O, targetMetadata); createdTargetMetadata = true; } var metadataMap = targetMetadata.get(P); if (IsUndefined(metadataMap)) { if (!Create) return undefined; metadataMap = new _Map(); targetMetadata.set(P, metadataMap); if (!registry.setProvider(O, P, provider)) { targetMetadata.delete(P); if (createdTargetMetadata) { metadata.delete(O); } throw new Error("Wrong provider for target."); } } return metadataMap; } // 3.1.2.1 OrdinaryHasOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryhasownmetadata function OrdinaryHasOwnMetadata(MetadataKey, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return false; return ToBoolean(metadataMap.has(MetadataKey)); } // 3.1.4.1 OrdinaryGetOwnMetadata(MetadataKey, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarygetownmetadata function OrdinaryGetOwnMetadata(MetadataKey, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return undefined; return metadataMap.get(MetadataKey); } // 3.1.5.1 OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) // https://rbuckton.github.io/reflect-metadata/#ordinarydefineownmetadata function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ true); metadataMap.set(MetadataKey, MetadataValue); } // 3.1.7.1 OrdinaryOwnMetadataKeys(O, P) // https://rbuckton.github.io/reflect-metadata/#ordinaryownmetadatakeys function OrdinaryOwnMetadataKeys(O, P) { var keys = []; var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return keys; var keysObj = metadataMap.keys(); var iterator = GetIterator(keysObj); var k = 0; while (true) { var next = IteratorStep(iterator); if (!next) { keys.length = k; return keys; } var nextValue = IteratorValue(next); try { keys[k] = nextValue; } catch (e) { try { IteratorClose(iterator); } finally { throw e; } } k++; } } function OrdinaryDeleteMetadata(MetadataKey, O, P) { var metadataMap = GetOrCreateMetadataMap(O, P, /*Create*/ false); if (IsUndefined(metadataMap)) return false; if (!metadataMap.delete(MetadataKey)) return false; if (metadataMap.size === 0) { var targetMetadata = metadata.get(O); if (!IsUndefined(targetMetadata)) { targetMetadata.delete(P); if (targetMetadata.size === 0) { metadata.delete(targetMetadata); } } } return true; } } function CreateFallbackProvider(reflect) { var defineMetadata = reflect.defineMetadata, hasOwnMetadata = reflect.hasOwnMetadata, getOwnMetadata = reflect.getOwnMetadata, getOwnMetadataKeys = reflect.getOwnMetadataKeys, deleteMetadata = reflect.deleteMetadata; var metadataOwner = new _WeakMap(); var provider = { isProviderFor: function (O, P) { var metadataPropertySet = metadataOwner.get(O); if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P)) { return true; } if (getOwnMetadataKeys(O, P).length) { if (IsUndefined(metadataPropertySet)) { metadataPropertySet = new _Set(); metadataOwner.set(O, metadataPropertySet); } metadataPropertySet.add(P); return true; } return false; }, OrdinaryDefineOwnMetadata: defineMetadata, OrdinaryHasOwnMetadata: hasOwnMetadata, OrdinaryGetOwnMetadata: getOwnMetadata, OrdinaryOwnMetadataKeys: getOwnMetadataKeys, OrdinaryDeleteMetadata: deleteMetadata, }; return provider; } /** * Gets the metadata provider for an object. If the object has no metadata provider and this is for a create operation, * then this module's metadata provider is assigned to the object. */ function GetMetadataProvider(O, P, Create) { var registeredProvider = metadataRegistry.getProvider(O, P); if (!IsUndefined(registeredProvider)) { return registeredProvider; } if (Create) { if (metadataRegistry.setProvider(O, P, metadataProvider)) { return metadataProvider; } throw new Error("Illegal state."); } return undefined; } // naive Map shim function CreateMapPolyfill() { var cacheSentinel = {}; var arraySentinel = []; var MapIterator = /** @class */ (function () { function MapIterator(keys, values, selector) { this._index = 0; this._keys = keys; this._values = values; this._selector = selector; } MapIterator.prototype["@@iterator"] = function () { return this; }; MapIterator.prototype[iteratorSymbol] = function () { return this; }; MapIterator.prototype.next = function () { var index = this._index; if (index >= 0 && index < this._keys.length) { var result = this._selector(this._keys[index], this._values[index]); if (index + 1 >= this._keys.length) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } else { this._index++; } return { value: result, done: false }; } return { value: undefined, done: true }; }; MapIterator.prototype.throw = function (error) { if (this._index >= 0) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } throw error; }; MapIterator.prototype.return = function (value) { if (this._index >= 0) { this._index = -1; this._keys = arraySentinel; this._values = arraySentinel; } return { value: value, done: true }; }; return MapIterator; }()); var Map = /** @class */ (function () { function Map() { this._keys = []; this._values = []; this._cacheKey = cacheSentinel; this._cacheIndex = -2; } Object.defineProperty(Map.prototype, "size", { get: function () { return this._keys.length; }, enumerable: true, configurable: true }); Map.prototype.has = function (key) { return this._find(key, /*insert*/ false) >= 0; }; Map.prototype.get = function (key) { var index = this._find(key, /*insert*/ false); return index >= 0 ? this._values[index] : undefined; }; Map.prototype.set = function (key, value) { var index = this._find(key, /*insert*/ true); this._values[index] = value; return this; }; Map.prototype.delete = function (key) { var index = this._find(key, /*insert*/ false); if (index >= 0) { var size = this._keys.length; for (var i = index + 1; i < size; i++) { this._keys[i - 1] = this._keys[i]; this._values[i - 1] = this._values[i]; } this._keys.length--; this._values.length--; if (SameValueZero(key, this._cacheKey)) { this._cacheKey = cacheSentinel; this._cacheIndex = -2; } return true; } return false; }; Map.prototype.clear = function () { this._keys.length = 0; this._values.length = 0; this._cacheKey = cacheSentinel; this._cacheIndex = -2; }; Map.prototype.keys = function () { return new MapIterator(this._keys, this._values, getKey); }; Map.prototype.values = function () { return new MapIterator(this._keys, this._values, getValue); }; Map.prototype.entries = function () { return new MapIterator(this._keys, this._values, getEntry); }; Map.prototype["@@iterator"] = function () { return this.entries(); }; Map.prototype[iteratorSymbol] = function () { return this.entries(); }; Map.prototype._find = function (key, insert) { if (!SameValueZero(this._cacheKey, key)) { this._cacheIndex = -1; for (var i = 0; i < this._keys.length; i++) { if (SameValueZero(this._keys[i], key)) { this._cacheIndex = i; break; } } } if (this._cacheIndex < 0 && insert) { this._cacheIndex = this._keys.length; this._keys.push(key); this._values.push(undefined); } return this._cacheIndex; }; return Map; }()); return Map; function getKey(key, _) { return key; } function getValue(_, value) { return value; } function getEntry(key, value) { return [key, value]; } } // naive Set shim function CreateSetPolyfill() { var Set = /** @class */ (function () { function Set() { this._map = new _Map(); } Object.defineProperty(Set.prototype, "size", { get: function () { return this._map.size; }, enumerable: true, configurable: true }); Set.prototype.has = function (value) { return this._map.has(value); }; Set.prototype.add = function (value) { return this._map.set(value, value), this; }; Set.prototype.delete = function (value) { return this._map.delete(value); }; Set.prototype.clear = function () { this._map.clear(); }; Set.prototype.keys = function () { return this._map.keys(); }; Set.prototype.values = function () { return this._map.keys(); }; Set.prototype.entries = function () { return this._map.entries(); }; Set.prototype["@@iterator"] = function () { return this.keys(); }; Set.prototype[iteratorSymbol] = function () { return this.keys(); }; return Set; }()); return Set; } // naive WeakMap shim function CreateWeakMapPolyfill() { var UUID_SIZE = 16; var keys = HashMap.create(); var rootKey = CreateUniqueKey(); return /** @class */ (function () { function WeakMap() { this._key = CreateUniqueKey(); } WeakMap.prototype.has = function (target) { var table = GetOrCreateWeakMapTable(target, /*create*/ false); return table !== undefined ? HashMap.has(table, this._key) : false; }; WeakMap.prototype.get = function (target) { var table = GetOrCreateWeakMapTable(target, /*create*/ false); return table !== undefined ? HashMap.get(table, this._key) : undefined; }; WeakMap.prototype.set = function (target, value) { var table = GetOrCreateWeakMapTable(target, /*create*/ true); table[this._key] = value; return this; }; WeakMap.prototype.delete = function (target) { var table = GetOrCreateWeakMapTable(target, /*create*/ false); return table !== undefined ? delete table[this._key] : false; }; WeakMap.prototype.clear = function () { // NOTE: not a real clear, just makes the previous data unreachable this._key = CreateUniqueKey(); }; return WeakMap; }()); function CreateUniqueKey() { var key; do key = "@@WeakMap@@" + CreateUUID(); while (HashMap.has(keys, key)); keys[key] = true; return key; } function GetOrCreateWeakMapTable(target, create) { if (!hasOwn.call(target, rootKey)) { if (!create) return undefined; Object.defineProperty(target, rootKey, { value: HashMap.create() }); } return target[rootKey]; } function FillRandomBytes(buffer, size) { for (var i = 0; i < size; ++i) buffer[i] = Math.random() * 0xff | 0; return buffer; } function GenRandomBytes(size) { if (typeof Uint8Array === "function") { var array = new Uint8Array(size); if (typeof crypto !== "undefined") { crypto.getRandomValues(array); } else if (typeof msCrypto !== "undefined") { msCrypto.getRandomValues(array); } else { FillRandomBytes(array, size); } return array; } return FillRandomBytes(new Array(size), size); } function CreateUUID() { var data = GenRandomBytes(UUID_SIZE); // mark as random - RFC 4122 § 4.4 data[6] = data[6] & 0x4f | 0x40; data[8] = data[8] & 0xbf | 0x80; var result = ""; for (var offset = 0; offset < UUID_SIZE; ++offset) { var byte = data[offset]; if (offset === 4 || offset === 6 || offset === 8) result += "-"; if (byte < 16) result += "0"; result += byte.toString(16).toLowerCase(); } return result; } } // uses a heuristic used by v8 and chakra to force an object into dictionary mode. function MakeDictionary(obj) { obj.__ = undefined; delete obj.__; return obj; } }); })(Reflect$1 || (Reflect$1 = {})); function coerce$1(o) { if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o; if (o instanceof ArrayBuffer) return new Uint8Array(o); if (ArrayBuffer.isView(o)) { return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); } throw new Error('Unknown type, must be binary type'); } function fromString$1(str) { return new TextEncoder().encode(str); } function toString$1(b) { return new TextDecoder().decode(b); } /* eslint-disable */ // base-x encoding / decoding // Copyright (c) 2018 base-x contributors // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. /** * @param {string} ALPHABET * @param {any} name */ function base(ALPHABET, name) { if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long'); } var BASE_MAP = new Uint8Array(256); for (var j = 0; j < BASE_MAP.length; j++) { BASE_MAP[j] = 255; } for (var i = 0; i < ALPHABET.length; i++) { var x = ALPHABET.charAt(i); var xc = x.charCodeAt(0); if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous'); } BASE_MAP[xc] = i; } var BASE = ALPHABET.length; var LEADER = ALPHABET.charAt(0); var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up /** * @param {any[] | Iterable} source */ function encode(source) { // @ts-ignore if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) { source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); } else if (Array.isArray(source)) { source = Uint8Array.from(source); } if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array'); } if (source.length === 0) { return ''; } // Skip & count leading zeroes. var zeroes = 0; var length = 0; var pbegin = 0; var pend = source.length; while (pbegin !== pend && source[pbegin] === 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. var size = ((pend - pbegin) * iFACTOR + 1) >>> 0; var b58 = new Uint8Array(size); // Process the bytes. while (pbegin !== pend) { var carry = source[pbegin]; // Apply "b58 = b58 * 256 + ch". var i = 0; for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) { carry += (256 * b58[it1]) >>> 0; b58[it1] = (carry % BASE) >>> 0; carry = (carry / BASE) >>> 0; } if (carry !== 0) { throw new Error('Non-zero carry'); } length = i; pbegin++; } // Skip leading zeroes in base58 result. var it2 = size - length; while (it2 !== size && b58[it2] === 0) { it2++; } // Translate the result into a string. var str = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } return str; } /** * @param {string | string[]} source */ function decodeUnsafe(source) { if (typeof source !== 'string') { throw new TypeError('Expected String'); } if (source.length === 0) { return new Uint8Array(); } var psz = 0; // Skip leading spaces. if (source[psz] === ' ') { return; } // Skip and count leading '1's. var zeroes = 0; var length = 0; while (source[psz] === LEADER) { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up. var b256 = new Uint8Array(size); // Process the characters. while (source[psz]) { // Decode character var carry = BASE_MAP[source.charCodeAt(psz)]; // Invalid character if (carry === 255) { return; } var i = 0; for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) { carry += (BASE * b256[it3]) >>> 0; b256[it3] = (carry % 256) >>> 0; carry = (carry / 256) >>> 0; } if (carry !== 0) { throw new Error('Non-zero carry'); } length = i; psz++; } // Skip trailing spaces. if (source[psz] === ' ') { return; } // Skip leading zeroes in b256. var it4 = size - length; while (it4 !== size && b256[it4] === 0) { it4++; } var vch = new Uint8Array(zeroes + (size - it4)); var j = zeroes; while (it4 !== size) { vch[j++] = b256[it4++]; } return vch; } /** * @param {string | string[]} string */ function decode(string) { var buffer = decodeUnsafe(string); if (buffer) { return buffer; } throw new Error(`Non-${name} character`); } return { encode: encode, decodeUnsafe: decodeUnsafe, decode: decode }; } var src$1 = base; var _brrp__multiformats_scope_baseX = src$1; /** * Class represents both BaseEncoder and MultibaseEncoder meaning it * can be used to encode to multibase or base encode without multibase * prefix. */ class Encoder { name; prefix; baseEncode; constructor(name, prefix, baseEncode) { this.name = name; this.prefix = prefix; this.baseEncode = baseEncode; } encode(bytes) { if (bytes instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes)}`; } else { throw Error('Unknown type, must be binary type'); } } } /** * Class represents both BaseDecoder and MultibaseDecoder so it could be used * to decode multibases (with matching prefix) or just base decode strings * with corresponding base encoding. */ class Decoder { name; prefix; baseDecode; prefixCodePoint; constructor(name, prefix, baseDecode) { this.name = name; this.prefix = prefix; const prefixCodePoint = prefix.codePointAt(0); /* c8 ignore next 3 */ if (prefixCodePoint === undefined) { throw new Error('Invalid prefix character'); } this.prefixCodePoint = prefixCodePoint; this.baseDecode = baseDecode; } decode(text) { if (typeof text === 'string') { if (text.codePointAt(0) !== this.prefixCodePoint) { throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); } return this.baseDecode(text.slice(this.prefix.length)); } else { throw Error('Can only multibase decode strings'); } } or(decoder) { return or$1(this, decoder); } } class ComposedDecoder { decoders; constructor(decoders) { this.decoders = decoders; } or(decoder) { return or$1(this, decoder); } decode(input) { const prefix = input[0]; const decoder = this.decoders[prefix]; if (decoder != null) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } } function or$1(left, right) { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions return new ComposedDecoder({ ...(left.decoders ?? { [left.prefix]: left }), ...(right.decoders ?? { [right.prefix]: right }) }); } class Codec { name; prefix; baseEncode; baseDecode; encoder; decoder; constructor(name, prefix, baseEncode, baseDecode) { this.name = name; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder(name, prefix, baseEncode); this.decoder = new Decoder(name, prefix, baseDecode); } encode(input) { return this.encoder.encode(input); } decode(input) { return this.decoder.decode(input); } } function from({ name, prefix, encode, decode }) { return new Codec(name, prefix, encode, decode); } function baseX({ name, prefix, alphabet }) { const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name); return from({ prefix, name, encode, decode: (text) => coerce$1(decode(text)) }); } function decode$2(string, alphabet, bitsPerChar, name) { // Build the character lookup table: const codes = {}; for (let i = 0; i < alphabet.length; ++i) { codes[alphabet[i]] = i; } // Count the padding bytes: let end = string.length; while (string[end - 1] === '=') { --end; } // Allocate the output: const out = new Uint8Array((end * bitsPerChar / 8) | 0); // Parse the data: let bits = 0; // Number of bits currently in the buffer let buffer = 0; // Bits waiting to be written out, MSB first let written = 0; // Next byte to write for (let i = 0; i < end; ++i) { // Read one character from the string: const value = codes[string[i]]; if (value === undefined) { throw new SyntaxError(`Non-${name} character`); } // Append the bits to the buffer: buffer = (buffer << bitsPerChar) | value; bits += bitsPerChar; // Write out some bits if the buffer has a byte's worth: if (bits >= 8) { bits -= 8; out[written++] = 0xff & (buffer >> bits); } } // Verify that we have received just enough bits: if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) { throw new SyntaxError('Unexpected end of data'); } return out; } function encode$2(data, alphabet, bitsPerChar) { const pad = alphabet[alphabet.length - 1] === '='; const mask = (1 << bitsPerChar) - 1; let out = ''; let bits = 0; // Number of bits currently in the buffer let buffer = 0; // Bits waiting to be written out, MSB first for (let i = 0; i < data.length; ++i) { // Slurp data into the buffer: buffer = (buffer << 8) | data[i]; bits += 8; // Write out as much as we can: while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet[mask & (buffer >> bits)]; } } // Partial character: if (bits !== 0) { out += alphabet[mask & (buffer << (bitsPerChar - bits))]; } // Add padding characters until we hit a byte boundary: if (pad) { while (((out.length * bitsPerChar) & 7) !== 0) { out += '='; } } return out; } /** * RFC4648 Factory */ function rfc4648({ name, prefix, bitsPerChar, alphabet }) { return from({ prefix, name, encode(input) { return encode$2(input, alphabet, bitsPerChar); }, decode(input) { return decode$2(input, alphabet, bitsPerChar, name); } }); } const base10 = baseX({ prefix: '9', name: 'base10', alphabet: '0123456789' }); var base10$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base10: base10 }); const base16 = rfc4648({ prefix: 'f', name: 'base16', alphabet: '0123456789abcdef', bitsPerChar: 4 }); const base16upper = rfc4648({ prefix: 'F', name: 'base16upper', alphabet: '0123456789ABCDEF', bitsPerChar: 4 }); var base16$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base16: base16, base16upper: base16upper }); const base2 = rfc4648({ prefix: '0', name: 'base2', alphabet: '01', bitsPerChar: 1 }); var base2$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base2: base2 }); const alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂'); const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([]))); const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { const codePoint = c.codePointAt(0); if (codePoint == null) { throw new Error(`Invalid character: ${c}`); } p[codePoint] = i; return p; }, ([]))); function encode$1(data) { return data.reduce((p, c) => { p += alphabetBytesToChars[c]; return p; }, ''); } function decode$1(str) { const byts = []; for (const char of str) { const codePoint = char.codePointAt(0); if (codePoint == null) { throw new Error(`Invalid character: ${char}`); } const byt = alphabetCharsToBytes[codePoint]; if (byt == null) { throw new Error(`Non-base256emoji character: ${char}`); } byts.push(byt); } return new Uint8Array(byts); } const base256emoji = from({ prefix: '🚀', name: 'base256emoji', encode: encode$1, decode: decode$1 }); var base256emoji$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base256emoji: base256emoji }); const base32 = rfc4648({ prefix: 'b', name: 'base32', alphabet: 'abcdefghijklmnopqrstuvwxyz234567', bitsPerChar: 5 }); const base32upper = rfc4648({ prefix: 'B', name: 'base32upper', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', bitsPerChar: 5 }); const base32pad = rfc4648({ prefix: 'c', name: 'base32pad', alphabet: 'abcdefghijklmnopqrstuvwxyz234567=', bitsPerChar: 5 }); const base32padupper = rfc4648({ prefix: 'C', name: 'base32padupper', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=', bitsPerChar: 5 }); const base32hex = rfc4648({ prefix: 'v', name: 'base32hex', alphabet: '0123456789abcdefghijklmnopqrstuv', bitsPerChar: 5 }); const base32hexupper = rfc4648({ prefix: 'V', name: 'base32hexupper', alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV', bitsPerChar: 5 }); const base32hexpad = rfc4648({ prefix: 't', name: 'base32hexpad', alphabet: '0123456789abcdefghijklmnopqrstuv=', bitsPerChar: 5 }); const base32hexpadupper = rfc4648({ prefix: 'T', name: 'base32hexpadupper', alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=', bitsPerChar: 5 }); const base32z = rfc4648({ prefix: 'h', name: 'base32z', alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769', bitsPerChar: 5 }); var base32$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base32: base32, base32hex: base32hex, base32hexpad: base32hexpad, base32hexpadupper: base32hexpadupper, base32hexupper: base32hexupper, base32pad: base32pad, base32padupper: base32padupper, base32upper: base32upper, base32z: base32z }); const base36 = baseX({ prefix: 'k', name: 'base36', alphabet: '0123456789abcdefghijklmnopqrstuvwxyz' }); const base36upper = baseX({ prefix: 'K', name: 'base36upper', alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' }); var base36$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base36: base36, base36upper: base36upper }); const base58btc = baseX({ name: 'base58btc', prefix: 'z', alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' }); const base58flickr = baseX({ name: 'base58flickr', prefix: 'Z', alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' }); var base58 = /*#__PURE__*/Object.freeze({ __proto__: null, base58btc: base58btc, base58flickr: base58flickr }); const base64 = rfc4648({ prefix: 'm', name: 'base64', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', bitsPerChar: 6 }); const base64pad = rfc4648({ prefix: 'M', name: 'base64pad', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', bitsPerChar: 6 }); const base64url = rfc4648({ prefix: 'u', name: 'base64url', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', bitsPerChar: 6 }); const base64urlpad = rfc4648({ prefix: 'U', name: 'base64urlpad', alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=', bitsPerChar: 6 }); var base64$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base64: base64, base64pad: base64pad, base64url: base64url, base64urlpad: base64urlpad }); const base8 = rfc4648({ prefix: '7', name: 'base8', alphabet: '01234567', bitsPerChar: 3 }); var base8$1 = /*#__PURE__*/Object.freeze({ __proto__: null, base8: base8 }); const identity = from({ prefix: '\x00', name: 'identity', encode: (buf) => toString$1(buf), decode: (str) => fromString$1(str) }); var identityBase = /*#__PURE__*/Object.freeze({ __proto__: null, identity: identity }); new TextEncoder(); new TextDecoder(); const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$1, ...base256emoji$1 }; /** * Returns a `Uint8Array` of the requested size. Referenced memory will * be initialized to 0. */ /** * Where possible returns a Uint8Array of the requested size that references * uninitialized memory. Only use if you are certain you will immediately * overwrite every value in the returned `Uint8Array`. */ function allocUnsafe(size = 0) { return new Uint8Array(size); } function createCodec(name, prefix, encode, decode) { return { name, prefix, encoder: { name, prefix, encode }, decoder: { decode } }; } const string$3 = createCodec('utf8', 'u', (buf) => { const decoder = new TextDecoder('utf8'); return 'u' + decoder.decode(buf); }, (str) => { const encoder = new TextEncoder(); return encoder.encode(str.substring(1)); }); const ascii = createCodec('ascii', 'a', (buf) => { let string = 'a'; for (let i = 0; i < buf.length; i++) { string += String.fromCharCode(buf[i]); } return string; }, (str) => { str = str.substring(1); const buf = allocUnsafe(str.length); for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } return buf; }); const BASES = { utf8: string$3, 'utf-8': string$3, hex: bases.base16, latin1: ascii, ascii, binary: ascii, ...bases }; /** * Create a `Uint8Array` from the passed string * * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module. * * Also `ascii` which is similar to node's 'binary' encoding. */ function fromString(string, encoding = 'utf8') { const base = BASES[encoding]; if (base == null) { throw new Error(`Unsupported encoding "${encoding}"`); } // add multibase prefix return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions } /** * Turns a `Uint8Array` into a string. * * Supports `utf8`, `utf-8` and any encoding supported by the multibase module. * * Also `ascii` which is similar to node's 'binary' encoding. */ function toString(array, encoding = 'utf8') { const base = BASES[encoding]; if (base == null) { throw new Error(`Unsupported encoding "${encoding}"`); } // strip multibase prefix return base.encoder.encode(array).substring(1); } const pathSepS = '/'; const pathSepB = new TextEncoder().encode(pathSepS); const pathSep = pathSepB[0]; /** * A Key represents the unique identifier of an object. * Our Key scheme is inspired by file systems and Google App Engine key model. * Keys are meant to be unique across a system. Keys are hierarchical, * incorporating more and more specific namespaces. Thus keys can be deemed * 'children' or 'ancestors' of other keys: * - `new Key('/Comedy')` * - `new Key('/Comedy/MontyPython')` * Also, every namespace can be parametrized to embed relevant object * information. For example, the Key `name` (most specific namespace) could * include the object type: * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')` * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')` * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')` * */ class Key { _buf; /** * @param {string | Uint8Array} s * @param {boolean} [clean] */ constructor(s, clean) { if (typeof s === 'string') { this._buf = fromString(s); } else if (s instanceof Uint8Array) { this._buf = s; } else { throw new Error('Invalid key, should be String of Uint8Array'); } if (clean == null) { clean = true; } if (clean) { this.clean(); } if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) { throw new Error('Invalid key'); } } /** * Convert to the string representation * * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use. * @returns {string} */ toString(encoding = 'utf8') { return toString(this._buf, encoding); } /** * Return the Uint8Array representation of the key * * @returns {Uint8Array} */ uint8Array() { return this._buf; } /** * Return string representation of the key * * @returns {string} */ get [Symbol.toStringTag]() { return `Key(${this.toString()})`; } /** * Constructs a key out of a namespace array. * * @param {Array} list - The array of namespaces * @returns {Key} * * @example * ```js * Key.withNamespaces(['one', 'two']) * // => Key('/one/two') * ``` */ static withNamespaces(list) { return new Key(list.join(pathSepS)); } /** * Returns a randomly (uuid) generated key. * * @returns {Key} * * @example * ```js * Key.random() * // => Key('/344502982398') * ``` */ static random() { return new Key(Math.random().toString().substring(2)); } /** * @param {*} other */ static asKey(other) { if (other instanceof Uint8Array || typeof other === 'string') { // we can create a key from this return new Key(other); } if (typeof other.uint8Array === 'function') { // this is an older version or may have crossed the esm/cjs boundary return new Key(other.uint8Array()); } return null; } /** * Cleanup the current key * * @returns {void} */ clean() { if (this._buf == null || this._buf.byteLength === 0) { this._buf = pathSepB; } if (this._buf[0] !== pathSep) { const bytes = new Uint8Array(this._buf.byteLength + 1); bytes.fill(pathSep, 0, 1); bytes.set(this._buf, 1); this._buf = bytes; } // normalize does not remove trailing slashes while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) { this._buf = this._buf.subarray(0, -1); } } /** * Check if the given key is sorted lower than ourself. * * @param {Key} key - The other Key to check against * @returns {boolean} */ less(key) { const list1 = this.list(); const list2 = key.list(); for (let i = 0; i < list1.length; i++) { if (list2.length < i + 1) { return false; } const c1 = list1[i]; const c2 = list2[i]; if (c1 < c2) { return true; } else if (c1 > c2) { return false; } } return list1.length < list2.length; } /** * Returns the key with all parts in reversed order. * * @returns {Key} * * @example * ```js * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse() * // => Key('/Actor:JohnCleese/MontyPython/Comedy') * ``` */ reverse() { return Key.withNamespaces(this.list().slice().reverse()); } /** * Returns the `namespaces` making up this Key. * * @returns {Array} */ namespaces() { return this.list(); } /** Returns the "base" namespace of this key. * * @returns {string} * * @example * ```js * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace() * // => 'Actor:JohnCleese' * ``` */ baseNamespace() { const ns = this.namespaces(); return ns[ns.length - 1]; } /** * Returns the `list` representation of this key. * * @returns {Array} * * @example * ```js * new Key('/Comedy/MontyPython/Actor:JohnCleese').list() * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese'] * ``` */ list() { return this.toString().split(pathSepS).slice(1); } /** * Returns the "type" of this key (value of last namespace). * * @returns {string} * * @example * ```js * new Key('/Comedy/MontyPython/Actor:JohnCleese').type() * // => 'Actor' * ``` */ type() { return namespaceType(this.baseNamespace()); } /** * Returns the "name" of this key (field of last namespace). * * @returns {string} * * @example * ```js * new Key('/Comedy/MontyPython/Actor:JohnCleese').name() * // => 'JohnCleese' * ``` */ name() { return namespaceValue(this.baseNamespace()); } /** * Returns an "instance" of this type key (appends value to namespace). * * @param {string} s - The string to append. * @returns {Key} * * @example * ```js * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse') * // => Key('/Comedy/MontyPython/Actor:JohnCleese') * ``` */ instance(s) { return new Key(this.toString() + ':' + s); } /** * Returns the "path" of this key (parent + type). * * @returns {Key} * * @example * ```js * new Key('/Comedy/MontyPython/Actor:JohnCleese').path() * // => Key('/Comedy/MontyPython/Actor') * ``` */ path() { let p = this.parent().toString(); if (!p.endsWith(pathSepS)) { p += pathSepS; } p += this.type(); return new Key(p); } /** * Returns the `parent` Key of this Key. * * @returns {Key} * * @example * ```js * new Key("/Comedy/MontyPython/Actor:JohnCleese").parent() * // => Key("/Comedy/MontyPython") * ``` */ parent() { const list = this.list(); if (list.length === 1) { return new Key(pathSepS); } return new Key(list.slice(0, -1).join(pathSepS)); } /** * Returns the `child` Key of this Key. * * @param {Key} key - The child Key to add * @returns {Key} * * @example * ```js * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese')) * // => Key('/Comedy/MontyPython/Actor:JohnCleese') * ``` */ child(key) { if (this.toString() === pathSepS) { return key; } else if (key.toString() === pathSepS) { return this; } return new Key(this.toString() + key.toString(), false); } /** * Returns whether this key is a prefix of `other` * * @param {Key} other - The other key to test against * @returns {boolean} * * @example * ```js * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython') * // => true * ``` */ isAncestorOf(other) { if (other.toString() === this.toString()) { return false; } return other.toString().startsWith(this.toString()); } /** * Returns whether this key is a contains another as prefix. * * @param {Key} other - The other Key to test against * @returns {boolean} * * @example * ```js * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy') * // => true * ``` */ isDecendantOf(other) { if (other.toString() === this.toString()) { return false; } return this.toString().startsWith(other.toString()); } /** * Checks if this key has only one namespace. * * @returns {boolean} */ isTopLevel() { return this.list().length === 1; } /** * Concats one or more Keys into one new Key. * * @param {Array} keys - The array of keys to concatenate * @returns {Key} */ concat(...keys) { return Key.withNamespaces([...this.namespaces(), ...flatten$2(keys.map(key => key.namespaces()))]); } } /** * The first component of a namespace. `foo` in `foo:bar` * * @param {string} ns * @returns {string} */ function namespaceType(ns) { const parts = ns.split(':'); if (parts.length < 2) { return ''; } return parts.slice(0, -1).join(':'); } /** * The last component of a namespace, `baz` in `foo:bar:baz`. * * @param {string} ns * @returns {string} */ function namespaceValue(ns) { const parts = ns.split(':'); return parts[parts.length - 1]; } /** * Flatten array of arrays (only one level) * * @template T * @param {Array} arr * @returns {T[]} */ function flatten$2(arr) { return ([]).concat(...arr); } const SHARDING_FN = 'SHARDING'; /** * @packageDocumentation * * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values. * * @example * * ```javascript * import drain from 'it-drain' * * // This can also be an iterator, generator, etc * const values = [0, 1, 2, 3, 4] * * drain(values) * ``` * * Async sources must be awaited: * * ```javascript * import drain from 'it-drain' * * const values = async function * { * yield * [0, 1, 2, 3, 4] * } * * await drain(values()) * ``` */ function isAsyncIterable$6(thing) { return thing[Symbol.asyncIterator] != null; } function drain(source) { if (isAsyncIterable$6(source)) { return (async () => { for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars })(); } else { for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars } } /** * @packageDocumentation * * Lets you look at the contents of an async iterator and decide what to do * * @example * * ```javascript * import peekable from 'it-peekable' * * // This can also be an iterator, generator, etc * const values = [0, 1, 2, 3, 4] * * const it = peekable(value) * * const first = it.peek() * * console.info(first) // 0 * * it.push(first) * * console.info([...it]) * // [ 0, 1, 2, 3, 4 ] * ``` * * Async sources must be awaited: * * ```javascript * import peekable from 'it-peekable' * * const values = async function * () { * yield * [0, 1, 2, 3, 4] * } * * const it = peekable(values()) * * const first = await it.peek() * * console.info(first) // 0 * * it.push(first) * * console.info(await all(it)) * // [ 0, 1, 2, 3, 4 ] * ``` */ function peekable(iterable) { // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable const [iterator, symbol] = iterable[Symbol.asyncIterator] != null // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator] // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable : [iterable[Symbol.iterator](), Symbol.iterator]; const queue = []; // @ts-expect-error can't use symbol to index peekable return { peek: () => { return iterator.next(); }, push: (value) => { queue.push(value); }, next: () => { if (queue.length > 0) { return { done: false, value: queue.shift() }; } return iterator.next(); }, [symbol]() { return this; } }; } /** * @packageDocumentation * * Filter values out of an (async)iterable * * @example * * ```javascript * import all from 'it-all' * import filter from 'it-filter' * * // This can also be an iterator, generator, etc * const values = [0, 1, 2, 3, 4] * * const fn = (val, index) => val > 2 // Return boolean to keep item * * const arr = all(filter(values, fn)) * * console.info(arr) // 3, 4 * ``` * * Async sources and filter functions must be awaited: * * ```javascript * import all from 'it-all' * import filter from 'it-filter' * * const values = async function * () { * yield * [0, 1, 2, 3, 4] * } * * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item * * const arr = await all(filter(values, fn)) * * console.info(arr) // 3, 4 * ``` */ function isAsyncIterable$5(thing) { return thing[Symbol.asyncIterator] != null; } function filter(source, fn) { let index = 0; if (isAsyncIterable$5(source)) { return (async function* () { for await (const entry of source) { if (await fn(entry, index++)) { yield entry; } } })(); } // if mapping function returns a promise we have to return an async generator const peekable$1 = peekable(source); const { value, done } = peekable$1.next(); if (done === true) { return (function* () { }()); } const res = fn(value, index++); // @ts-expect-error .then is not present on O if (typeof res.then === 'function') { return (async function* () { if (await res) { yield value; } for await (const entry of peekable$1) { if (await fn(entry, index++)) { yield entry; } } })(); } const func = fn; return (function* () { if (res === true) { yield value; } for (const entry of peekable$1) { if (func(entry, index++)) { yield entry; } } })(); } /** * @packageDocumentation * * For when you need a one-liner to collect iterable values. * * @example * * ```javascript * import all from 'it-all' * * // This can also be an iterator, etc * const values = function * () { * yield * [0, 1, 2, 3, 4] * } * * const arr = all(values) * * console.info(arr) // 0, 1, 2, 3, 4 * ``` * * Async sources must be awaited: * * ```javascript * const values = async function * () { * yield * [0, 1, 2, 3, 4] * } * * const arr = await all(values()) * * console.info(arr) // 0, 1, 2, 3, 4 * ``` */ function isAsyncIterable$4(thing) { return thing[Symbol.asyncIterator] != null; } function all(source) { if (isAsyncIterable$4(source)) { return (async () => { const arr = []; for await (const entry of source) { arr.push(entry); } return arr; })(); } const arr = []; for (const entry of source) { arr.push(entry); } return arr; } /** * @packageDocumentation * * Consumes all values from an (async)iterable and returns them sorted by the passed sort function. * * @example * * ```javascript * import sort from 'it-sort' * import all from 'it-all' * * const sorter = (a, b) => { * return a.localeCompare(b) * } * * // This can also be an iterator, generator, etc * const values = ['foo', 'bar'] * * const arr = all(sort(values, sorter)) * * console.info(arr) // 'bar', 'foo' * ``` * * Async sources must be awaited: * * ```javascript * import sort from 'it-sort' * import all from 'it-all' * * const sorter = (a, b) => { * return a.localeCompare(b) * } * * const values = async function * () { * yield * ['foo', 'bar'] * } * * const arr = await all(sort(values, sorter)) * * console.info(arr) // 'bar', 'foo' * ``` */ function isAsyncIterable$3(thing) { return thing[Symbol.asyncIterator] != null; } function sort(source, sorter) { if (isAsyncIterable$3(source)) { return (async function* () { const arr = await all(source); yield* arr.sort(sorter); })(); } return (function* () { const arr = all(source); yield* arr.sort(sorter); })(); } /** * @packageDocumentation * * For when you only want a few values out of an (async)iterable. * * @example * * ```javascript * import take from 'it-take' * import all from 'it-all' * * // This can also be an iterator, generator, etc * const values = [0, 1, 2, 3, 4] * * const arr = all(take(values, 2)) * * console.info(arr) // 0, 1 * ``` * * Async sources must be awaited: * * ```javascript * import take from 'it-take' * import all from 'it-all' * * const values = async function * () { * yield * [0, 1, 2, 3, 4] * } * * const arr = await all(take(values(), 2)) * * console.info(arr) // 0, 1 * ``` */ function isAsyncIterable$2(thing) { return thing[Symbol.asyncIterator] != null; } function take(source, limit) { if (isAsyncIterable$2(source)) { return (async function* () { let items = 0; if (limit < 1) { return; } for await (const entry of source) { yield entry; items++; if (items === limit) { return; } } })(); } return (function* () { let items = 0; if (limit < 1) { return; } for (const entry of source) { yield entry; items++; if (items === limit) { return; } } })(); } class BaseDatastore { put(key, val, options) { return Promise.reject(new Error('.put is not implemented')); } get(key, options) { return Promise.reject(new Error('.get is not implemented')); } has(key, options) { return Promise.reject(new Error('.has is not implemented')); } delete(key, options) { return Promise.reject(new Error('.delete is not implemented')); } async *putMany(source, options = {}) { for await (const { key, value } of source) { await this.put(key, value, options); yield key; } } async *getMany(source, options = {}) { for await (const key of source) { yield { key, value: await this.get(key, options) }; } } async *deleteMany(source, options = {}) { for await (const key of source) { await this.delete(key, options); yield key; } } batch() { let puts = []; let dels = []; return { put(key, value) { puts.push({ key, value }); }, delete(key) { dels.push(key); }, commit: async (options) => { await drain(this.putMany(puts, options)); puts = []; await drain(this.deleteMany(dels, options)); dels = []; } }; } /** * Extending classes should override `query` or implement this method */ // eslint-disable-next-line require-yield async *_all(q, options) { throw new Error('._all is not implemented'); } /** * Extending classes should override `queryKeys` or implement this method */ // eslint-disable-next-line require-yield async *_allKeys(q, options) { throw new Error('._allKeys is not implemented'); } query(q, options) { let it = this._all(q, options); if (q.prefix != null) { const prefix = q.prefix; it = filter(it, (e) => e.key.toString().startsWith(prefix)); } if (Array.isArray(q.filters)) { it = q.filters.reduce((it, f) => filter(it, f), it); } if (Array.isArray(q.orders)) { it = q.orders.reduce((it, f) => sort(it, f), it); } if (q.offset != null) { let i = 0; const offset = q.offset; it = filter(it, () => i++ >= offset); } if (q.limit != null) { it = take(it, q.limit); } return it; } queryKeys(q, options) { let it = this._allKeys(q, options); if (q.prefix != null) { const prefix = q.prefix; it = filter(it, (key) => key.toString().startsWith(prefix)); } if (Array.isArray(q.filters)) { it = q.filters.reduce((it, f) => filter(it, f), it); } if (Array.isArray(q.orders)) { it = q.orders.reduce((it, f) => sort(it, f), it); } if (q.offset != null) { const offset = q.offset; let i = 0; it = filter(it, () => i++ >= offset); } if (q.limit != null) { it = take(it, q.limit); } return it; } } class OpenFailedError extends Error { static name = 'OpenFailedError'; static code = 'ERR_OPEN_FAILED'; name = OpenFailedError.name; code = OpenFailedError.code; constructor(message = 'Open failed') { super(message); } } class PutFailedError extends Error { static name = 'PutFailedError'; static code = 'ERR_PUT_FAILED'; name = PutFailedError.name; code = PutFailedError.code; constructor(message = 'Put failed') { super(message); } } class DeleteFailedError extends Error { static name = 'DeleteFailedError'; static code = 'ERR_DELETE_FAILED'; name = DeleteFailedError.name; code = DeleteFailedError.code; constructor(message = 'Delete failed') { super(message); } } class NotFoundError extends Error { static name = 'NotFoundError'; static code = 'ERR_NOT_FOUND'; name = NotFoundError.name; code = NotFoundError.code; constructor(message = 'Not Found') { super(message); } } /** * @packageDocumentation * * Convert one value from an (async)iterator into another. * * @example * * ```javascript * import map from 'it-map' * * // This can also be an iterator, generator, etc * const values = [0, 1, 2, 3, 4] * * const result = map(values, (val, index) => val++) * * console.info(result) // [1, 2, 3, 4, 5] * ``` * * Async sources and transforms must be awaited: * * ```javascript * import map from 'it-map' * * const values = async function * () { * yield * [0, 1, 2, 3, 4] * } * * const result = await map(values(), async (val, index) => val++) * * console.info(result) // [1, 2, 3, 4, 5] * ``` */ function isAsyncIterable$1(thing) { return thing[Symbol.asyncIterator] != null; } function map$1(source, func) { let index = 0; if (isAsyncIterable$1(source)) { return (async function* () { for await (const val of source) { yield func(val, index++); } })(); } // if mapping function returns a promise we have to return an async generator const peekable$1 = peekable(source); const { value, done } = peekable$1.next(); if (done === true) { return (function* () { }()); } const res = func(value, index++); // @ts-expect-error .then is not present on O if (typeof res.then === 'function') { return (async function* () { yield await res; for await (const val of peekable$1) { yield func(val, index++); } })(); } const fn = func; return (function* () { yield res; for (const val of peekable$1) { yield fn(val, index++); } })(); } new Key(SHARDING_FN); // Helpers. const s$X = 1000; const m$V = s$X * 60; const h$10 = m$V * 60; const d$12 = h$10 * 24; const w$R = d$12 * 7; const y$10 = d$12 * 365.25; function ms(value, options) { try { if (typeof value === 'string' && value.length > 0) { return parse$6(value); } else if (typeof value === 'number' && isFinite(value)) { return options?.long ? fmtLong(value) : fmtShort(value); } throw new Error('Value is not a string or number.'); } catch (error) { const message = isError(error) ? `${error.message}. value=${JSON.stringify(value)}` : 'An unknown error has occured.'; throw new Error(message); } } /** * Parse the given `str` and return milliseconds. */ function parse$6(str) { str = String(str); if (str.length > 100) { throw new Error('Value exceeds the maximum length of 100 characters.'); } const 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 NaN; } const n = parseFloat(match[1]); const type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y$10; case 'weeks': case 'week': case 'w': return n * w$R; case 'days': case 'day': case 'd': return n * d$12; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h$10; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m$V; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s$X; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: // This should never occur. throw new Error(`The unit ${type} was matched, but no matching case exists.`); } } /** * Short format for `ms`. */ function fmtShort(ms) { const msAbs = Math.abs(ms); if (msAbs >= d$12) { return `${Math.round(ms / d$12)}d`; } if (msAbs >= h$10) { return `${Math.round(ms / h$10)}h`; } if (msAbs >= m$V) { return `${Math.round(ms / m$V)}m`; } if (msAbs >= s$X) { return `${Math.round(ms / s$X)}s`; } return `${ms}ms`; } /** * Long format for `ms`. */ function fmtLong(ms) { const msAbs = Math.abs(ms); if (msAbs >= d$12) { return plural(ms, msAbs, d$12, 'day'); } if (msAbs >= h$10) { return plural(ms, msAbs, h$10, 'hour'); } if (msAbs >= m$V) { return plural(ms, msAbs, m$V, 'minute'); } if (msAbs >= s$X) { return plural(ms, msAbs, s$X, 'second'); } return `${ms} ms`; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { const isPlural = msAbs >= n * 1.5; return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`; } /** * A type guard for errors. */ function isError(error) { return typeof error === 'object' && error !== null && 'message' in error; } /* eslint-env browser */ const level = (() => { if (/\b(Chrome|Chromium)\//.test(undefined)) { return 1; } return 0; })(); const colorSupport = level !== 0 && { level, hasBasic: true, has256: level >= 2, has16m: level >= 3, }; const supportsColor = { stdout: colorSupport, stderr: colorSupport, }; /* eslint-disable no-console */ /* eslint-disable @typescript-eslint/strict-boolean-expressions */ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = ms; createDebug.destroy = destroy; Object.keys(env).forEach(key => { // @ts-expect-error cannot use string to index type createDebug[key] = env[key]; }); /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * * @param {string} namespace - The namespace string for the debug instance to be colored * @returns {number | string} An ANSI color code for the given namespace */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } // @ts-expect-error colors is not in the types return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {string} namespace * @returns {Function} */ function createDebug(namespace) { let prevTime; let enableOverride = null; let namespacesCache; let enabledCache; function debug(...args) { // Disabled? // @ts-expect-error enabled is not in the types if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return '%'; } index++; // @ts-expect-error formatters is not in the types const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) // @ts-expect-error formatArgs is not in the types createDebug.formatArgs.call(self, args); // @ts-expect-error log is not in the types const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; // @ts-expect-error useColors is not in the types debug.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => { if (enableOverride !== null) { return enableOverride; } // @ts-expect-error namespaces is not in the types if (namespacesCache !== createDebug.namespaces) { // @ts-expect-error namespaces is not in the types namespacesCache = createDebug.namespaces; enabledCache = createDebug.enabled(namespace); } return enabledCache; }, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances // @ts-expect-error init is not in the types if (typeof createDebug.init === 'function') { // @ts-expect-error init is not in the types createDebug.init(debug); } // @ts-expect-error some properties are added dynamically return debug; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {string} namespaces */ function enable(namespaces) { // @ts-expect-error save is not in the types createDebug.save(namespaces); // @ts-expect-error namespaces is not in the types createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @returns {string} namespaces */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {string} name * @returns {boolean} */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) { return val.stack ?? val.message; } return val; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } // @ts-expect-error setupFormatters is not in the types createDebug.setupFormatters(createDebug.formatters); // @ts-expect-error load is not in the types createDebug.enable(createDebug.load()); // @ts-expect-error some properties are added dynamically return createDebug; } /** * @packageDocumentation * * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM. * * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application. * * ESM should be arriving in `debug@5.x.x` so this module can be retired after that. * * Please see [debug](https://www.npmjs.com/package/debug) for API details. */ /** * Module dependencies. */ /** * This is the Node.js implementation of `debug()`. */ /** * Colors. */ let colors = [6, 2, 3, 4, 5, 1]; if (supportsColor.stderr !== false && (supportsColor.stderr ?? supportsColor).level >= 2) { colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ const inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in inspectOpts ? Boolean(inspectOpts.colors) : tty.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. */ function formatArgs(args) { const { namespace: name, useColors } = this; if (useColors === true) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + ms(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (inspectOpts.hideDate != null) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util$5.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {string} namespaces */ function save(namespaces) { if (namespaces != null) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @returns {string} returns the previously persisted debug modes */ function load$1() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = inspectOpts[keys[i]]; } } function setupFormatters(formatters) { /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util$5.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util$5.inspect(v, this.inspectOpts); }; } var weald = setup({ init, log, formatArgs, save, load: load$1, useColors, setupFormatters, colors, inspectOpts }); /** * @packageDocumentation * * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module. * * @example * * ```TypeScript * import { logger } from '@libp2p/logger' * * const log = logger('libp2p:my:component:name') * * try { * // an operation * log('something happened: %s', 'it was ok') * } catch (err) { * log.error('something bad happened: %o', err) * } * * log('with this peer: %p', {}) * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3])) * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7])) * ``` * * ```console * $ DEBUG=libp2p:* node index.js * something happened: it was ok * something bad happened: * with this peer: 12D3Foo * with this base58btc: Qmfoo * with this base32: bafyfoo * ``` */ // Add a formatter for converting to a base58 string weald.formatters.b = (v) => { return v == null ? 'undefined' : base58btc.baseEncode(v); }; // Add a formatter for converting to a base32 string weald.formatters.t = (v) => { return v == null ? 'undefined' : base32.baseEncode(v); }; // Add a formatter for converting to a base64 string weald.formatters.m = (v) => { return v == null ? 'undefined' : base64.baseEncode(v); }; // Add a formatter for stringifying peer ids weald.formatters.p = (v) => { return v == null ? 'undefined' : v.toString(); }; // Add a formatter for stringifying CIDs weald.formatters.c = (v) => { return v == null ? 'undefined' : v.toString(); }; // Add a formatter for stringifying Datastore keys weald.formatters.k = (v) => { return v == null ? 'undefined' : v.toString(); }; // Add a formatter for stringifying Multiaddrs weald.formatters.a = (v) => { return v == null ? 'undefined' : v.toString(); }; // Add a formatter for stringifying Errors weald.formatters.e = (v) => { return v == null ? 'undefined' : notEmpty(v.stack) ?? notEmpty(v.message) ?? v.toString(); }; function createDisabledLogger(namespace) { const logger = () => { }; logger.enabled = false; logger.color = ''; logger.diff = 0; logger.log = () => { }; logger.namespace = namespace; logger.destroy = () => true; logger.extend = () => logger; return logger; } /** * Creates a logger for the passed component name. * * @example * * ```TypeScript * import { logger } from '@libp2p/logger' * * const log = logger('my-component') * log.info('hello world') * // logs "my-component hello world" * ``` */ function logger(name) { // trace logging is a no-op by default let trace = createDisabledLogger(`${name}:trace`); // look at all the debug names and see if trace logging has explicitly been enabled if (weald.enabled(`${name}:trace`) && weald.names.map((r) => r.toString()).find((n) => n.includes(':trace')) != null) { trace = weald(`${name}:trace`); } return Object.assign(weald(name), { error: weald(`${name}:error`), trace }); } function notEmpty(str) { if (str == null) { return; } str = str.trim(); if (str.length === 0) { return; } return str; } logger('datastore:core:tiered'); var tasks = {}; var utils$q = {}; var array$1 = {}; Object.defineProperty(array$1, "__esModule", { value: true }); array$1.splitWhen = array$1.flatten = void 0; function flatten$1(items) { return items.reduce((collection, item) => [].concat(collection, item), []); } array$1.flatten = flatten$1; function splitWhen(items, predicate) { const result = [[]]; let groupIndex = 0; for (const item of items) { if (predicate(item)) { groupIndex++; result[groupIndex] = []; } else { result[groupIndex].push(item); } } return result; } array$1.splitWhen = splitWhen; var errno$1 = {}; Object.defineProperty(errno$1, "__esModule", { value: true }); errno$1.isEnoentCodeError = void 0; function isEnoentCodeError(error) { return error.code === 'ENOENT'; } errno$1.isEnoentCodeError = isEnoentCodeError; var fs$b = {}; Object.defineProperty(fs$b, "__esModule", { value: true }); fs$b.createDirentFromStats = void 0; let DirentFromStats$1 = class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } }; function createDirentFromStats$1(name, stats) { return new DirentFromStats$1(name, stats); } fs$b.createDirentFromStats = createDirentFromStats$1; var path$g = {}; Object.defineProperty(path$g, "__esModule", { value: true }); path$g.convertPosixPathToPattern = path$g.convertWindowsPathToPattern = path$g.convertPathToPattern = path$g.escapePosixPath = path$g.escapeWindowsPath = path$g.escape = path$g.removeLeadingDotSegment = path$g.makeAbsolute = path$g.unixify = void 0; const os$2 = require$$1; const path$f = require$$0$3; const IS_WINDOWS_PLATFORM = os$2.platform() === 'win32'; const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ /** * All non-escaped special characters. * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. * Windows: (){}[], !+@ before (, ! at the beginning. */ const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; /** * The device path (\\.\ or \\?\). * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths */ const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; /** * All backslashes except those escaping special characters. * Windows: !()+@{} * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions */ const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; /** * Designed to work only with simple paths: `dir\\file`. */ function unixify(filepath) { return filepath.replace(/\\/g, '/'); } path$g.unixify = unixify; function makeAbsolute(cwd, filepath) { return path$f.resolve(cwd, filepath); } path$g.makeAbsolute = makeAbsolute; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with if (entry.charAt(0) === '.') { const secondCharactery = entry.charAt(1); if (secondCharactery === '/' || secondCharactery === '\\') { return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } } return entry; } path$g.removeLeadingDotSegment = removeLeadingDotSegment; path$g.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; function escapeWindowsPath(pattern) { return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$g.escapeWindowsPath = escapeWindowsPath; function escapePosixPath(pattern) { return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } path$g.escapePosixPath = escapePosixPath; path$g.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; function convertWindowsPathToPattern(filepath) { return escapeWindowsPath(filepath) .replace(DOS_DEVICE_PATH_RE, '//$1') .replace(WINDOWS_BACKSLASHES_RE, '/'); } path$g.convertWindowsPathToPattern = convertWindowsPathToPattern; function convertPosixPathToPattern(filepath) { return escapePosixPath(filepath); } path$g.convertPosixPathToPattern = convertPosixPathToPattern; var pattern$1 = {}; /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ var isExtglob$1 = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isExtglob = isExtglob$1; var chars = { '{': '}', '(': ')', '[': ']'}; var strictCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; var pipeIndex = -2; var closeSquareIndex = -2; var closeCurlyIndex = -2; var closeParenIndex = -2; var backSlashIndex = -2; while (index < str.length) { if (str[index] === '*') { return true; } if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { return true; } if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { if (closeSquareIndex < index) { closeSquareIndex = str.indexOf(']', index); } if (closeSquareIndex > index) { if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } } } if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { closeCurlyIndex = str.indexOf('}', index); if (closeCurlyIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { return true; } } } if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { closeParenIndex = str.indexOf(')', index); if (closeParenIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { if (pipeIndex < index) { pipeIndex = str.indexOf('|', index); } if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { closeParenIndex = str.indexOf(')', pipeIndex); if (closeParenIndex > pipeIndex) { backSlashIndex = str.indexOf('\\', pipeIndex); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var relaxedCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; while (index < str.length) { if (/[*?{}()[\]]/.test(str[index])) { return true; } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var isGlob$1 = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var check = strictCheck; // optionally relax check if (options && options.strict === false) { check = relaxedCheck; } return check(str); }; var isGlob = isGlob$1; var pathPosixDirname = require$$0$3.posix.dirname; var isWin32 = require$$1.platform() === 'win32'; var slash = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] * @returns {string} */ var globParent$1 = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob(str) || globby.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; var utils$p = {}; (function (exports) { exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { const node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { const ele = arr[i]; if (Array.isArray(ele)) { flat(ele); continue; } if (ele !== undefined) { result.push(ele); } } return result; }; flat(args); return result; }; } (utils$p)); const utils$o = utils$p; var stringify$7 = (ast, options = {}) => { const stringify = (node, parent = {}) => { const invalidBlock = options.escapeInvalid && utils$o.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils$o.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (const child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ var isNumber$2 = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; /*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber$1 = isNumber$2; const toRegexRange$1 = (min, max, options) => { if (isNumber$1(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber$1(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { return toRegexRange$1.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange$1.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false) || []; let onlyPositive = filterPatterns(pos, neg, '', false) || []; let intersected = filterPatterns(neg, pos, '-?', true) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange$1.cache = {}; toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); /** * Expose `toRegexRange` */ var toRegexRange_1 = toRegexRange$1; /*! * fill-range * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. */ const util$4 = require$$0$4; const toRegexRange = toRegexRange_1; const isObject$5 = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform$1 = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify$6 = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options, maxLen) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util$4.inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify$6(start, end, options) === false; let format = options.transform || transform$1(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill$2 = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill$2(start, end, 1, { transform: step }); } if (isObject$5(step)) { return fill$2(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber(step)) { if (step != null && !isObject$5(step)) return invalidStep(step, opts); return fill$2(start, end, 1, step); } if (isNumber(start) && isNumber(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; var fillRange = fill$2; const fill$1 = fillRange; const utils$n = utils$p; const compile$1 = (ast, options = {}) => { const walk = (node, parent = {}) => { const invalidBlock = utils$n.isInvalidBrace(parent); const invalidNode = node.invalid === true && options.escapeInvalid === true; const invalid = invalidBlock === true || invalidNode === true; const prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { console.log('node.isClose', prefix, node.value); return prefix + node.value; } if (node.type === 'open') { return invalid ? prefix + node.value : '('; } if (node.type === 'close') { return invalid ? prefix + node.value : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { const args = utils$n.reduce(node.nodes); const range = fill$1(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (const child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; var compile_1 = compile$1; const fill = fillRange; const stringify$5 = stringify$7; const utils$m = utils$p; const append = (queue = '', stash = '', enclose = false) => { const result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils$m.flatten(stash).map(ele => `{${ele}}`) : stash; } for (const item of queue) { if (Array.isArray(item)) { for (const value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } } } return utils$m.flatten(result); }; const expand$1 = (ast, options = {}) => { const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; const walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify$5(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { const args = utils$m.reduce(node.nodes); if (utils$m.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify$5(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } const enclose = utils$m.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { const child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils$m.flatten(walk(ast)); }; var expand_1 = expand$1; var constants$4 = { MAX_LENGTH: 10000, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; const stringify$4 = stringify$7; /** * Constants */ const { MAX_LENGTH: MAX_LENGTH$1, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants$4; /** * parse */ const parse$5 = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } const opts = options || {}; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } const ast = { type: 'root', input, nodes: [] }; const stack = [ast]; let block = ast; let prev = ast; let brackets = 0; const length = input.length; let index = 0; let depth = 0; let value; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET$1) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET$1) { brackets++; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET$1) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES$1) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES$1) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { const open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE$1) { depth++; const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; const brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE$1) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } const type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA$1 && depth > 0) { if (block.ranges > 0) { block.ranges = 0; const open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify$4(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT$1 && depth > 0 && block.commas === 0) { const siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); const before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) const parent = stack[stack.length - 1]; const index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; var parse_1$1 = parse$5; const stringify$3 = stringify$7; const compile = compile_1; const expand = expand_1; const parse$4 = parse_1$1; /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces$1 = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (const pattern of input) { const result = braces$1.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces$1.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces$1.parse = (input, options = {}) => parse$4(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify$3(braces$1.parse(input, options), options); } return stringify$3(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces$1.parse(input, options); } return compile(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces$1.parse(input, options); } let result = expand(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces$1.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces$1.compile(input, options) : braces$1.expand(input, options); }; /** * Expose "braces" */ var braces_1 = braces$1; var utils$l = {}; const path$e = require$$0$3; const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; /** * Posix glob regex */ const DOT_LITERAL = '\\.'; const PLUS_LITERAL = '\\+'; const QMARK_LITERAL = '\\?'; const SLASH_LITERAL = '\\/'; const ONE_CHAR = '(?=.)'; const QMARK = '[^/]'; const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; const NO_DOT = `(?!${DOT_LITERAL})`; const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; const STAR = `${QMARK}*?`; const POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR, START_ANCHOR }; /** * Windows glob regex */ const WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE$1 = { alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', blank: ' \\t', cntrl: '\\x00-\\x1F\\x7F', digit: '0-9', graph: '\\x21-\\x7E', lower: 'a-z', print: '\\x20-\\x7E ', punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', space: ' \\t\\r\\n\\v\\f', upper: 'A-Z', word: 'A-Za-z0-9_', xdigit: 'A-Fa-f0-9' }; var constants$3 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path$e.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; (function (exports) { const path = require$$0$3; const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$3; exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; } (utils$l)); const utils$k = utils$l; const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = constants$3; const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; const depth = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan$1 = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils$k.removeBackslashes(glob); if (base && backslashes === true) { base = utils$k.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1 = scan$1; const constants$2 = constants$3; const utils$j = utils$l; /** * Constants */ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$2; /** * Helpers */ const expandRange = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; try { /* eslint-disable-next-line no-new */ new RegExp(value); } catch (ex) { return args.map(v => utils$j.escapeRegex(v)).join('..'); } return value; }; /** * Create the message for a syntax error */ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse$3 = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils$j.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants$2.globChars(win32); const EXTGLOB_CHARS = constants$2.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils$j.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. // In this case, we need to parse the string and use it in the output of the original pattern. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. // // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. const expression = parse$3(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils$j.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils$j.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils$j.hasRegexChars(prevValue)) { continue; } const escaped = utils$j.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils$j.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); state.output = utils$j.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils$j.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils$j.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse$3.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils$j.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$2.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils$j.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; var parse_1 = parse$3; const path$d = require$$0$3; const scan = scan_1; const parse$2 = parse_1; const utils$i = utils$l; const constants$1 = constants$3; const isObject$4 = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch$2 = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch$2(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject$4(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils$i.isWindows(options); const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch$2.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch$2.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils$i.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch$2.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch$2.matchBase = (input, glob, options, posix = utils$i.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options); return regex.test(path$d.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String|Array} str The string to test. * @param {String|Array} patterns One or more glob patterns to use for matching. * @param {Object} [options] See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch$2.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch$2.parse(p, options)); return parse$2(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch$2.scan = (input, options) => scan(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch$2.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse$2.fastpaths(input, options); } if (!parsed.output) { parsed = parse$2(input, options); } return picomatch$2.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch$2.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch$2.constants = constants$1; /** * Expose "picomatch" */ var picomatch_1 = picomatch$2; var picomatch$1 = picomatch_1; const util$3 = require$$0$4; const braces = braces_1; const picomatch = picomatch$1; const utils$h = utils$l; const isEmptyString = v => v === '' || v === './'; const hasBraces = v => { const index = v.indexOf('{'); return index > -1 && v.indexOf('}', index) > -1; }; /** * Returns an array of strings that match one or more glob patterns. * * ```js * const mm = require('micromatch'); * // mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {String|Array} `list` List of strings to match. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) * @return {Array} Returns an array of matches * @summary false * @api public */ const micromatch$1 = (list, patterns, options) => { patterns = [].concat(patterns); list = [].concat(list); let omit = new Set(); let keep = new Set(); let items = new Set(); let negatives = 0; let onResult = state => { items.add(state.output); if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); let match = negated ? !matched.isMatch : matched.isMatch; if (!match) continue; if (negated) { omit.add(matched.output); } else { omit.delete(matched.output); keep.add(matched.output); } } } let result = negatives === patterns.length ? [...items] : [...keep]; let matches = result.filter(item => !omit.has(item)); if (options && matches.length === 0) { if (options.failglob === true) { throw new Error(`No matches found for "${patterns.join(', ')}"`); } if (options.nonull === true || options.nullglob === true) { return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; } } return matches; }; /** * Backwards compatibility */ micromatch$1.match = micromatch$1; /** * Returns a matcher function from the given glob `pattern` and `options`. * The returned function takes a string to match as its only argument and returns * true if the string is a match. * * ```js * const mm = require('micromatch'); * // mm.matcher(pattern[, options]); * * const isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @param {String} `pattern` Glob pattern * @param {Object} `options` * @return {Function} Returns a matcher function. * @api public */ micromatch$1.matcher = (pattern, options) => picomatch(pattern, options); /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const mm = require('micromatch'); * // mm.isMatch(string, patterns[, options]); * * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(mm.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `[options]` See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch$1.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Backwards compatibility */ micromatch$1.any = micromatch$1.isMatch; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js * const mm = require('micromatch'); * // mm.not(list, patterns[, options]); * * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. * @param {String|Array} `patterns` One or more glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array} Returns an array of strings that **do not match** the given patterns. * @api public */ micromatch$1.not = (list, patterns, options = {}) => { patterns = [].concat(patterns).map(String); let result = new Set(); let items = []; let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; let matches = new Set(micromatch$1(list, patterns, { ...options, onResult })); for (let item of items) { if (!matches.has(item)) { result.add(item); } } return [...result]; }; /** * Returns true if the given `string` contains the given pattern. Similar * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js * var mm = require('micromatch'); * // mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. * @param {String|Array} `patterns` Glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any of the patterns matches any part of `str`. * @api public */ micromatch$1.contains = (str, pattern, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$3.inspect(str)}"`); } if (Array.isArray(pattern)) { return pattern.some(p => micromatch$1.contains(str, p, options)); } if (typeof pattern === 'string') { if (isEmptyString(str) || isEmptyString(pattern)) { return false; } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); }; /** * Filter the keys of the given object with the given `glob` pattern * and `options`. Does not attempt to match nested keys. If you need this feature, * use [glob-object][] instead. * * ```js * const mm = require('micromatch'); * // mm.matchKeys(object, patterns[, options]); * * const obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Object} Returns an object with only keys that match the given patterns. * @api public */ micromatch$1.matchKeys = (obj, patterns, options) => { if (!utils$h.isObject(obj)) { throw new TypeError('Expected the first argument to be an object'); } let keys = micromatch$1(Object.keys(obj), patterns, options); let res = {}; for (let key of keys) res[key] = obj[key]; return res; }; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` * @api public */ micromatch$1.some = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (items.some(item => isMatch(item))) { return true; } } return false; }; /** * Returns true if every string in the given `list` matches * any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` * @api public */ micromatch$1.every = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (!items.every(item => isMatch(item))) { return false; } } return true; }; /** * Returns true if **all** of the given `patterns` match * the specified string. * * ```js * const mm = require('micromatch'); * // mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @param {String|Array} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch$1.all = (str, patterns, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util$3.inspect(str)}"`); } return [].concat(patterns).every(p => picomatch(p, options)(str)); }; /** * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. * * ```js * const mm = require('micromatch'); * // mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `glob` Glob pattern to use for matching. * @param {String} `input` String to match * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch$1.capture = (glob, input, options) => { let posix = utils$h.isWindows(options); let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); let match = regex.exec(posix ? utils$h.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; /** * Create a regular expression from the given glob `pattern`. * * ```js * const mm = require('micromatch'); * // mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ micromatch$1.makeRe = (...args) => picomatch.makeRe(...args); /** * Scan a glob pattern to separate the pattern into segments. Used * by the [split](#split) method. * * ```js * const mm = require('micromatch'); * const state = mm.scan(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with * @api public */ micromatch$1.scan = (...args) => picomatch.scan(...args); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const mm = require('micromatch'); * const state = mm.parse(pattern[, options]); * ``` * @param {String} `glob` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as regex source string. * @api public */ micromatch$1.parse = (patterns, options) => { let res = []; for (let pattern of [].concat(patterns || [])) { for (let str of braces(String(pattern), options)) { res.push(picomatch.parse(str, options)); } } return res; }; /** * Process the given brace `pattern`. * * ```js * const { braces } = require('micromatch'); * console.log(braces('foo/{a,b,c}/bar')); * //=> [ 'foo/(a|b|c)/bar' ] * * console.log(braces('foo/{a,b,c}/bar', { expand: true })); * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] * ``` * @param {String} `pattern` String with brace pattern to process. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. * @return {Array} * @api public */ micromatch$1.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); if ((options && options.nobrace === true) || !hasBraces(pattern)) { return [pattern]; } return braces(pattern, options); }; /** * Expand braces */ micromatch$1.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); return micromatch$1.braces(pattern, { ...options, expand: true }); }; /** * Expose micromatch */ // exposed for tests micromatch$1.hasBraces = hasBraces; var micromatch_1 = micromatch$1; Object.defineProperty(pattern$1, "__esModule", { value: true }); pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; const path$c = require$$0$3; const globParent = globParent$1; const micromatch = micromatch_1; const GLOBSTAR = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; /** * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. * The latter is due to the presence of the device path at the beginning of the UNC path. */ const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } pattern$1.isStaticPattern = isStaticPattern; function isDynamicPattern(pattern, options = {}) { /** * A special case with an empty string is necessary for matching patterns that start with a forward slash. * An empty string cannot be a dynamic pattern. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. */ if (pattern === '') { return false; } /** * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check * filepath directly (without read directory). */ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { return true; } if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { return true; } if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { return true; } if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { return true; } return false; } pattern$1.isDynamicPattern = isDynamicPattern; function hasBraceExpansion(pattern) { const openingBraceIndex = pattern.indexOf('{'); if (openingBraceIndex === -1) { return false; } const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); if (closingBraceIndex === -1) { return false; } const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); } function convertToPositivePattern(pattern) { return isNegativePattern(pattern) ? pattern.slice(1) : pattern; } pattern$1.convertToPositivePattern = convertToPositivePattern; function convertToNegativePattern(pattern) { return '!' + pattern; } pattern$1.convertToNegativePattern = convertToNegativePattern; function isNegativePattern(pattern) { return pattern.startsWith('!') && pattern[1] !== '('; } pattern$1.isNegativePattern = isNegativePattern; function isPositivePattern(pattern) { return !isNegativePattern(pattern); } pattern$1.isPositivePattern = isPositivePattern; function getNegativePatterns(patterns) { return patterns.filter(isNegativePattern); } pattern$1.getNegativePatterns = getNegativePatterns; function getPositivePatterns$1(patterns) { return patterns.filter(isPositivePattern); } pattern$1.getPositivePatterns = getPositivePatterns$1; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsInsideCurrentDirectory(patterns) { return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); } pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsOutsideCurrentDirectory(patterns) { return patterns.filter(isPatternRelatedToParentDirectory); } pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; function isPatternRelatedToParentDirectory(pattern) { return pattern.startsWith('..') || pattern.startsWith('./..'); } pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; function getBaseDirectory(pattern) { return globParent(pattern, { flipBackslashes: false }); } pattern$1.getBaseDirectory = getBaseDirectory; function hasGlobStar(pattern) { return pattern.includes(GLOBSTAR); } pattern$1.hasGlobStar = hasGlobStar; function endsWithSlashGlobStar(pattern) { return pattern.endsWith('/' + GLOBSTAR); } pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; function isAffectDepthOfReadingPattern(pattern) { const basename = path$c.basename(pattern); return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); } pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; function expandPatternsWithBraceExpansion(patterns) { return patterns.reduce((collection, pattern) => { return collection.concat(expandBraceExpansion(pattern)); }, []); } pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); /** * Sort the patterns by length so that the same depth patterns are processed side by side. * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` */ patterns.sort((a, b) => a.length - b.length); /** * Micromatch can return an empty string in the case of patterns like `{a,}`. */ return patterns.filter((pattern) => pattern !== ''); } pattern$1.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); /** * The scan method returns an empty array in some cases. * See micromatch/picomatch#58 for more details. */ if (parts.length === 0) { parts = [pattern]; } /** * The scan method does not return an empty part for the pattern with a forward slash. * This is another part of micromatch/picomatch#58. */ if (parts[0].startsWith('/')) { parts[0] = parts[0].slice(1); parts.unshift(''); } return parts; } pattern$1.getPatternParts = getPatternParts; function makeRe(pattern, options) { return micromatch.makeRe(pattern, options); } pattern$1.makeRe = makeRe; function convertPatternsToRe(patterns, options) { return patterns.map((pattern) => makeRe(pattern, options)); } pattern$1.convertPatternsToRe = convertPatternsToRe; function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } pattern$1.matchAny = matchAny; /** * This package only works with forward slashes as a path separator. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. */ function removeDuplicateSlashes(pattern) { return pattern.replace(DOUBLE_SLASH_RE, '/'); } pattern$1.removeDuplicateSlashes = removeDuplicateSlashes; var stream$5 = {}; /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = require$$0$5; const PassThrough = Stream.PassThrough; const slice = Array.prototype.slice; var merge2_1 = merge2$1; function merge2$1 () { const streamsQueue = []; const args = slice.call(arguments); let merging = false; let options = args[args.length - 1]; if (options && !Array.isArray(options) && options.pipe == null) { args.pop(); } else { options = {}; } const doEnd = options.end !== false; const doPipeError = options.pipeError === true; if (options.objectMode == null) { options.objectMode = true; } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024; } const mergedStream = PassThrough(options); function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)); } mergeStream(); return this } function mergeStream () { if (merging) { return } merging = true; let streams = streamsQueue.shift(); if (!streams) { process.nextTick(endStream); return } if (!Array.isArray(streams)) { streams = [streams]; } let pipesCount = streams.length + 1; function next () { if (--pipesCount > 0) { return } merging = false; mergeStream(); } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend); stream.removeListener('end', onend); if (doPipeError) { stream.removeListener('error', onerror); } next(); } function onerror (err) { mergedStream.emit('error', err); } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend); stream.on('end', onend); if (doPipeError) { stream.on('error', onerror); } stream.pipe(mergedStream, { end: false }); // compatible for old stream stream.resume(); } for (let i = 0; i < streams.length; i++) { pipe(streams[i]); } next(); } function endStream () { merging = false; // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain'); if (doEnd) { mergedStream.end(); } } mergedStream.setMaxListeners(0); mergedStream.add = addStream; mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd'); }); if (args.length) { addStream.apply(null, args); } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough(options)); } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause(); } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options); } } return streams } Object.defineProperty(stream$5, "__esModule", { value: true }); stream$5.merge = void 0; const merge2 = merge2_1; function merge$3(streams) { const mergedStream = merge2(streams); streams.forEach((stream) => { stream.once('error', (error) => mergedStream.emit('error', error)); }); mergedStream.once('close', () => propagateCloseEventToSources(streams)); mergedStream.once('end', () => propagateCloseEventToSources(streams)); return mergedStream; } stream$5.merge = merge$3; function propagateCloseEventToSources(streams) { streams.forEach((stream) => stream.emit('close')); } var string$2 = {}; Object.defineProperty(string$2, "__esModule", { value: true }); string$2.isEmpty = string$2.isString = void 0; function isString(input) { return typeof input === 'string'; } string$2.isString = isString; function isEmpty$1(input) { return input === ''; } string$2.isEmpty = isEmpty$1; Object.defineProperty(utils$q, "__esModule", { value: true }); utils$q.string = utils$q.stream = utils$q.pattern = utils$q.path = utils$q.fs = utils$q.errno = utils$q.array = void 0; const array = array$1; utils$q.array = array; const errno = errno$1; utils$q.errno = errno; const fs$a = fs$b; utils$q.fs = fs$a; const path$b = path$g; utils$q.path = path$b; const pattern = pattern$1; utils$q.pattern = pattern; const stream$4 = stream$5; utils$q.stream = stream$4; const string$1 = string$2; utils$q.string = string$1; Object.defineProperty(tasks, "__esModule", { value: true }); tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; const utils$g = utils$q; function generate(input, settings) { const patterns = processPatterns(input, settings); const ignore = processPatterns(settings.ignore, settings); const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); const staticPatterns = positivePatterns.filter((pattern) => utils$g.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils$g.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); } tasks.generate = generate; function processPatterns(input, settings) { let patterns = input; /** * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry * and some problems with the micromatch package (see fast-glob issues: #365, #394). * * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown * in matching in the case of a large set of patterns after expansion. */ if (settings.braceExpansion) { patterns = utils$g.pattern.expandPatternsWithBraceExpansion(patterns); } /** * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used * at any nesting level. * * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change * the pattern in the filter before creating a regular expression. There is no need to change the patterns * in the application. Only on the input. */ if (settings.baseNameMatch) { patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); } /** * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. */ return patterns.map((pattern) => utils$g.pattern.removeDuplicateSlashes(pattern)); } /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ function convertPatternsToTasks(positive, negative, dynamic) { const tasks = []; const patternsOutsideCurrentDirectory = utils$g.pattern.getPatternsOutsideCurrentDirectory(positive); const patternsInsideCurrentDirectory = utils$g.pattern.getPatternsInsideCurrentDirectory(positive); const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); /* * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. */ if ('.' in insideCurrentDirectoryGroup) { tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); } else { tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); } return tasks; } tasks.convertPatternsToTasks = convertPatternsToTasks; function getPositivePatterns(patterns) { return utils$g.pattern.getPositivePatterns(patterns); } tasks.getPositivePatterns = getPositivePatterns; function getNegativePatternsAsPositive(patterns, ignore) { const negative = utils$g.pattern.getNegativePatterns(patterns).concat(ignore); const positive = negative.map(utils$g.pattern.convertToPositivePattern); return positive; } tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; function groupPatternsByBaseDirectory(patterns) { const group = {}; return patterns.reduce((collection, pattern) => { const base = utils$g.pattern.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, group); } tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; function convertPatternGroupsToTasks(positive, negative, dynamic) { return Object.keys(positive).map((base) => { return convertPatternGroupToTask(base, positive[base], negative, dynamic); }); } tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; function convertPatternGroupToTask(base, positive, negative, dynamic) { return { dynamic, positive, negative, base, patterns: [].concat(positive, negative.map(utils$g.pattern.convertToNegativePattern)) }; } tasks.convertPatternGroupToTask = convertPatternGroupToTask; var async$8 = {}; var async$7 = {}; var out$3 = {}; var async$6 = {}; var async$5 = {}; var out$2 = {}; var async$4 = {}; var out$1 = {}; var async$3 = {}; Object.defineProperty(async$3, "__esModule", { value: true }); async$3.read = void 0; function read$4(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback$2(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback$2(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback$2(callback, statError); return; } callSuccessCallback$2(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback$2(callback, stat); }); }); } async$3.read = read$4; function callFailureCallback$2(callback, error) { callback(error); } function callSuccessCallback$2(callback, result) { callback(null, result); } var sync$8 = {}; Object.defineProperty(sync$8, "__esModule", { value: true }); sync$8.read = void 0; function read$3(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } sync$8.read = read$3; var settings$3 = {}; var fs$9 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0$6; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; } (fs$9)); Object.defineProperty(settings$3, "__esModule", { value: true }); const fs$8 = fs$9; let Settings$2 = class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs$8.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } }; settings$3.default = Settings$2; Object.defineProperty(out$1, "__esModule", { value: true }); out$1.statSync = out$1.stat = out$1.Settings = void 0; const async$2 = async$3; const sync$7 = sync$8; const settings_1$3 = settings$3; out$1.Settings = settings_1$3.default; function stat(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async$2.read(path, getSettings$2(), optionsOrSettingsOrCallback); return; } async$2.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); } out$1.stat = stat; function statSync(path, optionsOrSettings) { const settings = getSettings$2(optionsOrSettings); return sync$7.read(path, settings); } out$1.statSync = statSync; function getSettings$2(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$3.default) { return settingsOrOptions; } return new settings_1$3.default(settingsOrOptions); } /*! queue-microtask. MIT License. Feross Aboukhadijeh */ let promise; var queueMicrotask_1 = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) // reuse resolved promise, and allocate it lazily : cb => (promise || (promise = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)); /*! run-parallel. MIT License. Feross Aboukhadijeh */ var runParallel_1 = runParallel; const queueMicrotask$1 = queueMicrotask_1; function runParallel (tasks, cb) { let results, pending, keys; let isSync = true; if (Array.isArray(tasks)) { results = []; pending = tasks.length; } else { keys = Object.keys(tasks); results = {}; pending = keys.length; } function done (err) { function end () { if (cb) cb(err, results); cb = null; } if (isSync) queueMicrotask$1(end); else end(); } function each (i, err, result) { results[i] = result; if (--pending === 0 || err) { done(err); } } if (!pending) { // empty done(null); } else if (keys) { // object keys.forEach(function (key) { tasks[key](function (err, result) { each(key, err, result); }); }); } else { // array tasks.forEach(function (task, i) { task(function (err, result) { each(i, err, result); }); }); } isSync = false; } var constants = {}; Object.defineProperty(constants, "__esModule", { value: true }); constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ constants.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; var utils$f = {}; var fs$7 = {}; Object.defineProperty(fs$7, "__esModule", { value: true }); fs$7.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } fs$7.createDirentFromStats = createDirentFromStats; Object.defineProperty(utils$f, "__esModule", { value: true }); utils$f.fs = void 0; const fs$6 = fs$7; utils$f.fs = fs$6; var common$6 = {}; Object.defineProperty(common$6, "__esModule", { value: true }); common$6.joinPathSegments = void 0; function joinPathSegments$1(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$6.joinPathSegments = joinPathSegments$1; Object.defineProperty(async$4, "__esModule", { value: true }); async$4.readdir = async$4.readdirWithFileTypes = async$4.read = void 0; const fsStat$5 = out$1; const rpl = runParallel_1; const constants_1$1 = constants; const utils$e = utils$f; const common$5 = common$6; function read$2(directory, settings, callback) { if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes$1(directory, settings, callback); return; } readdir$1(directory, settings, callback); } async$4.read = read$2; function readdirWithFileTypes$1(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common$5.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback$1(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, rplEntries); }); }); } async$4.readdirWithFileTypes = readdirWithFileTypes$1; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils$e.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir$1(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback$1(callback, readdirError); return; } const tasks = names.map((name) => { const path = common$5.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils$e.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback$1(callback, rplError); return; } callSuccessCallback$1(callback, entries); }); }); } async$4.readdir = readdir$1; function callFailureCallback$1(callback, error) { callback(error); } function callSuccessCallback$1(callback, result) { callback(null, result); } var sync$6 = {}; Object.defineProperty(sync$6, "__esModule", { value: true }); sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0; const fsStat$4 = out$1; const constants_1 = constants; const utils$d = utils$f; const common$4 = common$6; function read$1(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir(directory, settings); } sync$6.read = read$1; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common$4.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils$d.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } sync$6.readdirWithFileTypes = readdirWithFileTypes; function readdir(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common$4.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils$d.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } sync$6.readdir = readdir; var settings$2 = {}; var fs$5 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0$6; exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; } (fs$5)); Object.defineProperty(settings$2, "__esModule", { value: true }); const path$a = require$$0$3; const fsStat$3 = out$1; const fs$4 = fs$5; let Settings$1 = class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs$4.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$a.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat$3.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } }; settings$2.default = Settings$1; Object.defineProperty(out$2, "__esModule", { value: true }); out$2.Settings = out$2.scandirSync = out$2.scandir = void 0; const async$1 = async$4; const sync$5 = sync$6; const settings_1$2 = settings$2; out$2.Settings = settings_1$2.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async$1.read(path, getSettings$1(), optionsOrSettingsOrCallback); return; } async$1.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); } out$2.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings$1(optionsOrSettings); return sync$5.read(path, settings); } out$2.scandirSync = scandirSync; function getSettings$1(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$2.default) { return settingsOrOptions; } return new settings_1$2.default(settingsOrOptions); } var queue$1 = {exports: {}}; function reusify$1 (Constructor) { var head = new Constructor(); var tail = head; function get () { var current = head; if (current.next) { head = current.next; } else { head = new Constructor(); tail = head; } current.next = null; return current } function release (obj) { tail.next = obj; tail = obj; } return { get: get, release: release } } var reusify_1 = reusify$1; /* eslint-disable no-var */ var reusify = reusify_1; function fastqueue (context, worker, _concurrency) { if (typeof context === 'function') { _concurrency = worker; worker = context; context = null; } if (!(_concurrency >= 1)) { throw new Error('fastqueue concurrency must be equal to or greater than 1') } var cache = reusify(Task); var queueHead = null; var queueTail = null; var _running = 0; var errorHandler = null; var self = { push: push, drain: noop, saturated: noop, pause: pause, paused: false, get concurrency () { return _concurrency }, set concurrency (value) { if (!(value >= 1)) { throw new Error('fastqueue concurrency must be equal to or greater than 1') } _concurrency = value; if (self.paused) return for (; queueHead && _running < _concurrency;) { _running++; release(); } }, running: running, resume: resume, idle: idle, length: length, getQueue: getQueue, unshift: unshift, empty: noop, kill: kill, killAndDrain: killAndDrain, error: error }; return self function running () { return _running } function pause () { self.paused = true; } function length () { var current = queueHead; var counter = 0; while (current) { current = current.next; counter++; } return counter } function getQueue () { var current = queueHead; var tasks = []; while (current) { tasks.push(current.value); current = current.next; } return tasks } function resume () { if (!self.paused) return self.paused = false; if (queueHead === null) { _running++; release(); return } for (; queueHead && _running < _concurrency;) { _running++; release(); } } function idle () { return _running === 0 && self.length() === 0 } function push (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop; current.errorHandler = errorHandler; if (_running >= _concurrency || self.paused) { if (queueTail) { queueTail.next = current; queueTail = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function unshift (value, done) { var current = cache.get(); current.context = context; current.release = release; current.value = value; current.callback = done || noop; current.errorHandler = errorHandler; if (_running >= _concurrency || self.paused) { if (queueHead) { current.next = queueHead; queueHead = current; } else { queueHead = current; queueTail = current; self.saturated(); } } else { _running++; worker.call(context, current.value, current.worked); } } function release (holder) { if (holder) { cache.release(holder); } var next = queueHead; if (next && _running <= _concurrency) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null; } queueHead = next.next; next.next = null; worker.call(context, next.value, next.worked); if (queueTail === null) { self.empty(); } } else { _running--; } } else if (--_running === 0) { self.drain(); } } function kill () { queueHead = null; queueTail = null; self.drain = noop; } function killAndDrain () { queueHead = null; queueTail = null; self.drain(); self.drain = noop; } function error (handler) { errorHandler = handler; } } function noop () {} function Task () { this.value = null; this.callback = noop; this.next = null; this.release = noop; this.context = null; this.errorHandler = null; var self = this; this.worked = function worked (err, result) { var callback = self.callback; var errorHandler = self.errorHandler; var val = self.value; self.value = null; self.callback = noop; if (self.errorHandler) { errorHandler(err, val); } callback.call(self.context, err, result); self.release(self); }; } function queueAsPromised (context, worker, _concurrency) { if (typeof context === 'function') { _concurrency = worker; worker = context; context = null; } function asyncWrapper (arg, cb) { worker.call(this, arg) .then(function (res) { cb(null, res); }, cb); } var queue = fastqueue(context, asyncWrapper, _concurrency); var pushCb = queue.push; var unshiftCb = queue.unshift; queue.push = push; queue.unshift = unshift; queue.drained = drained; return queue function push (value) { var p = new Promise(function (resolve, reject) { pushCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop); return p } function unshift (value) { var p = new Promise(function (resolve, reject) { unshiftCb(value, function (err, result) { if (err) { reject(err); return } resolve(result); }); }); // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop); return p } function drained () { if (queue.idle()) { return new Promise(function (resolve) { resolve(); }) } var previousDrain = queue.drain; var p = new Promise(function (resolve) { queue.drain = function () { previousDrain(); resolve(); }; }); return p } } queue$1.exports = fastqueue; queue$1.exports.promise = queueAsPromised; var queueExports = queue$1.exports; var common$3 = {}; Object.defineProperty(common$3, "__esModule", { value: true }); common$3.joinPathSegments = common$3.replacePathSegmentSeparator = common$3.isAppliedFilter = common$3.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } common$3.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } common$3.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } common$3.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } common$3.joinPathSegments = joinPathSegments; var reader$1 = {}; Object.defineProperty(reader$1, "__esModule", { value: true }); const common$2 = common$3; let Reader$1 = class Reader { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } }; reader$1.default = Reader$1; Object.defineProperty(async$5, "__esModule", { value: true }); const events_1 = require$$0$7; const fsScandir$2 = out$2; const fastq = queueExports; const common$1 = common$3; const reader_1$4 = reader$1; class AsyncReader extends reader_1$4.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir$2.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common$1.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common$1.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common$1.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common$1.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } async$5.default = AsyncReader; Object.defineProperty(async$6, "__esModule", { value: true }); const async_1$4 = async$5; class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$4.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } async$6.default = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } var stream$3 = {}; Object.defineProperty(stream$3, "__esModule", { value: true }); const stream_1$5 = require$$0$5; const async_1$3 = async$5; class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1$3.default(this._root, this._settings); this._stream = new stream_1$5.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } stream$3.default = StreamProvider; var sync$4 = {}; var sync$3 = {}; Object.defineProperty(sync$3, "__esModule", { value: true }); const fsScandir$1 = out$2; const common = common$3; const reader_1$3 = reader$1; class SyncReader extends reader_1$3.default { constructor() { super(...arguments); this._scandir = fsScandir$1.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } sync$3.default = SyncReader; Object.defineProperty(sync$4, "__esModule", { value: true }); const sync_1$3 = sync$3; class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1$3.default(this._root, this._settings); } read() { return this._reader.read(); } } sync$4.default = SyncProvider; var settings$1 = {}; Object.defineProperty(settings$1, "__esModule", { value: true }); const path$9 = require$$0$3; const fsScandir = out$2; class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$9.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } settings$1.default = Settings; Object.defineProperty(out$3, "__esModule", { value: true }); out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0; const async_1$2 = async$6; const stream_1$4 = stream$3; const sync_1$2 = sync$4; const settings_1$1 = settings$1; out$3.Settings = settings_1$1.default; function walk(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } out$3.walk = walk; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1$2.default(directory, settings); return provider.read(); } out$3.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1$4.default(directory, settings); return provider.read(); } out$3.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1$1.default) { return settingsOrOptions; } return new settings_1$1.default(settingsOrOptions); } var reader = {}; Object.defineProperty(reader, "__esModule", { value: true }); const path$8 = require$$0$3; const fsStat$2 = out$1; const utils$c = utils$q; class Reader { constructor(_settings) { this._settings = _settings; this._fsStatSettings = new fsStat$2.Settings({ followSymbolicLink: this._settings.followSymbolicLinks, fs: this._settings.fs, throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks }); } _getFullEntryPath(filepath) { return path$8.resolve(this._settings.cwd, filepath); } _makeEntry(stats, pattern) { const entry = { name: pattern, path: pattern, dirent: utils$c.fs.createDirentFromStats(pattern, stats) }; if (this._settings.stats) { entry.stats = stats; } return entry; } _isFatalError(error) { return !utils$c.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } reader.default = Reader; var stream$2 = {}; Object.defineProperty(stream$2, "__esModule", { value: true }); const stream_1$3 = require$$0$5; const fsStat$1 = out$1; const fsWalk$2 = out$3; const reader_1$2 = reader; class ReaderStream extends reader_1$2.default { constructor() { super(...arguments); this._walkStream = fsWalk$2.walkStream; this._stat = fsStat$1.stat; } dynamic(root, options) { return this._walkStream(root, options); } static(patterns, options) { const filepaths = patterns.map(this._getFullEntryPath, this); const stream = new stream_1$3.PassThrough({ objectMode: true }); stream._write = (index, _enc, done) => { return this._getEntry(filepaths[index], patterns[index], options) .then((entry) => { if (entry !== null && options.entryFilter(entry)) { stream.push(entry); } if (index === filepaths.length - 1) { stream.end(); } done(); }) .catch(done); }; for (let i = 0; i < filepaths.length; i++) { stream.write(i); } return stream; } _getEntry(filepath, pattern, options) { return this._getStat(filepath) .then((stats) => this._makeEntry(stats, pattern)) .catch((error) => { if (options.errorFilter(error)) { return null; } throw error; }); } _getStat(filepath) { return new Promise((resolve, reject) => { this._stat(filepath, this._fsStatSettings, (error, stats) => { return error === null ? resolve(stats) : reject(error); }); }); } } stream$2.default = ReaderStream; Object.defineProperty(async$7, "__esModule", { value: true }); const fsWalk$1 = out$3; const reader_1$1 = reader; const stream_1$2 = stream$2; class ReaderAsync extends reader_1$1.default { constructor() { super(...arguments); this._walkAsync = fsWalk$1.walk; this._readerStream = new stream_1$2.default(this._settings); } dynamic(root, options) { return new Promise((resolve, reject) => { this._walkAsync(root, options, (error, entries) => { if (error === null) { resolve(entries); } else { reject(error); } }); }); } async static(patterns, options) { const entries = []; const stream = this._readerStream.static(patterns, options); // After #235, replace it with an asynchronous iterator. return new Promise((resolve, reject) => { stream.once('error', reject); stream.on('data', (entry) => entries.push(entry)); stream.once('end', () => resolve(entries)); }); } } async$7.default = ReaderAsync; var provider = {}; var deep = {}; var partial = {}; var matcher = {}; Object.defineProperty(matcher, "__esModule", { value: true }); const utils$b = utils$q; class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; this._settings = _settings; this._micromatchOptions = _micromatchOptions; this._storage = []; this._fillStorage(); } _fillStorage() { for (const pattern of this._patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ complete: sections.length <= 1, pattern, segments, sections }); } } _getPatternSegments(pattern) { const parts = utils$b.pattern.getPatternParts(pattern, this._micromatchOptions); return parts.map((part) => { const dynamic = utils$b.pattern.isDynamicPattern(part, this._settings); if (!dynamic) { return { dynamic: false, pattern: part }; } return { dynamic: true, pattern: part, patternRe: utils$b.pattern.makeRe(part, this._micromatchOptions) }; }); } _splitSegmentsIntoSections(segments) { return utils$b.array.splitWhen(segments, (segment) => segment.dynamic && utils$b.pattern.hasGlobStar(segment.pattern)); } } matcher.default = Matcher; Object.defineProperty(partial, "__esModule", { value: true }); const matcher_1 = matcher; class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); const levels = parts.length; const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); for (const pattern of patterns) { const section = pattern.sections[0]; /** * In this case, the pattern has a globstar and we must read all directories unconditionally, * but only if the level has reached the end of the first group. * * fixtures/{a,b}/** * ^ true/false ^ always true */ if (!pattern.complete && levels > section.length) { return true; } const match = parts.every((part, index) => { const segment = pattern.segments[index]; if (segment.dynamic && segment.patternRe.test(part)) { return true; } if (!segment.dynamic && segment.pattern === part) { return true; } return false; }); if (match) { return true; } } return false; } } partial.default = PartialMatcher; Object.defineProperty(deep, "__esModule", { value: true }); const utils$a = utils$q; const partial_1 = partial; class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; } getFilter(basePath, positive, negative) { const matcher = this._getMatcher(positive); const negativeRe = this._getNegativePatternsRe(negative); return (entry) => this._filter(basePath, entry, matcher, negativeRe); } _getMatcher(patterns) { return new partial_1.default(patterns, this._settings, this._micromatchOptions); } _getNegativePatternsRe(patterns) { const affectDepthOfReadingPatterns = patterns.filter(utils$a.pattern.isAffectDepthOfReadingPattern); return utils$a.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } _filter(basePath, entry, matcher, negativeRe) { if (this._isSkippedByDeep(basePath, entry.path)) { return false; } if (this._isSkippedSymbolicLink(entry)) { return false; } const filepath = utils$a.path.removeLeadingDotSegment(entry.path); if (this._isSkippedByPositivePatterns(filepath, matcher)) { return false; } return this._isSkippedByNegativePatterns(filepath, negativeRe); } _isSkippedByDeep(basePath, entryPath) { /** * Avoid unnecessary depth calculations when it doesn't matter. */ if (this._settings.deep === Infinity) { return false; } return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } _getEntryLevel(basePath, entryPath) { const entryPathDepth = entryPath.split('/').length; if (basePath === '') { return entryPathDepth; } const basePathDepth = basePath.split('/').length; return entryPathDepth - basePathDepth; } _isSkippedSymbolicLink(entry) { return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } _isSkippedByPositivePatterns(entryPath, matcher) { return !this._settings.baseNameMatch && !matcher.match(entryPath); } _isSkippedByNegativePatterns(entryPath, patternsRe) { return !utils$a.pattern.matchAny(entryPath, patternsRe); } } deep.default = DeepFilter; var entry$1 = {}; Object.defineProperty(entry$1, "__esModule", { value: true }); const utils$9 = utils$q; class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; this.index = new Map(); } getFilter(positive, negative) { const positiveRe = utils$9.pattern.convertPatternsToRe(positive, this._micromatchOptions); const negativeRe = utils$9.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); return (entry) => this._filter(entry, positiveRe, negativeRe); } _filter(entry, positiveRe, negativeRe) { const filepath = utils$9.path.removeLeadingDotSegment(entry.path); if (this._settings.unique && this._isDuplicateEntry(filepath)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { return false; } const isDirectory = entry.dirent.isDirectory(); const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); if (this._settings.unique && isMatched) { this._createIndexRecord(filepath); } return isMatched; } _isDuplicateEntry(filepath) { return this.index.has(filepath); } _createIndexRecord(filepath) { this.index.set(filepath, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); } _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { if (!this._settings.absolute) { return false; } const fullpath = utils$9.path.makeAbsolute(this._settings.cwd, entryPath); return utils$9.pattern.matchAny(fullpath, patternsRe); } _isMatchToPatterns(filepath, patternsRe, isDirectory) { // Trying to match files and directories by patterns. const isMatched = utils$9.pattern.matchAny(filepath, patternsRe); // A pattern with a trailling slash can be used for directory matching. // To apply such pattern, we need to add a tralling slash to the path. if (!isMatched && isDirectory) { return utils$9.pattern.matchAny(filepath + '/', patternsRe); } return isMatched; } } entry$1.default = EntryFilter; var error$2 = {}; Object.defineProperty(error$2, "__esModule", { value: true }); const utils$8 = utils$q; class ErrorFilter { constructor(_settings) { this._settings = _settings; } getFilter() { return (error) => this._isNonFatalError(error); } _isNonFatalError(error) { return utils$8.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } error$2.default = ErrorFilter; var entry = {}; Object.defineProperty(entry, "__esModule", { value: true }); const utils$7 = utils$q; class EntryTransformer { constructor(_settings) { this._settings = _settings; } getTransformer() { return (entry) => this._transform(entry); } _transform(entry) { let filepath = entry.path; if (this._settings.absolute) { filepath = utils$7.path.makeAbsolute(this._settings.cwd, filepath); filepath = utils$7.path.unixify(filepath); } if (this._settings.markDirectories && entry.dirent.isDirectory()) { filepath += '/'; } if (!this._settings.objectMode) { return filepath; } return Object.assign(Object.assign({}, entry), { path: filepath }); } } entry.default = EntryTransformer; Object.defineProperty(provider, "__esModule", { value: true }); const path$7 = require$$0$3; const deep_1 = deep; const entry_1 = entry$1; const error_1$v = error$2; const entry_2 = entry; class Provider { constructor(_settings) { this._settings = _settings; this.errorFilter = new error_1$v.default(this._settings); this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); this.entryTransformer = new entry_2.default(this._settings); } _getRootDirectory(task) { return path$7.resolve(this._settings.cwd, task.base); } _getReaderOptions(task) { const basePath = task.base === '.' ? '' : task.base; return { basePath, pathSegmentSeparator: '/', concurrency: this._settings.concurrency, deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), entryFilter: this.entryFilter.getFilter(task.positive, task.negative), errorFilter: this.errorFilter.getFilter(), followSymbolicLinks: this._settings.followSymbolicLinks, fs: this._settings.fs, stats: this._settings.stats, throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, transform: this.entryTransformer.getTransformer() }; } _getMicromatchOptions() { return { dot: this._settings.dot, matchBase: this._settings.baseNameMatch, nobrace: !this._settings.braceExpansion, nocase: !this._settings.caseSensitiveMatch, noext: !this._settings.extglob, noglobstar: !this._settings.globstar, posix: true, strictSlashes: false }; } } provider.default = Provider; Object.defineProperty(async$8, "__esModule", { value: true }); const async_1$1 = async$7; const provider_1$2 = provider; class ProviderAsync extends provider_1$2.default { constructor() { super(...arguments); this._reader = new async_1$1.default(this._settings); } async read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = await this.api(root, task, options); return entries.map((entry) => options.transform(entry)); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } async$8.default = ProviderAsync; var stream$1 = {}; Object.defineProperty(stream$1, "__esModule", { value: true }); const stream_1$1 = require$$0$5; const stream_2 = stream$2; const provider_1$1 = provider; class ProviderStream extends provider_1$1.default { constructor() { super(...arguments); this._reader = new stream_2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const source = this.api(root, task, options); const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); source .once('error', (error) => destination.emit('error', error)) .on('data', (entry) => destination.emit('data', options.transform(entry))) .once('end', () => destination.emit('end')); destination .once('close', () => source.destroy()); return destination; } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } stream$1.default = ProviderStream; var sync$2 = {}; var sync$1 = {}; Object.defineProperty(sync$1, "__esModule", { value: true }); const fsStat = out$1; const fsWalk = out$3; const reader_1 = reader; class ReaderSync extends reader_1.default { constructor() { super(...arguments); this._walkSync = fsWalk.walkSync; this._statSync = fsStat.statSync; } dynamic(root, options) { return this._walkSync(root, options); } static(patterns, options) { const entries = []; for (const pattern of patterns) { const filepath = this._getFullEntryPath(pattern); const entry = this._getEntry(filepath, pattern, options); if (entry === null || !options.entryFilter(entry)) { continue; } entries.push(entry); } return entries; } _getEntry(filepath, pattern, options) { try { const stats = this._getStat(filepath); return this._makeEntry(stats, pattern); } catch (error) { if (options.errorFilter(error)) { return null; } throw error; } } _getStat(filepath) { return this._statSync(filepath, this._fsStatSettings); } } sync$1.default = ReaderSync; Object.defineProperty(sync$2, "__esModule", { value: true }); const sync_1$1 = sync$1; const provider_1 = provider; class ProviderSync extends provider_1.default { constructor() { super(...arguments); this._reader = new sync_1$1.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = this.api(root, task, options); return entries.map(options.transform); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } sync$2.default = ProviderSync; var settings = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; const fs = require$$0$6; const os = require$$1; /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ const CPU_COUNT = Math.max(os.cpus().length, 1); exports.DEFAULT_FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, lstatSync: fs.lstatSync, stat: fs.stat, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; class Settings { constructor(_options = {}) { this._options = _options; this.absolute = this._getValue(this._options.absolute, false); this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); this.braceExpansion = this._getValue(this._options.braceExpansion, true); this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); this.cwd = this._getValue(this._options.cwd, process.cwd()); this.deep = this._getValue(this._options.deep, Infinity); this.dot = this._getValue(this._options.dot, false); this.extglob = this._getValue(this._options.extglob, true); this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); this.fs = this._getFileSystemMethods(this._options.fs); this.globstar = this._getValue(this._options.globstar, true); this.ignore = this._getValue(this._options.ignore, []); this.markDirectories = this._getValue(this._options.markDirectories, false); this.objectMode = this._getValue(this._options.objectMode, false); this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); this.onlyFiles = this._getValue(this._options.onlyFiles, true); this.stats = this._getValue(this._options.stats, false); this.suppressErrors = this._getValue(this._options.suppressErrors, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); this.unique = this._getValue(this._options.unique, true); if (this.onlyDirectories) { this.onlyFiles = false; } if (this.stats) { this.objectMode = true; } // Remove the cast to the array in the next major (#404). this.ignore = [].concat(this.ignore); } _getValue(option, value) { return option === undefined ? value : option; } _getFileSystemMethods(methods = {}) { return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); } } exports.default = Settings; } (settings)); const taskManager = tasks; const async_1 = async$8; const stream_1 = stream$1; const sync_1 = sync$2; const settings_1 = settings; const utils$6 = utils$q; async function FastGlob(source, options) { assertPatternsInput(source); const works = getWorks(source, async_1.default, options); const result = await Promise.all(works); return utils$6.array.flatten(result); } // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { FastGlob.glob = FastGlob; FastGlob.globSync = sync; FastGlob.globStream = stream; FastGlob.async = FastGlob; function sync(source, options) { assertPatternsInput(source); const works = getWorks(source, sync_1.default, options); return utils$6.array.flatten(works); } FastGlob.sync = sync; function stream(source, options) { assertPatternsInput(source); const works = getWorks(source, stream_1.default, options); /** * The stream returned by the provider cannot work with an asynchronous iterator. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. * This affects performance (+25%). I don't see best solution right now. */ return utils$6.stream.merge(works); } FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput(source); const patterns = [].concat(source); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } FastGlob.generateTasks = generateTasks; function isDynamicPattern(source, options) { assertPatternsInput(source); const settings = new settings_1.default(options); return utils$6.pattern.isDynamicPattern(source, settings); } FastGlob.isDynamicPattern = isDynamicPattern; function escapePath(source) { assertPatternsInput(source); return utils$6.path.escape(source); } FastGlob.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils$6.path.convertPathToPattern(source); } FastGlob.convertPathToPattern = convertPathToPattern; (function (posix) { function escapePath(source) { assertPatternsInput(source); return utils$6.path.escapePosixPath(source); } posix.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils$6.path.convertPosixPathToPattern(source); } posix.convertPathToPattern = convertPathToPattern; })(FastGlob.posix || (FastGlob.posix = {})); (function (win32) { function escapePath(source) { assertPatternsInput(source); return utils$6.path.escapeWindowsPath(source); } win32.escapePath = escapePath; function convertPathToPattern(source) { assertPatternsInput(source); return utils$6.path.convertWindowsPathToPattern(source); } win32.convertPathToPattern = convertPathToPattern; })(FastGlob.win32 || (FastGlob.win32 = {})); })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { const patterns = [].concat(source); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); return tasks.map(provider.read, provider); } function assertPatternsInput(input) { const source = [].concat(input); const isValidSource = source.every((item) => utils$6.string.isString(item) && !utils$6.string.isEmpty(item)); if (!isValidSource) { throw new TypeError('Patterns must be a string (non empty) or an array of strings'); } } var out = FastGlob; var fg = /*@__PURE__*/getDefaultExportFromCjs(out); /** * @packageDocumentation * * Like [`glob`](https://npmjs.com/package/glob) but async iterable. * * File separators on Windows will be yielded as `/` and not `\`. * * @example * * ```javascript * import glob from 'it-glob' * * // All options are passed through to fast-glob * const options = {} * * for await (const path of glob('/path/to/file', '**\/*', options)) { * console.info(path) * } * ``` * * See the [fast-glob docs](https://github.com/mrmlnc/fast-glob#options-3) for the full list of options. */ /** * Async iterable filename pattern matcher */ async function* glob(dir, pattern, options = {}) { const absoluteDir = path$h.resolve(dir); const stats = await fs$c.stat(absoluteDir); for await (const entry of fg.stream(pattern, { ...options, cwd: stats.isDirectory() ? dir : process.cwd() })) { yield entry.toString(); } } /** * @packageDocumentation * * The final batch may be smaller than the max. * * @example * * ```javascript * import batch from 'it-batch' * import all from 'it-all' * * // This can also be an iterator, generator, etc * const values = [0, 1, 2, 3, 4] * const batchSize = 2 * * const result = all(batch(values, batchSize)) * * console.info(result) // [0, 1], [2, 3], [4] * ``` * * Async sources must be awaited: * * ```javascript * import batch from 'it-batch' * import all from 'it-all' * * const values = async function * () { * yield * [0, 1, 2, 3, 4] * } * * const batchSize = 2 * const result = await all(batch(values(), batchSize)) * * console.info(result) // [0, 1], [2, 3], [4] * ``` */ function isAsyncIterable(thing) { return thing[Symbol.asyncIterator] != null; } function batch(source, size = 1) { size = Number(size); if (isAsyncIterable(source)) { return (async function* () { let things = []; if (size < 1) { size = 1; } if (size !== Math.round(size)) { throw new Error('Batch size must be an integer'); } for await (const thing of source) { things.push(thing); while (things.length >= size) { yield things.slice(0, size); things = things.slice(size); } } while (things.length > 0) { yield things.slice(0, size); things = things.slice(size); } }()); } return (function* () { let things = []; if (size < 1) { size = 1; } if (size !== Math.round(size)) { throw new Error('Batch size must be an integer'); } for (const thing of source) { things.push(thing); while (things.length >= size) { yield things.slice(0, size); things = things.slice(size); } } while (things.length > 0) { yield things.slice(0, size); things = things.slice(size); } }()); } /** * @packageDocumentation * * Takes an async iterator that emits promise-returning functions, invokes them in parallel and emits the results in the same order as the input. * * The final batch may be smaller than the batch size. * * @example * * ```javascript * import parallelBatch from 'it-parallel-batch' * import all from 'it-all' * import delay from 'delay' * * // This can also be an iterator, async iterator, generator, etc * const input = [ * async () => { * await delay(500) * * return 1 * }, * async () => { * await delay(200) * * return 2 * }, * async () => { * await delay(100) * * return 3 * } * ] * * const batchSize = 2 * * const result = await all(parallelBatch(input, batchSize)) * * console.info(result) // [1, 2, 3] * ``` */ /** * Takes an (async) iterator that emits promise-returning functions, * invokes them in parallel and emits the results as they become available but * in the same order as the input */ async function* parallelBatch(source, size = 1) { for await (const tasks of batch(source, size)) { const things = tasks.map(async (p) => { return p().then(value => ({ ok: true, value }), err => ({ ok: false, err })); }); for (let i = 0; i < things.length; i++) { const result = await things[i]; if (result.ok) { yield result.value; } else { throw result.err; } } } } // Returns a temporary file // Example: for /some/file will return /some/.file.tmp function getTempFilename(file) { const f = file instanceof URL ? require$$3.fileURLToPath(file) : file.toString(); return path$h.join(path$h.dirname(f), `.${path$h.basename(f)}.tmp`); } // Retries an asynchronous operation with a delay between retries and a maximum retry count async function retryAsyncOperation(fn, maxRetries, delayMs) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (i < maxRetries - 1) { await new Promise((resolve) => setTimeout(resolve, delayMs)); } else { throw error; // Rethrow the error if max retries reached } } } } class Writer { #filename; #tempFilename; #locked = false; #prev = null; #next = null; #nextPromise = null; #nextData = null; // File is locked, add data for later #add(data) { // Only keep most recent data this.#nextData = data; // Create a singleton promise to resolve all next promises once next data is written this.#nextPromise ||= new Promise((resolve, reject) => { this.#next = [resolve, reject]; }); // Return a promise that will resolve at the same time as next promise return new Promise((resolve, reject) => { this.#nextPromise?.then(resolve).catch(reject); }); } // File isn't locked, write data async #write(data) { // Lock file this.#locked = true; try { // Atomic write await fs$c.writeFile(this.#tempFilename, data, 'utf-8'); await retryAsyncOperation(async () => { await fs$c.rename(this.#tempFilename, this.#filename); }, 10, 100); // Call resolve this.#prev?.[0](); } catch (err) { // Call reject if (err instanceof Error) { this.#prev?.[1](err); } throw err; } finally { // Unlock file this.#locked = false; this.#prev = this.#next; this.#next = this.#nextPromise = null; if (this.#nextData !== null) { const nextData = this.#nextData; this.#nextData = null; await this.write(nextData); } } } constructor(filename) { this.#filename = filename; this.#tempFilename = getTempFilename(filename); } async write(data) { return this.#locked ? this.#add(data) : this.#write(data); } } /** * @packageDocumentation * * A Datastore implementation with a file system backend. * * @example * * ```js * import { FsDatastore } from 'datastore-fs' * * const store = new FsDatastore('path/to/store') * ``` */ /** * Write a file atomically */ async function writeFile(path, contents) { try { const writer = new Writer(path); await writer.write(contents); } catch (err) { if (err.syscall === 'rename' && ['ENOENT', 'EPERM'].includes(err.code)) { // steno writes a file to a temp location before renaming it. // If the final file already exists this error is thrown. // Make sure we can read & write to this file await fs$c.access(path, fs$c.constants.F_OK | fs$c.constants.W_OK); // The file was created by another context - this means there were // attempts to write the same block by two different function calls return; } throw err; } } /** * A datastore backed by the file system. * * Keys need to be sanitized before use, as they are written * to the file system as is. */ class FsDatastore extends BaseDatastore { path; createIfMissing; errorIfExists; extension; deleteManyConcurrency; getManyConcurrency; putManyConcurrency; constructor(location, init = {}) { super(); this.path = path$h.resolve(location); this.createIfMissing = init.createIfMissing ?? true; this.errorIfExists = init.errorIfExists ?? false; this.extension = init.extension ?? '.data'; this.deleteManyConcurrency = init.deleteManyConcurrency ?? 50; this.getManyConcurrency = init.getManyConcurrency ?? 50; this.putManyConcurrency = init.putManyConcurrency ?? 50; } async open() { try { await fs$c.access(this.path, fs$c.constants.F_OK | fs$c.constants.W_OK); if (this.errorIfExists) { throw new OpenFailedError(`Datastore directory: ${this.path} already exists`); } } catch (err) { if (err.code === 'ENOENT') { if (this.createIfMissing) { await fs$c.mkdir(this.path, { recursive: true }); return; } else { throw new NotFoundError(`Datastore directory: ${this.path} does not exist`); } } throw err; } } async close() { } /** * Calculate the directory and file name for a given key. */ _encode(key) { const parent = key.parent().toString(); const dir = path$h.join(this.path, parent); const name = key.toString().slice(parent.length); const file = path$h.join(dir, name + this.extension); return { dir, file }; } /** * Calculate the original key, given the file name. */ _decode(file) { const ext = this.extension; if (path$h.extname(file) !== ext) { throw new Error(`Invalid extension: ${path$h.extname(file)}`); } const keyname = file .slice(this.path.length, -ext.length) .split(path$h.sep) .join('/'); return new Key(keyname); } /** * Store the given value under the key */ async put(key, val) { const parts = this._encode(key); try { await fs$c.mkdir(parts.dir, { recursive: true }); await writeFile(parts.file, val); return key; } catch (err) { throw new PutFailedError(String(err)); } } async *putMany(source) { yield* parallelBatch(map$1(source, ({ key, value }) => { return async () => { await this.put(key, value); return key; }; }), this.putManyConcurrency); } /** * Read from the file system */ async get(key) { const parts = this._encode(key); let data; try { data = await fs$c.readFile(parts.file); } catch (err) { throw new NotFoundError(String(err)); } return data; } async *getMany(source) { yield* parallelBatch(map$1(source, key => { return async () => { return { key, value: await this.get(key) }; }; }), this.getManyConcurrency); } async *deleteMany(source) { yield* parallelBatch(map$1(source, key => { return async () => { await this.delete(key); return key; }; }), this.deleteManyConcurrency); } /** * Check for the existence of the given key */ async has(key) { const parts = this._encode(key); try { await fs$c.access(parts.file); } catch (err) { return false; } return true; } /** * Delete the record under the given key */ async delete(key) { const parts = this._encode(key); try { await fs$c.unlink(parts.file); } catch (err) { if (err.code === 'ENOENT') { return; } throw new DeleteFailedError(String(err)); } } async *_all(q) { let prefix = q.prefix ?? '**'; // strip leading slashes prefix = prefix.replace(/^\/+/, ''); const pattern = `${prefix}/*${this.extension}` .split(path$h.sep) .join('/'); const files = glob(this.path, pattern, { absolute: true }); for await (const file of files) { try { const buf = await fs$c.readFile(file); const pair = { key: this._decode(file), value: buf }; yield pair; } catch (err) { // if keys are removed from the datastore while the query is // running, we may encounter missing files. if (err.code !== 'ENOENT') { throw err; } } } } async *_allKeys(q) { let prefix = q.prefix ?? '**'; // strip leading slashes prefix = prefix.replace(/^\/+/, ''); const pattern = `${prefix}/*${this.extension}` .split(path$h.sep) .join('/'); const files = glob(this.path, pattern, { absolute: true }); yield* map$1(files, f => this._decode(f)); } } var picocolors = {exports: {}}; let p$10 = process || {}, argv = p$10.argv || [], env = p$10.env || {}; let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p$10.platform === "win32" || ((p$10.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI); let formatter = (open, close, replace = open) => input => { let string = "" + input, index = string.indexOf(close, open.length); return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close }; let replaceClose = (string, close, replace, index) => { let result = "", cursor = 0; do { result += string.substring(cursor, index) + replace; cursor = index + close.length; index = string.indexOf(close, cursor); } while (~index) return result + string.substring(cursor) }; let createColors = (enabled = isColorSupported) => { let f = enabled ? formatter : () => String; return { isColorSupported: enabled, reset: f("\x1b[0m", "\x1b[0m"), bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), italic: f("\x1b[3m", "\x1b[23m"), underline: f("\x1b[4m", "\x1b[24m"), inverse: f("\x1b[7m", "\x1b[27m"), hidden: f("\x1b[8m", "\x1b[28m"), strikethrough: f("\x1b[9m", "\x1b[29m"), black: f("\x1b[30m", "\x1b[39m"), red: f("\x1b[31m", "\x1b[39m"), green: f("\x1b[32m", "\x1b[39m"), yellow: f("\x1b[33m", "\x1b[39m"), blue: f("\x1b[34m", "\x1b[39m"), magenta: f("\x1b[35m", "\x1b[39m"), cyan: f("\x1b[36m", "\x1b[39m"), white: f("\x1b[37m", "\x1b[39m"), gray: f("\x1b[90m", "\x1b[39m"), bgBlack: f("\x1b[40m", "\x1b[49m"), bgRed: f("\x1b[41m", "\x1b[49m"), bgGreen: f("\x1b[42m", "\x1b[49m"), bgYellow: f("\x1b[43m", "\x1b[49m"), bgBlue: f("\x1b[44m", "\x1b[49m"), bgMagenta: f("\x1b[45m", "\x1b[49m"), bgCyan: f("\x1b[46m", "\x1b[49m"), bgWhite: f("\x1b[47m", "\x1b[49m"), blackBright: f("\x1b[90m", "\x1b[39m"), redBright: f("\x1b[91m", "\x1b[39m"), greenBright: f("\x1b[92m", "\x1b[39m"), yellowBright: f("\x1b[93m", "\x1b[39m"), blueBright: f("\x1b[94m", "\x1b[39m"), magentaBright: f("\x1b[95m", "\x1b[39m"), cyanBright: f("\x1b[96m", "\x1b[39m"), whiteBright: f("\x1b[97m", "\x1b[39m"), bgBlackBright: f("\x1b[100m", "\x1b[49m"), bgRedBright: f("\x1b[101m", "\x1b[49m"), bgGreenBright: f("\x1b[102m", "\x1b[49m"), bgYellowBright: f("\x1b[103m", "\x1b[49m"), bgBlueBright: f("\x1b[104m", "\x1b[49m"), bgMagentaBright: f("\x1b[105m", "\x1b[49m"), bgCyanBright: f("\x1b[106m", "\x1b[49m"), bgWhiteBright: f("\x1b[107m", "\x1b[49m"), } }; picocolors.exports = createColors(); picocolors.exports.createColors = createColors; var picocolorsExports = picocolors.exports; var color = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); class Logger { info(message, ...optionalParams) { console.log(`[INFO] ${new Date().toISOString()} - ${message}`, ...optionalParams); } error(message, ...optionalParams) { console.error(`[ERROR] ${new Date().toISOString()} - ${message}`, ...optionalParams); } debug(message, ...optionalParams) { console.debug(`[DEBUG] ${new Date().toISOString()} - ${message}`, ...optionalParams); } } class Checkpointer { checkpoints = {}; datastore; constructor() { createDirectoryIfNotExists('./checkpoints').then(); const checkpointDir = require$$0$3.resolve('./checkpoints'); this.datastore = new FsDatastore(checkpointDir); } loadCheckpointFromFile(filePath) { throw new Error('Method not implemented.'); } // Método para cargar todos los checkpoints guardados async loadAllCheckpointsOnInit() { try { // Aquí podrías realizar una consulta para obtener todas las claves en el directorio de checkpoints const keys = this.datastore.queryKeys({}); for await (const key of keys) { const threadId = key.toString().replace("/", "").trim(); // Convertir la clave a string (thread_id) const checkpoints = await this.loadCheckpointFromDatastore(threadId); if (checkpoints) { this.checkpoints[threadId] = checkpoints; } } } catch (error) { console.error('Error al cargar los checkpoints iniciales:', error); } } // Verificar si un nodo está completado usando message_id isCompleted(ctx) { const checkpoints = this.checkpoints[ctx.from] || []; const actualCheckpoint = checkpoints.at(-1); if (actualCheckpoint) { const isComplete = actualCheckpoint?.ctx?.timestamp === ctx?.timestamp && actualCheckpoint?.status === "completed"; return isComplete; } return false; } // Obtener el estado del último checkpoint getCheckpointStatus(threadId) { const checkpoints = this.checkpoints[threadId] || []; const status = checkpoints.length ? checkpoints.at(-1).status : null; return status; } getCheckpointStatusPending() { return Object.values(this.checkpoints).map(checkpoint => checkpoint.at(-1)).filter(checkpoint => { return checkpoint.status === "in-progress" || checkpoint.status === "pending"; }); } getActualThreadID(thread_id) { const checkpoint = this.checkpoints[thread_id]?.at(-1) || undefined; return checkpoint; } // Resetear el último checkpoint resetCheckpoint(threadId) { const checkpoints = this.checkpoints[threadId] || []; if (checkpoints.length) { checkpoints[checkpoints.length - 1].status = 'reset'; } } // Guardar un nuevo checkpoint async saveCheckpoint(args) { args.trigger_key = String(args.trigger_key); const checkpoint = { timestamp: new Date(), status: "in-progress", ...args }; if (!this.checkpoints[args.thread_id]) { this.checkpoints[args.thread_id] = []; } // Filtrar checkpoints por message_id y reemplazar el anterior this.checkpoints[args.thread_id] = this.checkpoints[args.thread_id].filter(c => c?.message_id !== args?.message_id); this.checkpoints[args.thread_id].push(checkpoint); // Escribir el checkpoint en el datastore await this.writeCheckpointToDatastore(args.thread_id, this.checkpoints[args.thread_id]); } // Restaurar checkpoints desde el datastore async loadCheckpointFromDatastore(thread_id) { try { const key = new Key(thread_id); const buffer = await this.datastore.get(key); const data = buffer.toString(); // Convertir buffer a string return JSON.parse(data); } catch (error) { console.warn(`No se encontró el checkpoint para thread_id ${thread_id}:`, error.message); return []; } } // Actualizar el estado del último checkpoint usando messageId async updateCheckpointStatus(args) { await this.saveCheckpoint(args); } // Escribir un checkpoint en el datastore async writeCheckpointToDatastore(thread_id, data) { const key = new Key(thread_id); const buffer = require$$0$8.Buffer.from(JSON.stringify(data)); // Convertir a buffer try { await this.datastore.put(key, buffer); } catch (error) { console.error('Error escribiendo el checkpoint en el datastore:', error); } } } var util$2; (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" // eslint-disable-line ban/ban ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban : (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) // eslint-disable-line ban/ban : (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$2 || (util$2 = {})); var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { return { ...first, ...second, // second overwrites first }; }; })(objectUtil || (objectUtil = {})); const ZodParsedType = util$2.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 ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; const ZodIssueCode = util$2.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:"); }; 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) { // eslint-disable-next-line ban/ban 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: [] }; // if (typeof el === "string") { // curr[el] = curr[el] || { _errors: [] }; // } else if (typeof el === "number") { // const errorArray: any = []; // errorArray._errors = []; // curr[el] = curr[el] || errorArray; // } } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } static assert(value) { if (!(value instanceof ZodError)) { throw new Error(`Not a ZodError: ${value}`); } } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util$2.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } } ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; const errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$2.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util$2.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util$2.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util$2.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util$2.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util$2.assertNever(issue); } return { message }; }; let overrideErrorMap = errorMap; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; const fullIssue = { ...issueData, path: fullPath, }; if (issueData.message !== undefined) { return { ...issueData, path: fullPath, message: issueData.message, }; } 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: errorMessage, }; }; const EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const overrideMap = getErrorMap(); const issue = makeIssue({ issueData: issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, overrideMap, overrideMap === errorMap ? undefined : errorMap, // then global default map ].filter((x) => !!x), }); ctx.common.issues.push(issue); } 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 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) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs) { const finalObject = {}; for (const pair of pairs) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } } const INVALID = Object.freeze({ status: "aborted", }); const DIRTY = (value) => ({ status: "dirty", value }); const OK = (value) => ({ status: "valid", value }); const isAborted = (x) => x.status === "aborted"; const isDirty = (x) => x.status === "dirty"; const isValid = (x) => x.status === "valid"; const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __classPrivateFieldGet$5(receiver, state, kind, f) { 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 state.get(receiver); } function __classPrivateFieldSet$4(receiver, state, value, kind, f) { 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 (state.set(receiver, value)), value; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; 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 || (errorUtil = {})); var _ZodEnum_cache, _ZodNativeEnum_cache; 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 handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); this._error = error; return this._error; }, }; } }; 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) => { var _a, _b; const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; }; return { errorMap: customMap, description }; } class ZodType { constructor(def) { /** Alias of safeParseAsync */ this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return (ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }); } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent, }, }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _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: getParsedType(data), }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true, }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data), }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (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: 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 cuidRegex = /^c[^\s-]{8,}$/i; const cuid2Regex = /^[0-9a-z]+$/; const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; // const uuidRegex = // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; 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 nanoidRegex = /^[a-z0-9_-]{21}$/i; const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; // from https://stackoverflow.com/a/46181/1550155 // old version: too slow, didn't support unicode // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; //old email regex // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; // eslint-disable-next-line // const emailRegex = // /^(([^<>()[\]\\.,;:\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,})+))$/; // const emailRegex = // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; // const emailRegex = // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; // const emailRegex = // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; let emojiRegex; // faster, simpler, safer const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; 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})))$/; // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; // simple // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; // no leap year validation // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; // with leap year validation const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; const dateRegex = new RegExp(`^${dateRegexSource}$`); function timeRegexSource(args) { // let regex = `\\d{2}:\\d{2}:\\d{2}`; let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; if (args.precision) { regex = `${regex}\\.\\d{${args.precision}}`; } else if (args.precision == null) { regex = `${regex}(\\.\\d+)?`; } return regex; } function timeRegex(args) { return new RegExp(`^${timeRegexSource(args)}$`); } // Adapted from https://stackoverflow.com/a/3143231 function datetimeRegex(args) { let regex = `${dateRegexSource}T${timeRegexSource(args)}`; const opts = []; opts.push(args.local ? `Z?` : `Z`); if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`); regex = `${regex}(${opts.join("|")})`; return new RegExp(`^${regex}$`); } 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 ZodString extends ZodType { _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx.parsedType, }); return INVALID; } const status = new 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); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message, }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex) { emojiRegex = new RegExp(_emojiRegex, "u"); } if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "nanoid") { if (!nanoidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message, }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message, }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check.message, }); status.dirty(); } } else if (check.kind === "date") { const regex = dateRegex; if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "date", message: check.message, }); status.dirty(); } } else if (check.kind === "time") { const regex = timeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check.message, }); status.dirty(); } } else if (check.kind === "duration") { if (!durationRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else if (check.kind === "base64") { if (!base64Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check.message, }); status.dirty(); } } else { util$2.assertNever(check); } } return { status: status.value, value: input.data }; } _regex(regex, validation, message) { return this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message), }); } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check], }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } nanoid(message) { return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } base64(message) { return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } datetime(options) { var _a, _b; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: options, }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } date(message) { return this._addCheck({ kind: "date", message }); } time(options) { if (typeof options === "string") { return this._addCheck({ kind: "time", precision: null, message: options, }); } return this._addCheck({ kind: "time", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } duration(message) { return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex: regex, ...errorUtil.errToObj(message), }); } includes(value, options) { return this._addCheck({ kind: "includes", value: value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value: value, ...errorUtil.errToObj(message), }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value: value, ...errorUtil.errToObj(message), }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message), }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message), }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message), }); } /** * @deprecated Use z.string().min(1) instead. * @see {@link ZodString.min} */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } trim() { return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }], }); } toLowerCase() { return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }], }); } toUpperCase() { return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }], }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isDate() { return !!this._def.checks.find((ch) => ch.kind === "date"); } get isTime() { return !!this._def.checks.find((ch) => ch.kind === "time"); } get isDuration() { return !!this._def.checks.find((ch) => ch.kind === "duration"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isNANOID() { return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get isBase64() { return !!this._def.checks.find((ch) => ch.kind === "base64"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } ZodString.create = (params) => { var _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), }); }; // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 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); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx.parsedType, }); return INVALID; } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util$2.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message, }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message, }); status.dirty(); } } else { util$2.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check], }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message), }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value: value, message: errorUtil.toString(message), }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message), }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message), })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util$2.isInteger(ch.value))); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } } ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params), }); }; 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 !== ZodParsedType.bigint) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx.parsedType, }); return INVALID; } let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message, }); status.dirty(); } } else { util$2.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message), }, ], }); } _addCheck(check) { return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check], }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message), }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } } ZodBigInt.create = (params) => { var _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 !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params), }); }; class ZodDate extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx.parsedType, }); return INVALID; } if (isNaN(input.data.getTime())) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_date, }); return INVALID; } const status = new 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); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date", }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date", }); status.dirty(); } } else { util$2.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()), }; } _addCheck(check) { return new ZodDate({ ...this._def, checks: [...this._def.checks, check], }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message), }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message), }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } } ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params), }); }; class ZodSymbol extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params), }); }; class ZodUndefined extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params), }); }; class ZodNull extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params), }); }; class ZodAny extends ZodType { constructor() { super(...arguments); // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. this._any = true; } _parse(input) { return OK(input.data); } } ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params), }); }; class ZodUnknown extends ZodType { constructor() { super(...arguments); // required this._unknown = true; } _parse(input) { return OK(input.data); } } ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params), }); }; class ZodNever extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType, }); return INVALID; } } ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params), }); }; class ZodVoid extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType, }); return INVALID; } return OK(input.data); } } ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params), }); }; class ZodArray extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: (tooSmall ? def.exactLength.value : 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) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message, }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message, }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result) => { return ParseStatus.mergeArray(status, result); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) }, }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) }, }); } length(len, message) { return new ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) }, }); } nonempty(message) { return this.min(1, message); } } ZodArray.create = (schema, params) => { return new ZodArray({ type: schema, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params), }); }; 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; } } class ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; /** * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. * If you want to pass through unknown properties, use `.passthrough()` instead. */ this.nonstrict = this.passthrough; // extend< // Augmentation extends ZodRawShape, // NewOutput extends util.flatten<{ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }>, // NewInput extends util.flatten<{ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // }> // >( // augmentation: Augmentation // ): ZodObject< // extendShape, // UnknownKeys, // Catchall, // NewOutput, // NewInput // > { // return new ZodObject({ // ...this._def, // shape: () => ({ // ...this._def.shape(), // ...augmentation, // }), // }) as any; // } /** * @deprecated Use `.extend` instead * */ this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util$2.objectKeys(shape); return (this._cached = { shape, keys }); } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data, }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] }, }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys, }); status.dirty(); } } else if (unknownKeys === "strip") ; else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { // run catchall validation const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data, }); } } if (ctx.common.async) { return Promise.resolve() .then(async () => { const syncPairs = []; for (const pair of pairs) { const key = await pair.key; const value = await pair.value; syncPairs.push({ key, value, alwaysSet: pair.alwaysSet, }); } return syncPairs; }) .then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...(message !== 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.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, }; return { message: defaultError, }; }, } : {}), }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip", }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough", }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation, }), }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape(), }), typeName: ZodFirstPartyTypeKind.ZodObject, }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema) { return this.augment({ [key]: schema }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index) { return new ZodObject({ ...this._def, catchall: index, }); } pick(mask) { const shape = {}; util$2.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } omit(mask) { const shape = {}; util$2.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape, }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util$2.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape, }); } required(mask) { const newShape = {}; util$2.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$2.objectKeys(this.shape)); } } ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; class ZodUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { // return first issue-free validation if it exists for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { // add issues from dirty option ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } // return invalid const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [], }, parent: null, }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx, }), ctx: childCtx, }; })).then(handleResults); } else { let dirty = 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(issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors, }); return INVALID; } } get options() { return this._def.options; } } ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// ////////// ////////// ////////// ZodDiscriminatedUnion ////////// ////////// ////////// ///////////////////////////////////////////////////// ///////////////////////////////////////////////////// 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]; } else if (type instanceof ZodEnum) { return type.options; } else if (type instanceof ZodNativeEnum) { // eslint-disable-next-line ban/ban return util$2.objectValues(type.enum); } 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 if (type instanceof ZodOptional) { return [undefined, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodNullable) { return [null, ...getDiscriminator(type.unwrap())]; } else if (type instanceof ZodBranded) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodReadonly) { return getDiscriminator(type.unwrap()); } else if (type instanceof ZodCatch) { return getDiscriminator(type._def.innerType); } else { return []; } }; class ZodDiscriminatedUnion extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator], }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { // Get all the valid discriminator values const optionsMap = new Map(); // try { for (const type of options) { const discriminatorValues = getDiscriminator(type.shape[discriminator]); if (!discriminatorValues.length) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params), }); } } function mergeValues(a, b) { const aType = getParsedType(a); const bType = getParsedType(b); if (a === b) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util$2.objectKeys(b); const sharedKeys = util$2 .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 }; } else if (aType === ZodParsedType.array && bType === 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 }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { return { valid: true, data: a }; } else { return { valid: false }; } } class ZodIntersection extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types, }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx, }), ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, })); } } } ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left: left, right: right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params), }); }; class ZodTuple extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array", }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array", }); status.dirty(); } const items = [...ctx.data] .map((item, itemIndex) => { const schema = this._def.items[itemIndex] || this._def.rest; if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }) .filter((x) => !!x); // filter nulls if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest, }); } } ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params), }); }; class ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } const pairs = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), alwaysSet: key in ctx.data, }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs); } else { return ParseStatus.mergeObjectSync(status, pairs); } } get element() { return this._def.valueType; } static create(first, 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), }); } } 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 !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType, }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs = [...ctx.data.entries()].map(([key, value], index) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), }; }); if (ctx.common.async) { const finalMap = new Map(); return Promise.resolve().then(async () => { for (const pair of pairs) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = new Map(); for (const pair of pairs) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } } ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params), }); }; class ZodSet extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType, }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message, }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message, }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements) { const parsedSet = new Set(); for (const element of elements) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, 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.toString(message) }, }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) }, }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params), }); }; class ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType, }); return INVALID; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap, ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error, }, }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap, ].filter((x) => !!x), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error, }, }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { // Would love a way to avoid disabling this rule, but we need // an alias (using an arrow function was what caused 2651). // eslint-disable-next-line @typescript-eslint/no-this-alias const me = this; return OK(async function (...args) { const error = new 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 { // Would love a way to avoid disabling this rule, but we need // an alias (using an arrow function was what caused 2651). // eslint-disable-next-line @typescript-eslint/no-this-alias const me = this; return OK(function (...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()), }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType, }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params), }); } } class ZodLazy extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } } ZodLazy.create = (getter, params) => { return new ZodLazy({ getter: getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params), }); }; class ZodLiteral extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value, }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } } ZodLiteral.create = (value, params) => { return new ZodLiteral({ value: value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params), }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params), }); } class ZodEnum extends ZodType { constructor() { super(...arguments); _ZodEnum_cache.set(this, void 0); } _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util$2.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type, }); return INVALID; } if (!__classPrivateFieldGet$5(this, _ZodEnum_cache)) { __classPrivateFieldSet$4(this, _ZodEnum_cache, new Set(this._def.values)); } if (!__classPrivateFieldGet$5(this, _ZodEnum_cache).has(input.data)) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues, }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const 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, newDef = this._def) { return ZodEnum.create(values, { ...this._def, ...newDef, }); } exclude(values, newDef = this._def) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { ...this._def, ...newDef, }); } } _ZodEnum_cache = new WeakMap(); ZodEnum.create = createZodEnum; class ZodNativeEnum extends ZodType { constructor() { super(...arguments); _ZodNativeEnum_cache.set(this, void 0); } _parse(input) { const nativeEnumValues = util$2.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util$2.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util$2.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type, }); return INVALID; } if (!__classPrivateFieldGet$5(this, _ZodNativeEnum_cache)) { __classPrivateFieldSet$4(this, _ZodNativeEnum_cache, new Set(util$2.getValidEnumValues(this._def.values))); } if (!__classPrivateFieldGet$5(this, _ZodNativeEnum_cache).has(input.data)) { const expectedValues = util$2.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues, }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } } _ZodNativeEnum_cache = new WeakMap(); 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 !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType, }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap, }); })); } } ZodPromise.create = (schema, params) => { return new ZodPromise({ type: schema, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params), }); }; 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) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; }, }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.async) { return Promise.resolve(processed).then(async (processed) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed, path: ctx.path, parent: ctx, }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx, }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); // return value is ignored executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (!isValid(base)) return base; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) .then((base) => { if (!isValid(base)) return base; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util$2.assertNever(effect); } } ZodEffects.create = (schema, effect, params) => { return new ZodEffects({ schema, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params), }); }; ZodEffects.createWithPreprocess = (preprocess, schema, params) => { return new ZodEffects({ schema, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params), }); }; class ZodOptional extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(undefined); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params), }); }; class ZodNullable extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } } ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params), }); }; class ZodDefault extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx, }); } removeDefault() { return this._def.innerType; } } ZodDefault.create = (type, params) => { return new ZodDefault({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params), }); }; class ZodCatch extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); // newCtx is used to not collect issues from inner types in ctx const newCtx = { ...ctx, common: { ...ctx.common, issues: [], }, }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx, }, }); if (isAsync(result)) { return result.then((result) => { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data, }), }; } } removeCatch() { return this._def.innerType; } } ZodCatch.create = (type, params) => { return new ZodCatch({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params), }); }; class ZodNaN extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType, }); return INVALID; } return { status: "valid", value: input.data }; } } ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; const 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; } } 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 INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx, }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx, }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value, }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx, }); } } } static create(a, b) { return new ZodPipeline({ in: a, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline, }); } } class ZodReadonly extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); const freeze = (data) => { if (isValid(data)) { data.value = Object.freeze(data.value); } return data; }; return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } unwrap() { return this._def.innerType; } } ZodReadonly.create = (type, params) => { return new ZodReadonly({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params), }); }; function custom$1(check, params = {}, /** * @deprecated * * Pass `fatal` into the params object instead: * * ```ts * z.string().custom((val) => val.length > 5, { fatal: false }) * ``` * */ 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(); } const 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 || (ZodFirstPartyTypeKind = {})); const instanceOfType = ( // const instanceOfType = any>( cls, params = { message: `Input not instance of ${cls.name}`, }) => custom$1((data) => data instanceof cls, params); const stringType = ZodString.create; const numberType = ZodNumber.create; const nanType = ZodNaN.create; const bigIntType = ZodBigInt.create; const booleanType = ZodBoolean.create; const dateType = ZodDate.create; const symbolType = ZodSymbol.create; const undefinedType = ZodUndefined.create; const nullType = ZodNull.create; const anyType = ZodAny.create; const unknownType = ZodUnknown.create; const neverType = ZodNever.create; const voidType = ZodVoid.create; const arrayType = ZodArray.create; const objectType = ZodObject.create; const strictObjectType = ZodObject.strictCreate; const unionType = ZodUnion.create; const discriminatedUnionType = ZodDiscriminatedUnion.create; const intersectionType = ZodIntersection.create; const tupleType = ZodTuple.create; const recordType = ZodRecord.create; const mapType = ZodMap.create; const setType = ZodSet.create; const functionType = ZodFunction.create; const lazyType = ZodLazy.create; const literalType = ZodLiteral.create; const enumType = ZodEnum.create; const nativeEnumType = ZodNativeEnum.create; const promiseType = ZodPromise.create; const effectsType = ZodEffects.create; const optionalType = ZodOptional.create; const nullableType = ZodNullable.create; const preprocessType = ZodEffects.createWithPreprocess; const pipelineType = ZodPipeline.create; const ostring = () => stringType().optional(); const onumber = () => numberType().optional(); const oboolean = () => booleanType().optional(); const 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 })), }; const NEVER = INVALID; var z$N = /*#__PURE__*/Object.freeze({ __proto__: null, defaultErrorMap: errorMap, setErrorMap: setErrorMap, getErrorMap: getErrorMap, makeIssue: makeIssue, EMPTY_PATH: EMPTY_PATH, addIssueToContext: addIssueToContext, ParseStatus: ParseStatus, INVALID: INVALID, DIRTY: DIRTY, OK: OK, isAborted: isAborted, isDirty: isDirty, isValid: isValid, isAsync: isAsync, get util () { return util$2; }, get objectUtil () { return objectUtil; }, ZodParsedType: ZodParsedType, getParsedType: getParsedType, ZodType: ZodType, datetimeRegex: datetimeRegex, ZodString: ZodString, ZodNumber: ZodNumber, ZodBigInt: ZodBigInt, ZodBoolean: ZodBoolean, ZodDate: ZodDate, ZodSymbol: ZodSymbol, ZodUndefined: ZodUndefined, ZodNull: ZodNull, ZodAny: ZodAny, ZodUnknown: ZodUnknown, ZodNever: ZodNever, ZodVoid: ZodVoid, ZodArray: ZodArray, ZodObject: ZodObject, ZodUnion: ZodUnion, ZodDiscriminatedUnion: ZodDiscriminatedUnion, ZodIntersection: ZodIntersection, ZodTuple: ZodTuple, ZodRecord: ZodRecord, ZodMap: ZodMap, ZodSet: ZodSet, ZodFunction: ZodFunction, ZodLazy: ZodLazy, ZodLiteral: ZodLiteral, ZodEnum: ZodEnum, ZodNativeEnum: ZodNativeEnum, ZodPromise: ZodPromise, ZodEffects: ZodEffects, ZodTransformer: ZodEffects, ZodOptional: ZodOptional, ZodNullable: ZodNullable, ZodDefault: ZodDefault, ZodCatch: ZodCatch, ZodNaN: ZodNaN, BRAND: BRAND, ZodBranded: ZodBranded, ZodPipeline: ZodPipeline, ZodReadonly: ZodReadonly, custom: custom$1, Schema: ZodType, ZodSchema: ZodType, late: late, get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, coerce: coerce, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, 'enum': enumType, 'function': functionType, 'instanceof': instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, 'null': nullType, nullable: nullableType, number: numberType, object: objectType, oboolean: oboolean, onumber: onumber, optional: optionalType, ostring: ostring, pipeline: pipelineType, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, symbol: symbolType, transformer: effectsType, tuple: tupleType, 'undefined': undefinedType, union: unionType, unknown: unknownType, 'void': voidType, NEVER: NEVER, ZodIssueCode: ZodIssueCode, quotelessJson: quotelessJson, ZodError: ZodError }); class FactoryLlm { llm; model; constructor(llm) { this.llm = llm; this.init(); } init() { if (!this.llm) return; const { apiKey, model } = this.llm; this.llm.provider ||= "openai"; // Inicializa el proveedor LLM basado en el tipo switch (this.llm?.provider) { case 'openai': this.model = new openai$1.ChatOpenAI({ apiKey, model: model || "gpt-4o-mini", temperature: 0 }); break; case 'groq': this.model = new groq.ChatGroq({ apiKey, model: model || "llama3-70b-8192", temperature: 0 }); break; default: throw new Error('Provider no válido'); } } async captureIntention(input, intentions) { const values = intentions.map(i => `${i.intention}: ${i.description}`); intentions.push({ intention: "unknown", description: "Intención no clarificada, ambigua o sin casi detalles" }); const parser = output_parsers.StructuredOutputParser.fromZodSchema(z$N.object({ intention: z$N.enum(intentions.map(i => i.intention)) })); const fixed_parser = output_parsers.OutputFixingParser.fromLLM(this.model, parser); const prompt = await prompts.ChatPromptTemplate.fromMessages([ [ "system", `Analiza el siguiente texto y encuentra la intención correspondiente a las intenciones disponibles:. Intentiones disponibles en formato '[intention]:[description]: >>>> ${values} >>>> Instrucciones de Formato de respuesta: >>> {format_instructions} >>> `, ], ["human", "El texto a analizar es: {input}"], ["human", "Unicamente retorna una intención que coincida con alguna de las intenciones disponibles."] ]).partial({ format_instructions: parser.getFormatInstructions(), }); const chain = prompt.pipe(this.model).pipe(fixed_parser); const { intention } = await chain.invoke({ input, format_instructions: parser.getFormatInstructions() }); console.info(`[CATCH INTENTION]: ${intention}`); return intention; } } var main$2 = {exports: {}}; var name$1 = "dotenv"; var version$3 = "16.4.5"; var description$1 = "Loads environment variables from .env file"; var main$1 = "lib/main.js"; var types$2 = "lib/main.d.ts"; var exports$1 = { ".": { 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" }; var scripts$1 = { "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", "test:coverage": "tap --coverage-report=lcov", prerelease: "npm test", release: "standard-version" }; var repository$1 = { type: "git", url: "git://github.com/motdotla/dotenv.git" }; var funding = "https://dotenvx.com"; var keywords$1 = [ "dotenv", "env", ".env", "environment", "variables", "config", "settings" ]; var readmeFilename = "README.md"; var license$1 = "BSD-2-Clause"; var devDependencies$1 = { "@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" }; var engines$1 = { node: ">=12" }; var browser = { fs: false }; var require$$4 = { name: name$1, version: version$3, description: description$1, main: main$1, types: types$2, exports: exports$1, scripts: scripts$1, repository: repository$1, funding: funding, keywords: keywords$1, readmeFilename: readmeFilename, license: license$1, devDependencies: devDependencies$1, engines: engines$1, browser: browser }; const fs$3 = require$$0$6; const path$6 = require$$0$3; const os$1 = require$$1; const crypto$1 = crypto$2; const packageJson = require$$4; const version$2 = packageJson.version; const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; // Parse src into an Object function parse$1 (src) { const obj = {}; // Convert buffer to string let lines = src.toString(); // Convert line breaks to same format lines = lines.replace(/\r\n?/mg, '\n'); let match; while ((match = LINE.exec(lines)) != null) { const key = match[1]; // Default undefined or null to empty string let value = (match[2] || ''); // Remove whitespace value = value.trim(); // Check if double quoted const maybeQuote = value[0]; // Remove surrounding quotes value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'); // Expand newlines if double quoted if (maybeQuote === '"') { value = value.replace(/\\n/g, '\n'); value = value.replace(/\\r/g, '\r'); } // Add to object obj[key] = value; } return obj } function _parseVault (options) { const vaultPath = _vaultPath(options); // Parse .env.vault const result = DotenvModule.configDotenv({ path: vaultPath }); if (!result.parsed) { const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); err.code = 'MISSING_DATA'; throw err } // handle scenario for comma separated keys - for use with key rotation // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" const keys = _dotenvKey(options).split(','); const length = keys.length; let decrypted; for (let i = 0; i < length; i++) { try { // Get full key const key = keys[i].trim(); // Get instructions for decrypt const attrs = _instructions(result, key); // Decrypt decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); break } catch (error) { // last key if (i + 1 >= length) { throw error } // try next key } } // Parse decrypted .env string return DotenvModule.parse(decrypted) } function _log (message) { console.log(`[dotenv@${version$2}][INFO] ${message}`); } function _warn (message) { console.log(`[dotenv@${version$2}][WARN] ${message}`); } function _debug (message) { console.log(`[dotenv@${version$2}][DEBUG] ${message}`); } function _dotenvKey (options) { // prioritize developer directly setting options.DOTENV_KEY if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { return options.DOTENV_KEY } // secondary infra already contains a DOTENV_KEY environment variable if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { return process.env.DOTENV_KEY } // fallback to empty string return '' } function _instructions (result, dotenvKey) { // Parse DOTENV_KEY. Format is a URI let uri; try { uri = new URL(dotenvKey); } catch (error) { if (error.code === 'ERR_INVALID_URL') { const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development'); err.code = 'INVALID_DOTENV_KEY'; throw err } throw error } // Get decrypt key const key = uri.password; if (!key) { const err = new Error('INVALID_DOTENV_KEY: Missing key part'); err.code = 'INVALID_DOTENV_KEY'; throw err } // Get environment const environment = uri.searchParams.get('environment'); if (!environment) { const err = new Error('INVALID_DOTENV_KEY: Missing environment part'); err.code = 'INVALID_DOTENV_KEY'; throw err } // Get ciphertext payload const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION if (!ciphertext) { const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'; throw err } return { ciphertext, key } } function _vaultPath (options) { let possibleVaultPath = null; if (options && options.path && options.path.length > 0) { if (Array.isArray(options.path)) { for (const filepath of options.path) { if (fs$3.existsSync(filepath)) { possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`; } } } else { possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`; } } else { possibleVaultPath = path$6.resolve(process.cwd(), '.env.vault'); } if (fs$3.existsSync(possibleVaultPath)) { return possibleVaultPath } return null } function _resolveHome (envPath) { return envPath[0] === '~' ? path$6.join(os$1.homedir(), envPath.slice(1)) : envPath } function _configVault (options) { _log('Loading env from encrypted .env.vault'); const parsed = DotenvModule._parseVault(options); let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsed, options); return { parsed } } function configDotenv (options) { const dotenvPath = path$6.resolve(process.cwd(), '.env'); let encoding = 'utf8'; const debug = Boolean(options && options.debug); if (options && options.encoding) { encoding = options.encoding; } else { if (debug) { _debug('No encoding is specified. UTF-8 is used by default'); } } let optionPaths = [dotenvPath]; // default, look for .env if (options && options.path) { if (!Array.isArray(options.path)) { optionPaths = [_resolveHome(options.path)]; } else { optionPaths = []; // reset default for (const filepath of options.path) { optionPaths.push(_resolveHome(filepath)); } } } // Build the parsed data in a temporary object (because we need to return it). Once we have the final // parsed data, we will combine it with process.env (or options.processEnv if provided). let lastError; const parsedAll = {}; for (const path of optionPaths) { try { // Specifying an encoding returns a string instead of a buffer const parsed = DotenvModule.parse(fs$3.readFileSync(path, { encoding })); DotenvModule.populate(parsedAll, parsed, options); } catch (e) { if (debug) { _debug(`Failed to load ${path} ${e.message}`); } lastError = e; } } let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsedAll, options); if (lastError) { return { parsed: parsedAll, error: lastError } } else { return { parsed: parsedAll } } } // Populates process.env from .env file function config (options) { // fallback to original dotenv if DOTENV_KEY is not set if (_dotenvKey(options).length === 0) { return DotenvModule.configDotenv(options) } const vaultPath = _vaultPath(options); // dotenvKey exists but .env.vault file does not exist if (!vaultPath) { _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); return DotenvModule.configDotenv(options) } return DotenvModule._configVault(options) } function decrypt (encrypted, keyStr) { const key = Buffer.from(keyStr.slice(-64), 'hex'); let ciphertext = Buffer.from(encrypted, 'base64'); const nonce = ciphertext.subarray(0, 12); const authTag = ciphertext.subarray(-16); ciphertext = ciphertext.subarray(12, -16); try { const aesgcm = crypto$1.createDecipheriv('aes-256-gcm', key, nonce); aesgcm.setAuthTag(authTag); return `${aesgcm.update(ciphertext)}${aesgcm.final()}` } catch (error) { const isRange = error instanceof RangeError; const invalidKeyLength = error.message === 'Invalid key length'; const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'; if (isRange || invalidKeyLength) { const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)'); err.code = 'INVALID_DOTENV_KEY'; throw err } else if (decryptionFailed) { const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY'); err.code = 'DECRYPTION_FAILED'; throw err } else { throw error } } } // Populate process.env with parsed values function populate (processEnv, parsed, options = {}) { const debug = Boolean(options && options.debug); const override = Boolean(options && options.override); if (typeof parsed !== 'object') { const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate'); err.code = 'OBJECT_REQUIRED'; throw err } // Set process.env for (const key of Object.keys(parsed)) { if (Object.prototype.hasOwnProperty.call(processEnv, key)) { if (override === true) { processEnv[key] = parsed[key]; } if (debug) { if (override === true) { _debug(`"${key}" is already defined and WAS overwritten`); } else { _debug(`"${key}" is already defined and was NOT overwritten`); } } } else { processEnv[key] = parsed[key]; } } } const DotenvModule = { configDotenv, _configVault, _parseVault, config, decrypt, parse: parse$1, populate }; main$2.exports.configDotenv = DotenvModule.configDotenv; main$2.exports._configVault = DotenvModule._configVault; main$2.exports._parseVault = DotenvModule._parseVault; main$2.exports.config = DotenvModule.config; main$2.exports.decrypt = DotenvModule.decrypt; main$2.exports.parse = DotenvModule.parse; main$2.exports.populate = DotenvModule.populate; main$2.exports = DotenvModule; var mainExports = main$2.exports; // ../config.js accepts options via environment variables const options = {}; if (process.env.DOTENV_CONFIG_ENCODING != null) { options.encoding = process.env.DOTENV_CONFIG_ENCODING; } if (process.env.DOTENV_CONFIG_PATH != null) { options.path = process.env.DOTENV_CONFIG_PATH; } if (process.env.DOTENV_CONFIG_DEBUG != null) { options.debug = process.env.DOTENV_CONFIG_DEBUG; } if (process.env.DOTENV_CONFIG_OVERRIDE != null) { options.override = process.env.DOTENV_CONFIG_OVERRIDE; } if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) { options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY; } var envOptions = options; const re$b = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/; var cliOptions = function optionMatcher (args) { return args.reduce(function (acc, cur) { const matches = cur.match(re$b); if (matches) { acc[matches[1]] = matches[2]; } return acc }, {}) }; (function () { mainExports.config( Object.assign( {}, envOptions, cliOptions(process.argv) ) ); })(); var openai = {exports: {}}; var qs = {}; var formats = {}; Object.defineProperty(formats, "__esModule", { value: true }); formats.RFC3986 = formats.RFC1738 = formats.formatters = formats.default_format = void 0; formats.default_format = 'RFC3986'; formats.formatters = { RFC1738: (v) => String(v).replace(/%20/g, '+'), RFC3986: (v) => String(v), }; formats.RFC1738 = 'RFC1738'; formats.RFC3986 = 'RFC3986'; var stringify$2 = {}; var utils$5 = {}; Object.defineProperty(utils$5, "__esModule", { value: true }); utils$5.maybe_map = utils$5.combine = utils$5.is_buffer = utils$5.is_regexp = utils$5.compact = utils$5.encode = utils$5.decode = utils$5.assign_single_source = utils$5.merge = void 0; const formats_1$1 = formats; const has$1 = Object.prototype.hasOwnProperty; const is_array$1 = Array.isArray; const hex_table = (() => { const array = []; for (let i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; })(); function compact_queue(queue) { while (queue.length > 1) { const item = queue.pop(); if (!item) continue; const obj = item.obj[item.prop]; if (is_array$1(obj)) { const compacted = []; for (let j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } // @ts-ignore item.obj[item.prop] = compacted; } } } function array_to_object(source, options) { const obj = options && options.plainObjects ? Object.create(null) : {}; for (let i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; } function merge$2(target, source, options = {}) { if (!source) { return target; } if (typeof source !== 'object') { if (is_array$1(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has$1.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } let mergeTarget = target; if (is_array$1(target) && !is_array$1(source)) { // @ts-ignore mergeTarget = array_to_object(target, options); } if (is_array$1(target) && is_array$1(source)) { source.forEach(function (item, i) { if (has$1.call(target, i)) { const targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge$2(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { const value = source[key]; if (has$1.call(acc, key)) { acc[key] = merge$2(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); } utils$5.merge = merge$2; function assign_single_source(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); } utils$5.assign_single_source = assign_single_source; function decode(str, _, charset) { const strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } } utils$5.decode = decode; const limit = 1024; const encode = (str, _defaultEncoder, charset, _kind, format) => { // This code was originally written by Brian White for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } let string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } let out = ''; for (let j = 0; j < string.length; j += limit) { const segment = string.length >= limit ? string.slice(j, j + limit) : string; const arr = []; for (let i = 0; i < segment.length; ++i) { let c = segment.charCodeAt(i); if (c === 0x2d || // - c === 0x2e || // . c === 0x5f || // _ c === 0x7e || // ~ (c >= 0x30 && c <= 0x39) || // 0-9 (c >= 0x41 && c <= 0x5a) || // a-z (c >= 0x61 && c <= 0x7a) || // A-Z (format === formats_1$1.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) ) { arr[arr.length] = segment.charAt(i); continue; } if (c < 0x80) { arr[arr.length] = hex_table[c]; continue; } if (c < 0x800) { arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)]; continue; } if (c < 0xd800 || c >= 0xe000) { arr[arr.length] = hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; continue; } i += 1; c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); arr[arr.length] = hex_table[0xf0 | (c >> 18)] + hex_table[0x80 | ((c >> 12) & 0x3f)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; } out += arr.join(''); } return out; }; utils$5.encode = encode; function compact(value) { const queue = [{ obj: { o: value }, prop: 'o' }]; const refs = []; for (let i = 0; i < queue.length; ++i) { const item = queue[i]; // @ts-ignore const obj = item.obj[item.prop]; const keys = Object.keys(obj); for (let j = 0; j < keys.length; ++j) { const key = keys[j]; const val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compact_queue(queue); return value; } utils$5.compact = compact; function is_regexp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; } utils$5.is_regexp = is_regexp; function is_buffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); } utils$5.is_buffer = is_buffer; function combine(a, b) { return [].concat(a, b); } utils$5.combine = combine; function maybe_map(val, fn) { if (is_array$1(val)) { const mapped = []; for (let i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); } utils$5.maybe_map = maybe_map; Object.defineProperty(stringify$2, "__esModule", { value: true }); stringify$2.stringify = void 0; const utils_1 = utils$5; const formats_1 = formats; const has = Object.prototype.hasOwnProperty; const array_prefix_generators = { brackets(prefix) { return String(prefix) + '[]'; }, comma: 'comma', indices(prefix, key) { return String(prefix) + '[' + key + ']'; }, repeat(prefix) { return String(prefix); }, }; const is_array = Array.isArray; const push = Array.prototype.push; const push_to_array = function (arr, value_or_array) { push.apply(arr, is_array(value_or_array) ? value_or_array : [value_or_array]); }; const to_ISO = Date.prototype.toISOString; const defaults$1 = { addQueryPrefix: false, allowDots: false, allowEmptyArrays: false, arrayFormat: 'indices', charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encodeDotInKeys: false, encoder: utils_1.encode, encodeValuesOnly: false, format: formats_1.default_format, formatter: formats_1.formatters[formats_1.default_format], /** @deprecated */ indices: false, serializeDate(date) { return to_ISO.call(date); }, skipNulls: false, strictNullHandling: false, }; function is_non_nullish_primitive(v) { return (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'); } const sentinel = {}; function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { let obj = object; let tmp_sc = sideChannel; let step = 0; let find_flag = false; while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { // Where object last appeared in the ref tree const pos = tmp_sc.get(object); step += 1; if (typeof pos !== 'undefined') { if (pos === step) { throw new RangeError('Cyclic object value'); } else { find_flag = true; // Break while } } if (typeof tmp_sc.get(sentinel) === 'undefined') { step = 0; } } if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate?.(obj); } else if (generateArrayPrefix === 'comma' && is_array(obj)) { obj = (0, utils_1.maybe_map)(obj, function (value) { if (value instanceof Date) { return serializeDate?.(value); } return value; }); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? // @ts-expect-error encoder(prefix, defaults$1.encoder, charset, 'key', format) : prefix; } obj = ''; } if (is_non_nullish_primitive(obj) || (0, utils_1.is_buffer)(obj)) { if (encoder) { const key_value = encodeValuesOnly ? prefix // @ts-expect-error : encoder(prefix, defaults$1.encoder, charset, 'key', format); return [ formatter?.(key_value) + '=' + // @ts-expect-error formatter?.(encoder(obj, defaults$1.encoder, charset, 'value', format)), ]; } return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; } const values = []; if (typeof obj === 'undefined') { return values; } let obj_keys; if (generateArrayPrefix === 'comma' && is_array(obj)) { // we need to join elements in if (encodeValuesOnly && encoder) { // @ts-expect-error values only obj = (0, utils_1.maybe_map)(obj, encoder); } obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } else if (is_array(filter)) { obj_keys = filter; } else { const keys = Object.keys(obj); obj_keys = sort ? keys.sort(sort) : keys; } const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); const adjusted_prefix = commaRoundTrip && is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; if (allowEmptyArrays && is_array(obj) && obj.length === 0) { return adjusted_prefix + '[]'; } for (let j = 0; j < obj_keys.length; ++j) { const key = obj_keys[j]; const value = // @ts-ignore typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; if (skipNulls && value === null) { continue; } // @ts-ignore const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; const key_prefix = is_array(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); sideChannel.set(object, step); const valueSideChannel = new WeakMap(); valueSideChannel.set(sentinel, sideChannel); push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, // @ts-ignore generateArrayPrefix === 'comma' && encodeValuesOnly && is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); } return values; } function normalize_stringify_options(opts = defaults$1) { if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); } if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); } if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } const charset = opts.charset || defaults$1.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } let format = formats_1.default_format; if (typeof opts.format !== 'undefined') { if (!has.call(formats_1.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } const formatter = formats_1.formatters[format]; let filter = defaults$1.filter; if (typeof opts.filter === 'function' || is_array(opts.filter)) { filter = opts.filter; } let arrayFormat; if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { arrayFormat = opts.arrayFormat; } else if ('indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = defaults$1.arrayFormat; } if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); } const allowDots = typeof opts.allowDots === 'undefined' ? !!opts.encodeDotInKeys === true ? true : defaults$1.allowDots : !!opts.allowDots; return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults$1.addQueryPrefix, // @ts-ignore allowDots: allowDots, allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults$1.allowEmptyArrays, arrayFormat: arrayFormat, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults$1.charsetSentinel, commaRoundTrip: !!opts.commaRoundTrip, delimiter: typeof opts.delimiter === 'undefined' ? defaults$1.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults$1.encode, encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults$1.encodeDotInKeys, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults$1.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults$1.encodeValuesOnly, filter: filter, format: format, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults$1.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults$1.skipNulls, // @ts-ignore sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults$1.strictNullHandling, }; } function stringify$1(object, opts = {}) { let obj = object; const options = normalize_stringify_options(opts); let obj_keys; let filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (is_array(options.filter)) { filter = options.filter; obj_keys = filter; } const keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; if (!obj_keys) { obj_keys = Object.keys(obj); } if (options.sort) { obj_keys.sort(options.sort); } const sideChannel = new WeakMap(); for (let i = 0; i < obj_keys.length; ++i) { const key = obj_keys[i]; if (options.skipNulls && obj[key] === null) { continue; } push_to_array(keys, inner_stringify(obj[key], key, // @ts-expect-error generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); } const joined = keys.join(options.delimiter); let prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('✓') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; } stringify$2.stringify = stringify$1; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.formats = exports.stringify = void 0; const formats_1 = formats; const formats$1 = { formatters: formats_1.formatters, RFC1738: formats_1.RFC1738, RFC3986: formats_1.RFC3986, default: formats_1.default_format, }; exports.formats = formats$1; var stringify_1 = stringify$2; Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return stringify_1.stringify; } }); } (qs)); var core$2 = {}; var version$1 = {}; Object.defineProperty(version$1, "__esModule", { value: true }); version$1.VERSION = void 0; version$1.VERSION = '4.70.1'; // x-release-please-version var streaming = {}; var _shims = {}; let auto = false; let kind = undefined; let fetch$1 = undefined; let Request$1 = undefined; let Response$1 = undefined; let Headers$1 = undefined; let FormData$1 = undefined; let Blob$1 = undefined; let File$1 = undefined; let ReadableStream$1 = undefined; let getMultipartRequestOptions = undefined; let getDefaultAgent = undefined; let fileFromPath = undefined; let isFsReadStream = undefined; function setShims(shims, options = { auto: false }) { if (auto) { throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); } if (kind) { throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``); } auto = options.auto; kind = shims.kind; fetch$1 = shims.fetch; Request$1 = shims.Request; Response$1 = shims.Response; Headers$1 = shims.Headers; FormData$1 = shims.FormData; Blob$1 = shims.Blob; File$1 = shims.File; ReadableStream$1 = shims.ReadableStream; getMultipartRequestOptions = shims.getMultipartRequestOptions; getDefaultAgent = shims.getDefaultAgent; fileFromPath = shims.fileFromPath; isFsReadStream = shims.isFsReadStream; } var registry = /*#__PURE__*/Object.freeze({ __proto__: null, get Blob () { return Blob$1; }, get File () { return File$1; }, get FormData () { return FormData$1; }, get Headers () { return Headers$1; }, get ReadableStream () { return ReadableStream$1; }, get Request () { return Request$1; }, get Response () { return Response$1; }, get auto () { return auto; }, get fetch () { return fetch$1; }, get fileFromPath () { return fileFromPath; }, get getDefaultAgent () { return getDefaultAgent; }, get getMultipartRequestOptions () { return getMultipartRequestOptions; }, get isFsReadStream () { return isFsReadStream; }, get kind () { return kind; }, setShims: setShims }); var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(registry); var runtime = {}; var webRuntime = {}; var MultipartBody$1 = {}; Object.defineProperty(MultipartBody$1, "__esModule", { value: true }); MultipartBody$1.MultipartBody = void 0; /** * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ class MultipartBody { constructor(body) { this.body = body; } get [Symbol.toStringTag]() { return 'MultipartBody'; } } MultipartBody$1.MultipartBody = MultipartBody; Object.defineProperty(webRuntime, "__esModule", { value: true }); webRuntime.getRuntime = void 0; /** * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ const MultipartBody_1 = MultipartBody$1; function getRuntime({ manuallyImported } = {}) { const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import … from 'openai'\`: - \`import 'openai/shims/node'\` (if you're running on Node) - \`import 'openai/shims/web'\` (otherwise) `; let _fetch, _Request, _Response, _Headers; try { // @ts-ignore _fetch = fetch; // @ts-ignore _Request = Request; // @ts-ignore _Response = Response; // @ts-ignore _Headers = Headers; } catch (error) { throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); } return { kind: 'web', fetch: _fetch, Request: _Request, Response: _Response, Headers: _Headers, FormData: // @ts-ignore typeof FormData !== 'undefined' ? FormData : (class FormData { // @ts-ignore constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); } }), Blob: typeof Blob !== 'undefined' ? Blob : (class Blob { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); } }), File: // @ts-ignore typeof File !== 'undefined' ? File : (class File { // @ts-ignore constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); } }), ReadableStream: // @ts-ignore typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream { // @ts-ignore constructor() { throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); } }), getMultipartRequestOptions: async ( // @ts-ignore form, opts) => ({ ...opts, body: new MultipartBody_1.MultipartBody(form), }), getDefaultAgent: (url) => undefined, fileFromPath: () => { throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads'); }, isFsReadStream: (value) => false, }; } webRuntime.getRuntime = getRuntime; (function (exports) { var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__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 }); /** * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ __exportStar(webRuntime, exports); } (runtime)); /** * Disclaimer: modules in _shims aren't intended to be imported by SDK users. */ (function (exports) { const shims = require$$0$2; const auto = runtime; if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); for (const property of Object.keys(shims)) { Object.defineProperty(exports, property, { get() { return shims[property]; }, }); } } (_shims)); var error$1 = {}; var hasRequiredError; function requireError () { if (hasRequiredError) return error$1; hasRequiredError = 1; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(error$1, "__esModule", { value: true }); error$1.ContentFilterFinishReasonError = error$1.LengthFinishReasonError = error$1.InternalServerError = error$1.RateLimitError = error$1.UnprocessableEntityError = error$1.ConflictError = error$1.NotFoundError = error$1.PermissionDeniedError = error$1.AuthenticationError = error$1.BadRequestError = error$1.APIConnectionTimeoutError = error$1.APIConnectionError = error$1.APIUserAbortError = error$1.APIError = error$1.OpenAIError = void 0; const core_1 = requireCore$1(); class OpenAIError extends Error { } error$1.OpenAIError = OpenAIError; class APIError extends OpenAIError { constructor(status, error, message, headers) { super(`${APIError.makeMessage(status, error, message)}`); this.status = status; this.headers = headers; this.request_id = headers?.['x-request-id']; const data = error; this.error = data; this.code = data?.['code']; this.param = data?.['param']; this.type = data?.['type']; } static makeMessage(status, error, message) { const msg = error?.message ? typeof error.message === 'string' ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; if (status && msg) { return `${status} ${msg}`; } if (status) { return `${status} status code (no body)`; } if (msg) { return msg; } return '(no status code or body)'; } static generate(status, errorResponse, message, headers) { if (!status) { return new APIConnectionError({ message, cause: (0, core_1.castToError)(errorResponse) }); } const error = errorResponse?.['error']; if (status === 400) { return new BadRequestError(status, error, message, headers); } if (status === 401) { return new AuthenticationError(status, error, message, headers); } if (status === 403) { return new PermissionDeniedError(status, error, message, headers); } if (status === 404) { return new NotFoundError(status, error, message, headers); } if (status === 409) { return new ConflictError(status, error, message, headers); } if (status === 422) { return new UnprocessableEntityError(status, error, message, headers); } if (status === 429) { return new RateLimitError(status, error, message, headers); } if (status >= 500) { return new InternalServerError(status, error, message, headers); } return new APIError(status, error, message, headers); } } error$1.APIError = APIError; class APIUserAbortError extends APIError { constructor({ message } = {}) { super(undefined, undefined, message || 'Request was aborted.', undefined); this.status = undefined; } } error$1.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; } } error$1.APIConnectionError = APIConnectionError; class APIConnectionTimeoutError extends APIConnectionError { constructor({ message } = {}) { super({ message: message ?? 'Request timed out.' }); } } error$1.APIConnectionTimeoutError = APIConnectionTimeoutError; class BadRequestError extends APIError { constructor() { super(...arguments); this.status = 400; } } error$1.BadRequestError = BadRequestError; class AuthenticationError extends APIError { constructor() { super(...arguments); this.status = 401; } } error$1.AuthenticationError = AuthenticationError; class PermissionDeniedError extends APIError { constructor() { super(...arguments); this.status = 403; } } error$1.PermissionDeniedError = PermissionDeniedError; class NotFoundError extends APIError { constructor() { super(...arguments); this.status = 404; } } error$1.NotFoundError = NotFoundError; class ConflictError extends APIError { constructor() { super(...arguments); this.status = 409; } } error$1.ConflictError = ConflictError; class UnprocessableEntityError extends APIError { constructor() { super(...arguments); this.status = 422; } } error$1.UnprocessableEntityError = UnprocessableEntityError; class RateLimitError extends APIError { constructor() { super(...arguments); this.status = 429; } } error$1.RateLimitError = RateLimitError; class InternalServerError extends APIError { } error$1.InternalServerError = InternalServerError; class LengthFinishReasonError extends OpenAIError { constructor() { super(`Could not parse response content as the length limit was reached`); } } error$1.LengthFinishReasonError = LengthFinishReasonError; class ContentFilterFinishReasonError extends OpenAIError { constructor() { super(`Could not parse response content as the request was rejected by the content filter`); } } error$1.ContentFilterFinishReasonError = ContentFilterFinishReasonError; return error$1; } var line = {}; var hasRequiredLine; function requireLine () { if (hasRequiredLine) return line; hasRequiredLine = 1; Object.defineProperty(line, "__esModule", { value: true }); line.LineDecoder = void 0; const error_1 = requireError(); /** * 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 there is a trailing new line then the last entry will be an empty // string which we don't care about if (trailingNewline) { lines.pop(); } if (lines.length === 1 && !trailingNewline) { this.buffer.push(lines[0]); return []; } if (this.buffer.length > 0) { lines = [this.buffer.join('') + lines[0], ...lines.slice(1)]; this.buffer = []; } if (!trailingNewline) { this.buffer = [lines.pop() || '']; } return lines; } decodeText(bytes) { if (bytes == null) return ''; if (typeof bytes === 'string') return bytes; // Node: if (typeof Buffer !== 'undefined') { if (bytes instanceof Buffer) { return bytes.toString(); } if (bytes instanceof Uint8Array) { return Buffer.from(bytes).toString(); } throw new error_1.OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); } // Browser if (typeof TextDecoder !== 'undefined') { if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8')); return this.textDecoder.decode(bytes); } throw new error_1.OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); } throw new error_1.OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); } flush() { if (!this.buffer.length && !this.trailingCR) { return []; } const lines = [this.buffer.join('')]; this.buffer = []; this.trailingCR = false; return lines; } } line.LineDecoder = LineDecoder; // prettier-ignore LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; return line; } var hasRequiredStreaming; function requireStreaming () { if (hasRequiredStreaming) return streaming; hasRequiredStreaming = 1; Object.defineProperty(streaming, "__esModule", { value: true }); streaming.readableStreamAsyncIterable = streaming._decodeChunks = streaming._iterSSEMessages = streaming.Stream = void 0; const index_1 = _shims; const error_1 = requireError(); const line_1 = requireLine(); const error_2 = requireError(); class Stream { constructor(iterator, controller) { this.iterator = iterator; this.controller = controller; } static fromSSEResponse(response, controller) { let consumed = false; async function* iterator() { if (consumed) { throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); } consumed = true; let done = false; try { for await (const sse of _iterSSEMessages(response, controller)) { if (done) continue; if (sse.data.startsWith('[DONE]')) { done = true; continue; } if (sse.event === null) { let data; try { data = JSON.parse(sse.data); } catch (e) { console.error(`Could not parse message into JSON:`, sse.data); console.error(`From chunk:`, sse.raw); throw e; } if (data && data.error) { throw new error_2.APIError(undefined, data.error, undefined, undefined); } yield data; } else { let data; try { data = JSON.parse(sse.data); } catch (e) { console.error(`Could not parse message into JSON:`, sse.data); console.error(`From chunk:`, sse.raw); throw e; } // TODO: Is this where the error should be thrown? if (sse.event == 'error') { throw new error_2.APIError(undefined, data.error, data.message, undefined); } yield { event: sse.event, data: data }; } } 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) controller.abort(); } } return new Stream(iterator, controller); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ static fromReadableStream(readableStream, controller) { let consumed = false; async function* iterLines() { const lineDecoder = new line_1.LineDecoder(); const iter = readableStreamAsyncIterable(readableStream); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { yield line; } } for (const line of lineDecoder.flush()) { yield line; } } async function* iterator() { if (consumed) { throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); } consumed = true; let done = false; try { for await (const line of iterLines()) { if (done) continue; if (line) yield JSON.parse(line); } 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) controller.abort(); } } return new Stream(iterator, controller); } [Symbol.asyncIterator]() { return this.iterator(); } /** * Splits the stream into two streams which can be * independently read from at different speeds. */ tee() { const left = []; const right = []; const iterator = this.iterator(); const teeIterator = (queue) => { return { next: () => { if (queue.length === 0) { const result = iterator.next(); left.push(result); right.push(result); } return queue.shift(); }, }; }; return [ new Stream(() => teeIterator(left), this.controller), new Stream(() => teeIterator(right), this.controller), ]; } /** * Converts this stream to a newline-separated ReadableStream of * JSON stringified values in the stream * which can be turned back into a Stream with `Stream.fromReadableStream()`. */ toReadableStream() { const self = this; let iter; const encoder = new TextEncoder(); return new index_1.ReadableStream({ async start() { iter = self[Symbol.asyncIterator](); }, async pull(ctrl) { try { const { value, done } = await iter.next(); if (done) return ctrl.close(); const bytes = encoder.encode(JSON.stringify(value) + '\n'); ctrl.enqueue(bytes); } catch (err) { ctrl.error(err); } }, async cancel() { await iter.return?.(); }, }); } } streaming.Stream = Stream; async function* _iterSSEMessages(response, controller) { if (!response.body) { controller.abort(); throw new error_1.OpenAIError(`Attempted to iterate over a response with no body`); } const sseDecoder = new SSEDecoder(); const lineDecoder = new line_1.LineDecoder(); const iter = readableStreamAsyncIterable(response.body); for await (const sseChunk of iterSSEChunks(iter)) { for (const line of lineDecoder.decode(sseChunk)) { const sse = sseDecoder.decode(line); if (sse) yield sse; } } for (const line of lineDecoder.flush()) { const sse = sseDecoder.decode(line); if (sse) yield sse; } } streaming._iterSSEMessages = _iterSSEMessages; /** * Given an async iterable iterator, iterates over it and yields full * SSE chunks, i.e. yields when a double new-line is encountered. */ async function* iterSSEChunks(iterator) { let data = new Uint8Array(); for await (const chunk of iterator) { if (chunk == null) { continue; } const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk; let newData = new Uint8Array(data.length + binaryChunk.length); newData.set(data); newData.set(binaryChunk, data.length); data = newData; let patternIndex; while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { yield data.slice(0, patternIndex); data = data.slice(patternIndex); } } if (data.length > 0) { yield data; } } function findDoubleNewlineIndex(buffer) { // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) // and returns the index right after the first occurrence of any pattern, // or -1 if none of the patterns are found. const newline = 0x0a; // \n const carriage = 0x0d; // \r for (let i = 0; i < buffer.length - 2; i++) { if (buffer[i] === newline && buffer[i + 1] === newline) { // \n\n return i + 2; } if (buffer[i] === carriage && buffer[i + 1] === carriage) { // \r\r return i + 2; } if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) { // \r\n\r\n return i + 4; } } return -1; } 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; } } /** This is an internal helper function that's just used for testing */ function _decodeChunks(chunks) { const decoder = new line_1.LineDecoder(); const lines = []; for (const chunk of chunks) { lines.push(...decoder.decode(chunk)); } return lines; } streaming._decodeChunks = _decodeChunks; 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?.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; }, }; } streaming.readableStreamAsyncIterable = readableStreamAsyncIterable; return streaming; } var uploads$1 = {}; (function (exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = exports.isMultipartBody = exports.toFile = exports.isUploadable = exports.isBlobLike = exports.isFileLike = exports.isResponseLike = exports.fileFromPath = void 0; const index_1 = _shims; var index_2 = _shims; Object.defineProperty(exports, "fileFromPath", { enumerable: true, get: function () { return index_2.fileFromPath; } }); 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; /** * 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'; exports.isBlobLike = isBlobLike; const isUploadable = (value) => { return (0, exports.isFileLike)(value) || (0, exports.isResponseLike)(value) || (0, index_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) { // If it's a promise, resolve it. value = await value; // If we've been given a `File` we don't need to do anything if ((0, exports.isFileLike)(value)) { return value; } if ((0, exports.isResponseLike)(value)) { const blob = await value.blob(); name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file'); // we need to convert the `Blob` into an array buffer because the `Blob` class // that `node-fetch` defines is incompatible with the web standard which results // in `new File` interpreting it as a string instead of binary data. const data = (0, exports.isBlobLike)(blob) ? [(await blob.arrayBuffer())] : [blob]; return new index_1.File(data, name, options); } const bits = await getBytes(value); name || (name = getName(value) ?? 'unknown_file'); if (!options?.type) { const type = bits[0]?.type; if (typeof type === 'string') { options = { ...options, type }; } } return new index_1.File(bits, name, options); } exports.toFile = toFile; async function getBytes(value) { let parts = []; if (typeof value === 'string' || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. value instanceof ArrayBuffer) { parts.push(value); } else if ((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: ${value?.constructor ?.name}; props: ${propsForError(value)}`); } return parts; } function propsForError(value) { const props = Object.getOwnPropertyNames(value); return `[${props.map((p) => `"${p}"`).join(', ')}]`; } function getName(value) { return (getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream getStringFromMaybeBuffer(value.path)?.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'; const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; exports.isMultipartBody = isMultipartBody; /** * 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 (0, exports.createForm)(opts.body); return (0, index_1.getMultipartRequestOptions)(form, opts); }; exports.maybeMultipartFormRequestOptions = maybeMultipartFormRequestOptions; const multipartFormRequestOptions = async (opts) => { const form = await (0, exports.createForm)(opts.body); return (0, index_1.getMultipartRequestOptions)(form, opts); }; exports.multipartFormRequestOptions = multipartFormRequestOptions; const createForm = async (body) => { const form = new index_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`); } }; } (uploads$1)); var hasRequiredCore$1; function requireCore$1 () { if (hasRequiredCore$1) return core$2; hasRequiredCore$1 = 1; (function (exports) { var __classPrivateFieldSet = (commonjsGlobal && commonjsGlobal.__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 = (commonjsGlobal && commonjsGlobal.__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.isObj = exports.toBase64 = exports.getHeader = exports.getRequiredHeader = 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.sleep = exports.safeJSON = exports.isRequestOptions = exports.createResponseHeaders = exports.PagePromise = exports.AbstractPage = exports.APIClient = exports.APIPromise = exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = void 0; const version_1 = version$1; const streaming_1 = requireStreaming(); const error_1 = requireError(); const index_1 = _shims; const uploads_1 = uploads$1; var uploads_2 = uploads$1; 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; } }); async function defaultParseResponse(props) { const { response } = props; if (props.options.stream) { debug('response', response.status, response.url, response.headers, response.body); // 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` if (props.options.__streamClass) { return props.options.__streamClass.fromSSEResponse(response, props.controller); } return streaming_1.Stream.fromSSEResponse(response, props.controller); } // fetch refuses to read the body when the status code is 204. if (response.status === 204) { return null; } if (props.options.__binaryResponse) { return response; } const contentType = response.headers.get('content-type'); const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json'); if (isJSON) { const json = await response.json(); debug('response', response.status, response.url, response.headers, json); return _addRequestID(json, response); } const text = await response.text(); debug('response', response.status, response.url, response.headers, text); // TODO handle blob, arraybuffer, other content types, etc. return text; } function _addRequestID(value, response) { if (!value || typeof value !== 'object' || Array.isArray(value)) { return value; } return Object.defineProperty(value, '_request_id', { value: response.headers.get('x-request-id'), enumerable: false, }); } /** * 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) => _addRequestID(transform(await this.parseResponse(props), props), props.response)); } /** * Gets the raw `Response` instance instead of parsing the response * data. * * If you want to parse the response body but still get the `Response` * instance, you can use {@link withResponse()}. * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */ asResponse() { return this.responsePromise.then((p) => p.response); } /** * Gets the parsed response data, the raw `Response` instance and the ID of the request, * returned via the X-Request-ID header which is useful for debugging requests and reporting * issues to OpenAI. * * If you just want to get the raw `Response` instance without parsing it, * you can use {@link asResponse()}. * * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */ async withResponse() { const [data, response] = await Promise.all([this.parse(), this.asResponse()]); return { data, response, request_id: response.headers.get('x-request-id') }; } parse() { if (!this.parsedPromise) { this.parsedPromise = this.responsePromise.then(this.parseResponse); } return this.parsedPromise; } then(onfulfilled, onrejected) { return this.parse().then(onfulfilled, onrejected); } catch(onrejected) { return this.parse().catch(onrejected); } finally(onfinally) { return this.parse().finally(onfinally); } } exports.APIPromise = APIPromise; class APIClient { constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes httpAgent, fetch: overridenFetch, }) { this.baseURL = baseURL; this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); this.timeout = validatePositiveInteger('timeout', timeout); this.httpAgent = httpAgent; this.fetch = overridenFetch ?? index_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(async (opts) => { const body = opts && (0, uploads_1.isBlobLike)(opts?.body) ? new DataView(await opts.body.arrayBuffer()) : opts?.body instanceof DataView ? opts.body : opts?.body instanceof ArrayBuffer ? new DataView(opts.body) : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer) : opts?.body; return { method, path, ...opts, body }; })); } 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(); } } else if (ArrayBuffer.isView(body)) { return body.byteLength.toString(); } return null; } buildRequest(options, { retryCount = 0 } = {}) { const { method, path, query, headers: headers = {} } = options; const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ? options.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 = options.timeout ?? this.timeout; const httpAgent = options.httpAgent ?? this.httpAgent ?? (0, index_1.getDefaultAgent)(url); const minAgentTimeout = timeout + 1000; if (typeof httpAgent?.options?.timeout === 'number' && minAgentTimeout > (httpAgent.options.timeout ?? 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 = this.buildHeaders({ options, headers, contentLength, retryCount }); 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: options.signal ?? null, }; return { req, url, timeout }; } buildHeaders({ options, headers, contentLength, retryCount, }) { const reqHeaders = {}; if (contentLength) { reqHeaders['content-length'] = contentLength; } const defaultHeaders = this.defaultHeaders(options); applyHeadersMut(reqHeaders, defaultHeaders); applyHeadersMut(reqHeaders, headers); // let builtin fetch set the Content-Type for multipart bodies if ((0, uploads_1.isMultipartBody)(options.body) && index_1.kind !== 'node') { delete reqHeaders['content-type']; } // Don't set the retry count header if it was already set or removed through default headers or by the // caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to // account for the removal case. if ((0, exports.getHeader)(defaultHeaders, 'x-stainless-retry-count') === undefined && (0, exports.getHeader)(headers, 'x-stainless-retry-count') === undefined) { reqHeaders['x-stainless-retry-count'] = String(retryCount); } this.validateHeaders(reqHeaders, headers); return reqHeaders; } /** * Used as a callback for mutating the given `FinalRequestOptions` object. */ async prepareOptions(options) { } /** * Used as a callback for mutating the given `RequestInit` object. * * This is useful for cases where you want to add certain headers based off of * the request properties, e.g. `method` or `url`. */ async prepareRequest(request, { url, options }) { } parseHeaders(headers) { return (!headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers }); } makeStatusError(status, error, message, headers) { return error_1.APIError.generate(status, error, message, headers); } request(options, remainingRetries = null) { return new APIPromise(this.makeRequest(options, remainingRetries)); } async makeRequest(optionsInput, retriesRemaining) { const options = await optionsInput; const maxRetries = options.maxRetries ?? this.maxRetries; if (retriesRemaining == null) { retriesRemaining = maxRetries; } await this.prepareOptions(options); const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); await this.prepareRequest(req, { url, options }); debug('request', url, options, req.headers); if (options.signal?.aborted) { throw new error_1.APIUserAbortError(); } const controller = new AbortController(); const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError); if (response instanceof Error) { if (options.signal?.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)) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); return this.retryRequest(options, retriesRemaining, responseHeaders); } const errText = await response.text().catch((e) => (0, exports.castToError)(e).message); const errJSON = (0, exports.safeJSON)(errText); const errMessage = errJSON ? undefined : errText; const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); throw err; } return { response, options, controller }; } requestAPIList(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 (typeof query === 'object' && query && !Array.isArray(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_1.OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); }) .join('&'); } async fetchWithTimeout(url, init, ms, controller) { const { signal, ...options } = init || {}; if (signal) signal.addEventListener('abort', () => controller.abort()); const timeout = setTimeout(() => controller.abort(), ms); return (this.getRequestClient() // use undefined this binding; fetch errors if bound to something else in browser/cloudflare .fetch.call(undefined, 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 request timeouts. if (response.status === 408) return true; // 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) { let timeoutMillis; // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; if (retryAfterMillisHeader) { const timeoutMs = parseFloat(retryAfterMillisHeader); if (!Number.isNaN(timeoutMs)) { timeoutMillis = timeoutMs; } } // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After const retryAfterHeader = responseHeaders?.['retry-after']; if (retryAfterHeader && !timeoutMillis) { const timeoutSeconds = parseFloat(retryAfterHeader); if (!Number.isNaN(timeoutSeconds)) { timeoutMillis = timeoutSeconds * 1000; } else { timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } // If the API asks us to wait a certain amount of time (and it's a reasonable amount), // just do what it says, but otherwise calculate a default if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { const maxRetries = options.maxRetries ?? this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } await (0, exports.sleep)(timeoutMillis); return this.makeRequest(options, retriesRemaining - 1); } calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { const initialRetryDelay = 0.5; const maxRetryDelay = 8.0; const numRetries = maxRetries - retriesRemaining; // Apply exponential backoff, but not more than the max. const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); // Apply some jitter, take up to at most 25 percent of the retry time. const jitter = 1 - Math.random() * 0.25; return sleepSeconds * jitter * 1000; } getUserAgent() { return `${this.constructor.name}/JS ${version_1.VERSION}`; } } exports.APIClient = APIClient; 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_1.OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); } const nextOptions = { ...this.options }; if ('params' in nextInfo && typeof nextOptions.query === 'object') { nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; } else if ('url' in nextInfo) { const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; for (const [key, value] of params) { nextInfo.url.searchParams.set(key, value); } nextOptions.query = undefined; nextOptions.path = nextInfo.url.toString(); } 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; } } async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { for await (const page of this.iterPages()) { for (const item of page.getPaginatedItems()) { yield item; } } } } 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; } } } 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, __binaryRequest: true, __binaryResponse: true, __streamClass: 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': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', }; } 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(undefined); 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 ?? (_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)); exports.sleep = sleep; const validatePositiveInteger = (name, n) => { if (typeof n !== 'number' || !Number.isInteger(n)) { throw new error_1.OpenAIError(`${name} must be an integer`); } if (n < 0) { throw new error_1.OpenAIError(`${name} must be a positive integer`); } return n; }; const castToError = (err) => { if (err instanceof Error) return err; if (typeof err === 'object' && err !== null) { try { return new Error(JSON.stringify(err)); } catch { } } return new Error(err); }; exports.castToError = castToError; const ensurePresent = (value) => { if (value == null) throw new error_1.OpenAIError(`Expected a value to be given but received ${value} instead.`); return value; }; exports.ensurePresent = ensurePresent; /** * Read an environment variable. * * Trims beginning and trailing whitespace. * * Will return undefined if the environment variable doesn't exist or cannot be accessed. */ const readEnv = (env) => { if (typeof process !== 'undefined') { return process.env?.[env]?.trim() ?? undefined; } if (typeof Deno !== 'undefined') { return Deno.env?.get?.(env)?.trim(); } 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_1.OpenAIError(`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_1.OpenAIError(`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; /** * Copies headers from "newHeaders" onto "targetHeaders", * using lower-case for all properties, * ignoring any keys with undefined values, * and deleting any keys with null values. */ function applyHeadersMut(targetHeaders, newHeaders) { for (const k in newHeaders) { if (!hasOwn(newHeaders, k)) continue; const lowerKey = k.toLowerCase(); if (!lowerKey) continue; const val = newHeaders[k]; if (val === null) { delete targetHeaders[lowerKey]; } else if (val !== undefined) { targetHeaders[lowerKey] = val; } } } 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?.get === 'function'; }; exports.isHeadersProtocol = isHeadersProtocol; const getRequiredHeader = (headers, header) => { const foundHeader = (0, exports.getHeader)(headers, header); if (foundHeader === undefined) { throw new Error(`Could not find ${header} header`); } return foundHeader; }; exports.getRequiredHeader = getRequiredHeader; const getHeader = (headers, header) => { const lowerCasedHeader = header.toLowerCase(); if ((0, exports.isHeadersProtocol)(headers)) { // to deal with the case where the header looks like Stainless-Event-Id const intercapsHeader = header[0]?.toUpperCase() + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { const value = headers.get(key); if (value) { return value; } } } for (const [key, value] of Object.entries(headers)) { if (key.toLowerCase() === lowerCasedHeader) { if (Array.isArray(value)) { if (value.length <= 1) return value[0]; console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); return value[0]; } return value; } } return undefined; }; 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_1.OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); }; exports.toBase64 = toBase64; function isObj(obj) { return obj != null && typeof obj === 'object' && !Array.isArray(obj); } exports.isObj = isObj; } (core$2)); return core$2; } var pagination = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(pagination, "__esModule", { value: true }); pagination.CursorPage = pagination.Page = void 0; const core_1$b = requireCore$1(); /** * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ class Page extends core_1$b.AbstractPage { constructor(client, response, body, options) { super(client, response, body, options); this.data = body.data || []; this.object = body.object; } getPaginatedItems() { return this.data ?? []; } // @deprecated Please use `nextPageInfo()` instead /** * This page represents a response that isn't actually paginated at the API level * so there will never be any next page params. */ nextPageParams() { return null; } nextPageInfo() { return null; } } pagination.Page = Page; class CursorPage extends core_1$b.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() { const data = this.getPaginatedItems(); if (!data.length) { return null; } const id = data[data.length - 1]?.id; if (!id) { return null; } return { params: { after: id } }; } } pagination.CursorPage = CursorPage; var resources = {}; var chat$2 = {}; var chat$1 = {}; var resource = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(resource, "__esModule", { value: true }); resource.APIResource = void 0; class APIResource { constructor(client) { this._client = client; } } resource.APIResource = APIResource; var completions$2 = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(completions$2, "__esModule", { value: true }); completions$2.Completions = void 0; const resource_1$p = resource; let Completions$1 = class Completions extends resource_1$p.APIResource { create(body, options) { return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); } }; completions$2.Completions = Completions$1; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$f = (commonjsGlobal && commonjsGlobal.__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$f = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$f = (commonjsGlobal && commonjsGlobal.__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$f(result, mod, k); __setModuleDefault$f(result, mod); return result; }; Object.defineProperty(chat$1, "__esModule", { value: true }); chat$1.Chat = void 0; const resource_1$o = resource; const CompletionsAPI = __importStar$f(completions$2); const completions_1 = completions$2; class Chat extends resource_1$o.APIResource { constructor() { super(...arguments); this.completions = new CompletionsAPI.Completions(this._client); } } chat$1.Chat = Chat; Chat.Completions = completions_1.Completions; (function (exports) { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(exports, "__esModule", { value: true }); exports.Completions = exports.Chat = void 0; var chat_1 = chat$1; Object.defineProperty(exports, "Chat", { enumerable: true, get: function () { return chat_1.Chat; } }); var completions_1 = completions$2; Object.defineProperty(exports, "Completions", { enumerable: true, get: function () { return completions_1.Completions; } }); } (chat$2)); var shared = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(shared, "__esModule", { value: true }); var audio$1 = {}; var speech = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(speech, "__esModule", { value: true }); speech.Speech = void 0; const resource_1$n = resource; class Speech extends resource_1$n.APIResource { /** * Generates audio from the input text. */ create(body, options) { return this._client.post('/audio/speech', { body, ...options, __binaryResponse: true }); } } speech.Speech = Speech; var transcriptions = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$e = (commonjsGlobal && commonjsGlobal.__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$e = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$e = (commonjsGlobal && commonjsGlobal.__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$e(result, mod, k); __setModuleDefault$e(result, mod); return result; }; Object.defineProperty(transcriptions, "__esModule", { value: true }); transcriptions.Transcriptions = void 0; const resource_1$m = resource; const Core$5 = __importStar$e(requireCore$1()); class Transcriptions extends resource_1$m.APIResource { create(body, options) { return this._client.post('/audio/transcriptions', Core$5.multipartFormRequestOptions({ body, ...options })); } } transcriptions.Transcriptions = Transcriptions; var translations = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$d = (commonjsGlobal && commonjsGlobal.__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$d = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$d = (commonjsGlobal && commonjsGlobal.__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$d(result, mod, k); __setModuleDefault$d(result, mod); return result; }; Object.defineProperty(translations, "__esModule", { value: true }); translations.Translations = void 0; const resource_1$l = resource; const Core$4 = __importStar$d(requireCore$1()); class Translations extends resource_1$l.APIResource { create(body, options) { return this._client.post('/audio/translations', Core$4.multipartFormRequestOptions({ body, ...options })); } } translations.Translations = Translations; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$c = (commonjsGlobal && commonjsGlobal.__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$c = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$c = (commonjsGlobal && commonjsGlobal.__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$c(result, mod, k); __setModuleDefault$c(result, mod); return result; }; Object.defineProperty(audio$1, "__esModule", { value: true }); audio$1.Audio = void 0; const resource_1$k = resource; const SpeechAPI = __importStar$c(speech); const speech_1 = speech; const TranscriptionsAPI = __importStar$c(transcriptions); const transcriptions_1 = transcriptions; const TranslationsAPI = __importStar$c(translations); const translations_1 = translations; class Audio extends resource_1$k.APIResource { constructor() { super(...arguments); this.transcriptions = new TranscriptionsAPI.Transcriptions(this._client); this.translations = new TranslationsAPI.Translations(this._client); this.speech = new SpeechAPI.Speech(this._client); } } audio$1.Audio = Audio; Audio.Transcriptions = transcriptions_1.Transcriptions; Audio.Translations = translations_1.Translations; Audio.Speech = speech_1.Speech; var batches = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(batches, "__esModule", { value: true }); batches.BatchesPage = batches.Batches = void 0; const resource_1$j = resource; const core_1$a = requireCore$1(); const pagination_1$a = pagination; class Batches extends resource_1$j.APIResource { /** * Creates and executes a batch from an uploaded file of requests */ create(body, options) { return this._client.post('/batches', { body, ...options }); } /** * Retrieves a batch. */ retrieve(batchId, options) { return this._client.get(`/batches/${batchId}`, options); } list(query = {}, options) { if ((0, core_1$a.isRequestOptions)(query)) { return this.list({}, query); } return this._client.getAPIList('/batches', BatchesPage, { query, ...options }); } /** * Cancels an in-progress batch. The batch will be in status `cancelling` for up to * 10 minutes, before changing to `cancelled`, where it will have partial results * (if any) available in the output file. */ cancel(batchId, options) { return this._client.post(`/batches/${batchId}/cancel`, options); } } batches.Batches = Batches; class BatchesPage extends pagination_1$a.CursorPage { } batches.BatchesPage = BatchesPage; Batches.BatchesPage = BatchesPage; var beta = {}; var assistants = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(assistants, "__esModule", { value: true }); assistants.AssistantsPage = assistants.Assistants = void 0; const resource_1$i = resource; const core_1$9 = requireCore$1(); const pagination_1$9 = pagination; class Assistants extends resource_1$i.APIResource { /** * Create an assistant with a model and instructions. */ create(body, options) { return this._client.post('/assistants', { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Retrieves an assistant. */ retrieve(assistantId, options) { return this._client.get(`/assistants/${assistantId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Modifies an assistant. */ update(assistantId, body, options) { return this._client.post(`/assistants/${assistantId}`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } list(query = {}, options) { if ((0, core_1$9.isRequestOptions)(query)) { return this.list({}, query); } return this._client.getAPIList('/assistants', AssistantsPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Delete an assistant. */ del(assistantId, options) { return this._client.delete(`/assistants/${assistantId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } } assistants.Assistants = Assistants; class AssistantsPage extends pagination_1$9.CursorPage { } assistants.AssistantsPage = AssistantsPage; Assistants.AssistantsPage = AssistantsPage; var chat = {}; var completions$1 = {}; var ChatCompletionRunner$1 = {}; var AbstractChatCompletionRunner$1 = {}; var RunnableFunction = {}; Object.defineProperty(RunnableFunction, "__esModule", { value: true }); RunnableFunction.ParsingToolFunction = RunnableFunction.ParsingFunction = RunnableFunction.isRunnableFunctionWithParse = void 0; function isRunnableFunctionWithParse(fn) { return typeof fn.parse === 'function'; } RunnableFunction.isRunnableFunctionWithParse = isRunnableFunctionWithParse; /** * This is helper class for passing a `function` and `parse` where the `function` * argument type matches the `parse` return type. * * @deprecated - please use ParsingToolFunction instead. */ class ParsingFunction { constructor(input) { this.function = input.function; this.parse = input.parse; this.parameters = input.parameters; this.description = input.description; this.name = input.name; } } RunnableFunction.ParsingFunction = ParsingFunction; /** * This is helper class for passing a `function` and `parse` where the `function` * argument type matches the `parse` return type. */ class ParsingToolFunction { constructor(input) { this.type = 'function'; this.function = input; } } RunnableFunction.ParsingToolFunction = ParsingToolFunction; var chatCompletionUtils = {}; Object.defineProperty(chatCompletionUtils, "__esModule", { value: true }); chatCompletionUtils.isPresent = chatCompletionUtils.isToolMessage = chatCompletionUtils.isFunctionMessage = chatCompletionUtils.isAssistantMessage = void 0; const isAssistantMessage = (message) => { return message?.role === 'assistant'; }; chatCompletionUtils.isAssistantMessage = isAssistantMessage; const isFunctionMessage = (message) => { return message?.role === 'function'; }; chatCompletionUtils.isFunctionMessage = isFunctionMessage; const isToolMessage = (message) => { return message?.role === 'tool'; }; chatCompletionUtils.isToolMessage = isToolMessage; function isPresent(obj) { return obj != null; } chatCompletionUtils.isPresent = isPresent; var EventStream$1 = {}; var __classPrivateFieldSet$3 = (commonjsGlobal && commonjsGlobal.__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$4 = (commonjsGlobal && commonjsGlobal.__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 _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; Object.defineProperty(EventStream$1, "__esModule", { value: true }); EventStream$1.EventStream = void 0; const error_1$u = requireError(); class EventStream { constructor() { _EventStream_instances.add(this); this.controller = new AbortController(); _EventStream_connectedPromise.set(this, void 0); _EventStream_resolveConnectedPromise.set(this, () => { }); _EventStream_rejectConnectedPromise.set(this, () => { }); _EventStream_endPromise.set(this, void 0); _EventStream_resolveEndPromise.set(this, () => { }); _EventStream_rejectEndPromise.set(this, () => { }); _EventStream_listeners.set(this, {}); _EventStream_ended.set(this, false); _EventStream_errored.set(this, false); _EventStream_aborted.set(this, false); _EventStream_catchingPromiseCreated.set(this, false); __classPrivateFieldSet$3(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { __classPrivateFieldSet$3(this, _EventStream_resolveConnectedPromise, resolve, "f"); __classPrivateFieldSet$3(this, _EventStream_rejectConnectedPromise, reject, "f"); }), "f"); __classPrivateFieldSet$3(this, _EventStream_endPromise, new Promise((resolve, reject) => { __classPrivateFieldSet$3(this, _EventStream_resolveEndPromise, resolve, "f"); __classPrivateFieldSet$3(this, _EventStream_rejectEndPromise, reject, "f"); }), "f"); // Don't let these promises cause unhandled rejection errors. // we will manually cause an unhandled rejection error later // if the user hasn't registered any error listener or called // any promise-returning method. __classPrivateFieldGet$4(this, _EventStream_connectedPromise, "f").catch(() => { }); __classPrivateFieldGet$4(this, _EventStream_endPromise, "f").catch(() => { }); } _run(executor) { // Unfortunately if we call `executor()` immediately we get runtime errors about // references to `this` before the `super()` constructor call returns. setTimeout(() => { executor().then(() => { this._emitFinal(); this._emit('end'); }, __classPrivateFieldGet$4(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); }, 0); } _connected() { if (this.ended) return; __classPrivateFieldGet$4(this, _EventStream_resolveConnectedPromise, "f").call(this); this._emit('connect'); } get ended() { return __classPrivateFieldGet$4(this, _EventStream_ended, "f"); } get errored() { return __classPrivateFieldGet$4(this, _EventStream_errored, "f"); } get aborted() { return __classPrivateFieldGet$4(this, _EventStream_aborted, "f"); } abort() { this.controller.abort(); } /** * Adds the listener function to the end of the listeners array for the event. * No checks are made to see if the listener has already been added. Multiple calls passing * the same combination of event and listener will result in the listener being added, and * called, multiple times. * @returns this ChatCompletionStream, so that calls can be chained */ on(event, listener) { const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = []); listeners.push({ listener }); return this; } /** * Removes the specified listener from the listener array for the event. * off() will remove, at most, one instance of a listener from the listener array. If any single * listener has been added multiple times to the listener array for the specified event, then * off() must be called multiple times to remove each instance. * @returns this ChatCompletionStream, so that calls can be chained */ off(event, listener) { const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event]; if (!listeners) return this; const index = listeners.findIndex((l) => l.listener === listener); if (index >= 0) listeners.splice(index, 1); return this; } /** * Adds a one-time listener function for the event. The next time the event is triggered, * this listener is removed and then invoked. * @returns this ChatCompletionStream, so that calls can be chained */ once(event, listener) { const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = []); listeners.push({ listener, once: true }); return this; } /** * This is similar to `.once()`, but returns a Promise that resolves the next time * the event is triggered, instead of calling a listener callback. * @returns a Promise that resolves the next time given event is triggered, * or rejects if an error is emitted. (If you request the 'error' event, * returns a promise that resolves with the error). * * Example: * * const message = await stream.emitted('message') // rejects if the stream errors */ emitted(event) { return new Promise((resolve, reject) => { __classPrivateFieldSet$3(this, _EventStream_catchingPromiseCreated, true, "f"); if (event !== 'error') this.once('error', reject); this.once(event, resolve); }); } async done() { __classPrivateFieldSet$3(this, _EventStream_catchingPromiseCreated, true, "f"); await __classPrivateFieldGet$4(this, _EventStream_endPromise, "f"); } _emit(event, ...args) { // make sure we don't emit any events after end if (__classPrivateFieldGet$4(this, _EventStream_ended, "f")) { return; } if (event === 'end') { __classPrivateFieldSet$3(this, _EventStream_ended, true, "f"); __classPrivateFieldGet$4(this, _EventStream_resolveEndPromise, "f").call(this); } const listeners = __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event]; if (listeners) { __classPrivateFieldGet$4(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); listeners.forEach(({ listener }) => listener(...args)); } if (event === 'abort') { const error = args[0]; if (!__classPrivateFieldGet$4(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } __classPrivateFieldGet$4(this, _EventStream_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet$4(this, _EventStream_rejectEndPromise, "f").call(this, error); this._emit('end'); return; } if (event === 'error') { // NOTE: _emit('error', error) should only be called from #handleError(). const error = args[0]; if (!__classPrivateFieldGet$4(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { // Trigger an unhandled rejection if the user hasn't registered any error handlers. // If you are seeing stack traces here, make sure to handle errors via either: // - runner.on('error', () => ...) // - await runner.done() // - await runner.finalChatCompletion() // - etc. Promise.reject(error); } __classPrivateFieldGet$4(this, _EventStream_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet$4(this, _EventStream_rejectEndPromise, "f").call(this, error); this._emit('end'); } } _emitFinal() { } } EventStream$1.EventStream = EventStream; _EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { __classPrivateFieldSet$3(this, _EventStream_errored, true, "f"); if (error instanceof Error && error.name === 'AbortError') { error = new error_1$u.APIUserAbortError(); } if (error instanceof error_1$u.APIUserAbortError) { __classPrivateFieldSet$3(this, _EventStream_aborted, true, "f"); return this._emit('abort', error); } if (error instanceof error_1$u.OpenAIError) { return this._emit('error', error); } if (error instanceof Error) { const openAIError = new error_1$u.OpenAIError(error.message); // @ts-ignore openAIError.cause = error; return this._emit('error', openAIError); } return this._emit('error', new error_1$u.OpenAIError(String(error))); }; var parser$4 = {}; Object.defineProperty(parser$4, "__esModule", { value: true }); parser$4.validateInputTools = parser$4.hasAutoParseableInput = parser$4.shouldParseToolCall = parser$4.parseChatCompletion = parser$4.maybeParseChatCompletion = parser$4.isAutoParsableTool = parser$4.makeParseableTool = parser$4.isAutoParsableResponseFormat = parser$4.makeParseableResponseFormat = void 0; const error_1$t = requireError(); function makeParseableResponseFormat(response_format, parser) { const obj = { ...response_format }; Object.defineProperties(obj, { $brand: { value: 'auto-parseable-response-format', enumerable: false, }, $parseRaw: { value: parser, enumerable: false, }, }); return obj; } parser$4.makeParseableResponseFormat = makeParseableResponseFormat; function isAutoParsableResponseFormat(response_format) { return response_format?.['$brand'] === 'auto-parseable-response-format'; } parser$4.isAutoParsableResponseFormat = isAutoParsableResponseFormat; function makeParseableTool(tool, { parser, callback, }) { const obj = { ...tool }; Object.defineProperties(obj, { $brand: { value: 'auto-parseable-tool', enumerable: false, }, $parseRaw: { value: parser, enumerable: false, }, $callback: { value: callback, enumerable: false, }, }); return obj; } parser$4.makeParseableTool = makeParseableTool; function isAutoParsableTool(tool) { return tool?.['$brand'] === 'auto-parseable-tool'; } parser$4.isAutoParsableTool = isAutoParsableTool; function maybeParseChatCompletion(completion, params) { if (!params || !hasAutoParseableInput(params)) { return { ...completion, choices: completion.choices.map((choice) => ({ ...choice, message: { ...choice.message, parsed: null, tool_calls: choice.message.tool_calls ?? [] }, })), }; } return parseChatCompletion(completion, params); } parser$4.maybeParseChatCompletion = maybeParseChatCompletion; function parseChatCompletion(completion, params) { const choices = completion.choices.map((choice) => { if (choice.finish_reason === 'length') { throw new error_1$t.LengthFinishReasonError(); } if (choice.finish_reason === 'content_filter') { throw new error_1$t.ContentFilterFinishReasonError(); } return { ...choice, message: { ...choice.message, tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? [], parsed: choice.message.content && !choice.message.refusal ? parseResponseFormat(params, choice.message.content) : null, }, }; }); return { ...completion, choices }; } parser$4.parseChatCompletion = parseChatCompletion; function parseResponseFormat(params, content) { if (params.response_format?.type !== 'json_schema') { return null; } if (params.response_format?.type === 'json_schema') { if ('$parseRaw' in params.response_format) { const response_format = params.response_format; return response_format.$parseRaw(content); } return JSON.parse(content); } return null; } function parseToolCall(params, toolCall) { const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name); return { ...toolCall, function: { ...toolCall.function, parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null, }, }; } function shouldParseToolCall(params, toolCall) { if (!params) { return false; } const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name); return isAutoParsableTool(inputTool) || inputTool?.function.strict || false; } parser$4.shouldParseToolCall = shouldParseToolCall; function hasAutoParseableInput(params) { if (isAutoParsableResponseFormat(params.response_format)) { return true; } return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); } parser$4.hasAutoParseableInput = hasAutoParseableInput; function validateInputTools(tools) { for (const tool of tools ?? []) { if (tool.type !== 'function') { throw new error_1$t.OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); } if (tool.function.strict !== true) { throw new error_1$t.OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); } } } parser$4.validateInputTools = validateInputTools; var __classPrivateFieldGet$3 = (commonjsGlobal && commonjsGlobal.__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 _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; Object.defineProperty(AbstractChatCompletionRunner$1, "__esModule", { value: true }); AbstractChatCompletionRunner$1.AbstractChatCompletionRunner = void 0; const error_1$s = requireError(); const RunnableFunction_1 = RunnableFunction; const chatCompletionUtils_1$1 = chatCompletionUtils; const EventStream_1$1 = EventStream$1; const parser_1$1 = parser$4; const DEFAULT_MAX_CHAT_COMPLETIONS = 10; class AbstractChatCompletionRunner extends EventStream_1$1.EventStream { constructor() { super(...arguments); _AbstractChatCompletionRunner_instances.add(this); this._chatCompletions = []; this.messages = []; } _addChatCompletion(chatCompletion) { this._chatCompletions.push(chatCompletion); this._emit('chatCompletion', chatCompletion); const message = chatCompletion.choices[0]?.message; if (message) this._addMessage(message); return chatCompletion; } _addMessage(message, emit = true) { if (!('content' in message)) message.content = null; this.messages.push(message); if (emit) { this._emit('message', message); if (((0, chatCompletionUtils_1$1.isFunctionMessage)(message) || (0, chatCompletionUtils_1$1.isToolMessage)(message)) && message.content) { // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. this._emit('functionCallResult', message.content); } else if ((0, chatCompletionUtils_1$1.isAssistantMessage)(message) && message.function_call) { this._emit('functionCall', message.function_call); } else if ((0, chatCompletionUtils_1$1.isAssistantMessage)(message) && message.tool_calls) { for (const tool_call of message.tool_calls) { if (tool_call.type === 'function') { this._emit('functionCall', tool_call.function); } } } } } /** * @returns a promise that resolves with the final ChatCompletion, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletion. */ async finalChatCompletion() { await this.done(); const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (!completion) throw new error_1$s.OpenAIError('stream ended without producing a ChatCompletion'); return completion; } /** * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ async finalContent() { await this.done(); return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); } /** * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ async finalMessage() { await this.done(); return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); } /** * @returns a promise that resolves with the content of the final FunctionCall, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ async finalFunctionCall() { await this.done(); return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); } async finalFunctionCallResult() { await this.done(); return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); } async totalUsage() { await this.done(); return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); } allChatCompletions() { return [...this._chatCompletions]; } _emitFinal() { const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (completion) this._emit('finalChatCompletion', completion); const finalMessage = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); if (finalMessage) this._emit('finalMessage', finalMessage); const finalContent = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); if (finalContent) this._emit('finalContent', finalContent); const finalFunctionCall = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); if (finalFunctionCall) this._emit('finalFunctionCall', finalFunctionCall); const finalFunctionCallResult = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); if (finalFunctionCallResult != null) this._emit('finalFunctionCallResult', finalFunctionCallResult); if (this._chatCompletions.some((c) => c.usage)) { this._emit('totalUsage', __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); } } async _createChatCompletion(client, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addChatCompletion((0, parser_1$1.parseChatCompletion)(chatCompletion, params)); } async _runChatCompletion(client, params, options) { for (const message of params.messages) { this._addMessage(message, false); } return await this._createChatCompletion(client, params, options); } async _runFunctions(client, params, options) { const role = 'function'; const { function_call = 'auto', stream, ...restParams } = params; const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; const functionsByName = {}; for (const f of params.functions) { functionsByName[f.name || f.function.name] = f; } const functions = params.functions.map((f) => ({ name: f.name || f.function.name, parameters: f.parameters, description: f.description, })); for (const message of params.messages) { this._addMessage(message, false); } for (let i = 0; i < maxChatCompletions; ++i) { const chatCompletion = await this._createChatCompletion(client, { ...restParams, function_call, functions, messages: [...this.messages], }, options); const message = chatCompletion.choices[0]?.message; if (!message) { throw new error_1$s.OpenAIError(`missing message in ChatCompletion response`); } if (!message.function_call) return; const { name, arguments: args } = message.function_call; const fn = functionsByName[name]; if (!fn) { const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions .map((f) => JSON.stringify(f.name)) .join(', ')}. Please try again`; this._addMessage({ role, name, content }); continue; } else if (singleFunctionToCall && singleFunctionToCall !== name) { const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; this._addMessage({ role, name, content }); continue; } let parsed; try { parsed = (0, RunnableFunction_1.isRunnableFunctionWithParse)(fn) ? await fn.parse(args) : args; } catch (error) { this._addMessage({ role, name, content: error instanceof Error ? error.message : String(error), }); continue; } // @ts-expect-error it can't rule out `never` type. const rawContent = await fn.function(parsed, this); const content = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, name, content }); if (singleFunctionToCall) return; } } async _runTools(client, params, options) { const role = 'tool'; const { tool_choice = 'auto', stream, ...restParams } = params; const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; // TODO(someday): clean this logic up const inputTools = params.tools.map((tool) => { if ((0, parser_1$1.isAutoParsableTool)(tool)) { if (!tool.$callback) { throw new error_1$s.OpenAIError('Tool given to `.runTools()` that does not have an associated function'); } return { type: 'function', function: { function: tool.$callback, name: tool.function.name, description: tool.function.description || '', parameters: tool.function.parameters, parse: tool.$parseRaw, strict: true, }, }; } return tool; }); const functionsByName = {}; for (const f of inputTools) { if (f.type === 'function') { functionsByName[f.function.name || f.function.function.name] = f.function; } } const tools = 'tools' in params ? inputTools.map((t) => t.type === 'function' ? { type: 'function', function: { name: t.function.name || t.function.function.name, parameters: t.function.parameters, description: t.function.description, strict: t.function.strict, }, } : t) : undefined; for (const message of params.messages) { this._addMessage(message, false); } for (let i = 0; i < maxChatCompletions; ++i) { const chatCompletion = await this._createChatCompletion(client, { ...restParams, tool_choice, tools, messages: [...this.messages], }, options); const message = chatCompletion.choices[0]?.message; if (!message) { throw new error_1$s.OpenAIError(`missing message in ChatCompletion response`); } if (!message.tool_calls?.length) { return; } for (const tool_call of message.tool_calls) { if (tool_call.type !== 'function') continue; const tool_call_id = tool_call.id; const { name, arguments: args } = tool_call.function; const fn = functionsByName[name]; if (!fn) { const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName) .map((name) => JSON.stringify(name)) .join(', ')}. Please try again`; this._addMessage({ role, tool_call_id, content }); continue; } else if (singleFunctionToCall && singleFunctionToCall !== name) { const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; this._addMessage({ role, tool_call_id, content }); continue; } let parsed; try { parsed = (0, RunnableFunction_1.isRunnableFunctionWithParse)(fn) ? await fn.parse(args) : args; } catch (error) { const content = error instanceof Error ? error.message : String(error); this._addMessage({ role, tool_call_id, content }); continue; } // @ts-expect-error it can't rule out `never` type. const rawContent = await fn.function(parsed, this); const content = __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, tool_call_id, content }); if (singleFunctionToCall) { return; } } } return; } } AbstractChatCompletionRunner$1.AbstractChatCompletionRunner = AbstractChatCompletionRunner; _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { return __classPrivateFieldGet$3(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { let i = this.messages.length; while (i-- > 0) { const message = this.messages[i]; if ((0, chatCompletionUtils_1$1.isAssistantMessage)(message)) { const { function_call, ...rest } = message; // TODO: support audio here const ret = { ...rest, content: message.content ?? null, refusal: message.refusal ?? null, }; if (function_call) { ret.function_call = function_call; } return ret; } } throw new error_1$s.OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); }, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { for (let i = this.messages.length - 1; i >= 0; i--) { const message = this.messages[i]; if ((0, chatCompletionUtils_1$1.isAssistantMessage)(message) && message?.function_call) { return message.function_call; } if ((0, chatCompletionUtils_1$1.isAssistantMessage)(message) && message?.tool_calls?.length) { return message.tool_calls.at(-1)?.function; } } return; }, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() { for (let i = this.messages.length - 1; i >= 0; i--) { const message = this.messages[i]; if ((0, chatCompletionUtils_1$1.isFunctionMessage)(message) && message.content != null) { return message.content; } if ((0, chatCompletionUtils_1$1.isToolMessage)(message) && message.content != null && typeof message.content === 'string' && this.messages.some((x) => x.role === 'assistant' && x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { return message.content; } } return; }, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { const total = { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0, }; for (const { usage } of this._chatCompletions) { if (usage) { total.completion_tokens += usage.completion_tokens; total.prompt_tokens += usage.prompt_tokens; total.total_tokens += usage.total_tokens; } } return total; }, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { if (params.n != null && params.n > 1) { throw new error_1$s.OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); } }, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { return (typeof rawContent === 'string' ? rawContent : rawContent === undefined ? 'undefined' : JSON.stringify(rawContent)); }; Object.defineProperty(ChatCompletionRunner$1, "__esModule", { value: true }); ChatCompletionRunner$1.ChatCompletionRunner = void 0; const AbstractChatCompletionRunner_1$1 = AbstractChatCompletionRunner$1; const chatCompletionUtils_1 = chatCompletionUtils; class ChatCompletionRunner extends AbstractChatCompletionRunner_1$1.AbstractChatCompletionRunner { /** @deprecated - please use `runTools` instead. */ static runFunctions(client, params, options) { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, }; runner._run(() => runner._runFunctions(client, params, opts)); return runner; } static runTools(client, params, options) { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, }; runner._run(() => runner._runTools(client, params, opts)); return runner; } _addMessage(message, emit = true) { super._addMessage(message, emit); if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.content) { this._emit('content', message.content); } } } ChatCompletionRunner$1.ChatCompletionRunner = ChatCompletionRunner; var ChatCompletionStreamingRunner$1 = {}; var ChatCompletionStream$1 = {}; var parser$3 = {}; Object.defineProperty(parser$3, "__esModule", { value: true }); parser$3.MalformedJSON = parser$3.PartialJSON = parser$3.partialParse = void 0; const STR = 0b000000001; const NUM = 0b000000010; const ARR = 0b000000100; const OBJ = 0b000001000; const NULL = 0b000010000; const BOOL = 0b000100000; const NAN = 0b001000000; const INFINITY = 0b010000000; const MINUS_INFINITY = 0b100000000; const INF = INFINITY | MINUS_INFINITY; const SPECIAL = NULL | BOOL | INF | NAN; const ATOM = STR | NUM | SPECIAL; const COLLECTION = ARR | OBJ; const ALL = ATOM | COLLECTION; const Allow = { STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, MINUS_INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL, }; // The JSON string segment was unable to be parsed completely class PartialJSON extends Error { } parser$3.PartialJSON = PartialJSON; class MalformedJSON extends Error { } parser$3.MalformedJSON = MalformedJSON; /** * Parse incomplete JSON * @param {string} jsonString Partial JSON to be parsed * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details * @returns The parsed JSON * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) * @throws {MalformedJSON} If the JSON is malformed */ function parseJSON(jsonString, allowPartial = Allow.ALL) { if (typeof jsonString !== 'string') { throw new TypeError(`expecting str, got ${typeof jsonString}`); } if (!jsonString.trim()) { throw new Error(`${jsonString} is empty`); } return _parseJSON(jsonString.trim(), allowPartial); } const _parseJSON = (jsonString, allow) => { const length = jsonString.length; let index = 0; const markPartialJSON = (msg) => { throw new PartialJSON(`${msg} at position ${index}`); }; const throwMalformedError = (msg) => { throw new MalformedJSON(`${msg} at position ${index}`); }; const parseAny = () => { skipBlank(); if (index >= length) markPartialJSON('Unexpected end of input'); if (jsonString[index] === '"') return parseStr(); if (jsonString[index] === '{') return parseObj(); if (jsonString[index] === '[') return parseArr(); if (jsonString.substring(index, index + 4) === 'null' || (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { index += 4; return null; } if (jsonString.substring(index, index + 4) === 'true' || (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { index += 4; return true; } if (jsonString.substring(index, index + 5) === 'false' || (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { index += 5; return false; } if (jsonString.substring(index, index + 8) === 'Infinity' || (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { index += 8; return Infinity; } if (jsonString.substring(index, index + 9) === '-Infinity' || (Allow.MINUS_INFINITY & allow && 1 < length - index && length - index < 9 && '-Infinity'.startsWith(jsonString.substring(index)))) { index += 9; return -Infinity; } if (jsonString.substring(index, index + 3) === 'NaN' || (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { index += 3; return NaN; } return parseNum(); }; const parseStr = () => { const start = index; let escape = false; index++; // skip initial quote while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { escape = jsonString[index] === '\\' ? !escape : false; index++; } if (jsonString.charAt(index) == '"') { try { return JSON.parse(jsonString.substring(start, ++index - Number(escape))); } catch (e) { throwMalformedError(String(e)); } } else if (Allow.STR & allow) { try { return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); } catch (e) { // SyntaxError: Invalid escape sequence return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); } } markPartialJSON('Unterminated string literal'); }; const parseObj = () => { index++; // skip initial brace skipBlank(); const obj = {}; try { while (jsonString[index] !== '}') { skipBlank(); if (index >= length && Allow.OBJ & allow) return obj; const key = parseStr(); skipBlank(); index++; // skip colon try { const value = parseAny(); Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); } catch (e) { if (Allow.OBJ & allow) return obj; else throw e; } skipBlank(); if (jsonString[index] === ',') index++; // skip comma } } catch (e) { if (Allow.OBJ & allow) return obj; else markPartialJSON("Expected '}' at end of object"); } index++; // skip final brace return obj; }; const parseArr = () => { index++; // skip initial bracket const arr = []; try { while (jsonString[index] !== ']') { arr.push(parseAny()); skipBlank(); if (jsonString[index] === ',') { index++; // skip comma } } } catch (e) { if (Allow.ARR & allow) { return arr; } markPartialJSON("Expected ']' at end of array"); } index++; // skip final bracket return arr; }; const parseNum = () => { if (index === 0) { if (jsonString === '-' && Allow.NUM & allow) markPartialJSON("Not sure what '-' is"); try { return JSON.parse(jsonString); } catch (e) { if (Allow.NUM & allow) { try { if ('.' === jsonString[jsonString.length - 1]) return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); } catch (e) { } } throwMalformedError(String(e)); } } const start = index; if (jsonString[index] === '-') index++; while (jsonString[index] && !',]}'.includes(jsonString[index])) index++; if (index == length && !(Allow.NUM & allow)) markPartialJSON('Unterminated number literal'); try { return JSON.parse(jsonString.substring(start, index)); } catch (e) { if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) markPartialJSON("Not sure what '-' is"); try { return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); } catch (e) { throwMalformedError(String(e)); } } }; const skipBlank = () => { while (index < length && ' \n\r\t'.includes(jsonString[index])) { index++; } }; return parseAny(); }; // using this function with malformed JSON is undefined behavior const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); parser$3.partialParse = partialParse; var __classPrivateFieldSet$2 = (commonjsGlobal && commonjsGlobal.__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$2 = (commonjsGlobal && commonjsGlobal.__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 _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; Object.defineProperty(ChatCompletionStream$1, "__esModule", { value: true }); ChatCompletionStream$1.ChatCompletionStream = void 0; const error_1$r = requireError(); const AbstractChatCompletionRunner_1 = AbstractChatCompletionRunner$1; const streaming_1$1 = requireStreaming(); const parser_1 = parser$4; const parser_2 = parser$3; class ChatCompletionStream extends AbstractChatCompletionRunner_1.AbstractChatCompletionRunner { constructor(params) { super(); _ChatCompletionStream_instances.add(this); _ChatCompletionStream_params.set(this, void 0); _ChatCompletionStream_choiceEventStates.set(this, void 0); _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); __classPrivateFieldSet$2(this, _ChatCompletionStream_params, params, "f"); __classPrivateFieldSet$2(this, _ChatCompletionStream_choiceEventStates, [], "f"); } get currentChatCompletionSnapshot() { return __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); } /** * Intended for use on the frontend, consuming a stream produced with * `.toReadableStream()` on the backend. * * Note that messages sent to the model do not appear in `.on('message')` * in this context. */ static fromReadableStream(stream) { const runner = new ChatCompletionStream(null); runner._run(() => runner._fromReadableStream(stream)); return runner; } static createChatCompletion(client, params, options) { const runner = new ChatCompletionStream(params); runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); return runner; } async _createChatCompletion(client, params, options) { super._createChatCompletion; const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); this._connected(); for await (const chunk of stream) { __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); } if (stream.controller.signal?.aborted) { throw new error_1$r.APIUserAbortError(); } return this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } async _fromReadableStream(readableStream, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); this._connected(); const stream = streaming_1$1.Stream.fromReadableStream(readableStream, this.controller); let chatId; for await (const chunk of stream) { if (chatId && chatId !== chunk.id) { // A new request has been made. this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); chatId = chunk.id; } if (stream.controller.signal?.aborted) { throw new error_1$r.APIUserAbortError(); } return this._addChatCompletion(__classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { if (this.ended) return; __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { let state = __classPrivateFieldGet$2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; if (state) { return state; } state = { content_done: false, refusal_done: false, logprobs_content_done: false, logprobs_refusal_done: false, done_tool_calls: new Set(), current_tool_call_index: null, }; __classPrivateFieldGet$2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; return state; }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { if (this.ended) return; const completion = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); this._emit('chunk', chunk, completion); for (const choice of chunk.choices) { const choiceSnapshot = completion.choices[choice.index]; if (choice.delta.content != null && choiceSnapshot.message?.role === 'assistant' && choiceSnapshot.message?.content) { this._emit('content', choice.delta.content, choiceSnapshot.message.content); this._emit('content.delta', { delta: choice.delta.content, snapshot: choiceSnapshot.message.content, parsed: choiceSnapshot.message.parsed, }); } if (choice.delta.refusal != null && choiceSnapshot.message?.role === 'assistant' && choiceSnapshot.message?.refusal) { this._emit('refusal.delta', { delta: choice.delta.refusal, snapshot: choiceSnapshot.message.refusal, }); } if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { this._emit('logprobs.content.delta', { content: choice.logprobs?.content, snapshot: choiceSnapshot.logprobs?.content ?? [], }); } if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { this._emit('logprobs.refusal.delta', { refusal: choice.logprobs?.refusal, snapshot: choiceSnapshot.logprobs?.refusal ?? [], }); } const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); if (choiceSnapshot.finish_reason) { __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); if (state.current_tool_call_index != null) { __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); } } for (const toolCall of choice.delta.tool_calls ?? []) { if (state.current_tool_call_index !== toolCall.index) { __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); // new tool call started, the previous one is done if (state.current_tool_call_index != null) { __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); } } state.current_tool_call_index = toolCall.index; } for (const toolCallDelta of choice.delta.tool_calls ?? []) { const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; if (!toolCallSnapshot?.type) { continue; } if (toolCallSnapshot?.type === 'function') { this._emit('tool_calls.function.arguments.delta', { name: toolCallSnapshot.function?.name, index: toolCallDelta.index, arguments: toolCallSnapshot.function.arguments, parsed_arguments: toolCallSnapshot.function.parsed_arguments, arguments_delta: toolCallDelta.function?.arguments ?? '', }); } else { assertNever(toolCallSnapshot?.type); } } } }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); if (state.done_tool_calls.has(toolCallIndex)) { // we've already fired the done event return; } const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; if (!toolCallSnapshot) { throw new Error('no tool call snapshot'); } if (!toolCallSnapshot.type) { throw new Error('tool call snapshot missing `type`'); } if (toolCallSnapshot.type === 'function') { const inputTool = __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name); this._emit('tool_calls.function.arguments.done', { name: toolCallSnapshot.function.name, index: toolCallIndex, arguments: toolCallSnapshot.function.arguments, parsed_arguments: (0, parser_1.isAutoParsableTool)(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null, }); } else { assertNever(toolCallSnapshot.type); } }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { const state = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); if (choiceSnapshot.message.content && !state.content_done) { state.content_done = true; const responseFormat = __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); this._emit('content.done', { content: choiceSnapshot.message.content, parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, }); } if (choiceSnapshot.message.refusal && !state.refusal_done) { state.refusal_done = true; this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); } if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { state.logprobs_content_done = true; this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); } if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { state.logprobs_refusal_done = true; this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); } }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { if (this.ended) { throw new error_1$r.OpenAIError(`stream has ended, this shouldn't happen`); } const snapshot = __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); if (!snapshot) { throw new error_1$r.OpenAIError(`request ended without sending any chunks`); } __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); __classPrivateFieldSet$2(this, _ChatCompletionStream_choiceEventStates, [], "f"); return finalizeChatCompletion(snapshot, __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")); }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { const responseFormat = __classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f")?.response_format; if ((0, parser_1.isAutoParsableResponseFormat)(responseFormat)) { return responseFormat; } return null; }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { var _a, _b, _c, _d; let snapshot = __classPrivateFieldGet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); const { choices, ...rest } = chunk; if (!snapshot) { snapshot = __classPrivateFieldSet$2(this, _ChatCompletionStream_currentChatCompletionSnapshot, { ...rest, choices: [], }, "f"); } else { Object.assign(snapshot, rest); } for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { let choice = snapshot.choices[index]; if (!choice) { choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; } if (logprobs) { if (!choice.logprobs) { choice.logprobs = Object.assign({}, logprobs); } else { const { content, refusal, ...rest } = logprobs; Object.assign(choice.logprobs, rest); if (content) { (_a = choice.logprobs).content ?? (_a.content = []); choice.logprobs.content.push(...content); } if (refusal) { (_b = choice.logprobs).refusal ?? (_b.refusal = []); choice.logprobs.refusal.push(...refusal); } } } if (finish_reason) { choice.finish_reason = finish_reason; if (__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f") && (0, parser_1.hasAutoParseableInput)(__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"))) { if (finish_reason === 'length') { throw new error_1$r.LengthFinishReasonError(); } if (finish_reason === 'content_filter') { throw new error_1$r.ContentFilterFinishReasonError(); } } } Object.assign(choice, other); if (!delta) continue; // Shouldn't happen; just in case. const { content, refusal, function_call, role, tool_calls, ...rest } = delta; Object.assign(choice.message, rest); if (refusal) { choice.message.refusal = (choice.message.refusal || '') + refusal; } if (role) choice.message.role = role; if (function_call) { if (!choice.message.function_call) { choice.message.function_call = function_call; } else { if (function_call.name) choice.message.function_call.name = function_call.name; if (function_call.arguments) { (_c = choice.message.function_call).arguments ?? (_c.arguments = ''); choice.message.function_call.arguments += function_call.arguments; } } } if (content) { choice.message.content = (choice.message.content || '') + content; if (!choice.message.refusal && __classPrivateFieldGet$2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { choice.message.parsed = (0, parser_2.partialParse)(choice.message.content); } } if (tool_calls) { if (!choice.message.tool_calls) choice.message.tool_calls = []; for (const { index, id, type, function: fn, ...rest } of tool_calls) { const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {})); Object.assign(tool_call, rest); if (id) tool_call.id = id; if (type) tool_call.type = type; if (fn) tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' }); if (fn?.name) tool_call.function.name = fn.name; if (fn?.arguments) { tool_call.function.arguments += fn.arguments; if ((0, parser_1.shouldParseToolCall)(__classPrivateFieldGet$2(this, _ChatCompletionStream_params, "f"), tool_call)) { tool_call.function.parsed_arguments = (0, parser_2.partialParse)(tool_call.function.arguments); } } } } } return snapshot; }, Symbol.asyncIterator)]() { const pushQueue = []; const readQueue = []; let done = false; this.on('chunk', (chunk) => { const reader = readQueue.shift(); if (reader) { reader.resolve(chunk); } else { pushQueue.push(chunk); } }); this.on('end', () => { done = true; for (const reader of readQueue) { reader.resolve(undefined); } readQueue.length = 0; }); this.on('abort', (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); this.on('error', (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); return { next: async () => { if (!pushQueue.length) { if (done) { return { value: undefined, done: true }; } return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); } const chunk = pushQueue.shift(); return { value: chunk, done: false }; }, return: async () => { this.abort(); return { value: undefined, done: true }; }, }; } toReadableStream() { const stream = new streaming_1$1.Stream(this[Symbol.asyncIterator].bind(this), this.controller); return stream.toReadableStream(); } } ChatCompletionStream$1.ChatCompletionStream = ChatCompletionStream; function finalizeChatCompletion(snapshot, params) { const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; const completion = { ...rest, id, choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { if (!finish_reason) { throw new error_1$r.OpenAIError(`missing finish_reason for choice ${index}`); } const { content = null, function_call, tool_calls, ...messageRest } = message; const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. if (!role) { throw new error_1$r.OpenAIError(`missing role for choice ${index}`); } if (function_call) { const { arguments: args, name } = function_call; if (args == null) { throw new error_1$r.OpenAIError(`missing function_call.arguments for choice ${index}`); } if (!name) { throw new error_1$r.OpenAIError(`missing function_call.name for choice ${index}`); } return { ...choiceRest, message: { content, function_call: { arguments: args, name }, role, refusal: message.refusal ?? null, }, finish_reason, index, logprobs, }; } if (tool_calls) { return { ...choiceRest, index, finish_reason, logprobs, message: { ...messageRest, role, content, refusal: message.refusal ?? null, tool_calls: tool_calls.map((tool_call, i) => { const { function: fn, type, id, ...toolRest } = tool_call; const { arguments: args, name, ...fnRest } = fn || {}; if (id == null) { throw new error_1$r.OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); } if (type == null) { throw new error_1$r.OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); } if (name == null) { throw new error_1$r.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); } if (args == null) { throw new error_1$r.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); } return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; }), }, }; } return { ...choiceRest, message: { ...messageRest, content, role, refusal: message.refusal ?? null }, finish_reason, index, logprobs, }; }), created, model, object: 'chat.completion', ...(system_fingerprint ? { system_fingerprint } : {}), }; return (0, parser_1.maybeParseChatCompletion)(completion, params); } function str(x) { return JSON.stringify(x); } function assertNever(_x) { } Object.defineProperty(ChatCompletionStreamingRunner$1, "__esModule", { value: true }); ChatCompletionStreamingRunner$1.ChatCompletionStreamingRunner = void 0; const ChatCompletionStream_1 = ChatCompletionStream$1; class ChatCompletionStreamingRunner extends ChatCompletionStream_1.ChatCompletionStream { static fromReadableStream(stream) { const runner = new ChatCompletionStreamingRunner(null); runner._run(() => runner._fromReadableStream(stream)); return runner; } /** @deprecated - please use `runTools` instead. */ static runFunctions(client, params, options) { const runner = new ChatCompletionStreamingRunner(null); const opts = { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, }; runner._run(() => runner._runFunctions(client, params, opts)); return runner; } static runTools(client, params, options) { const runner = new ChatCompletionStreamingRunner( // @ts-expect-error TODO these types are incompatible params); const opts = { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, }; runner._run(() => runner._runTools(client, params, opts)); return runner; } } ChatCompletionStreamingRunner$1.ChatCompletionStreamingRunner = ChatCompletionStreamingRunner; (function (exports) { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(exports, "__esModule", { value: true }); exports.Completions = exports.ChatCompletionRunner = exports.ChatCompletionStream = exports.ParsingToolFunction = exports.ParsingFunction = exports.ChatCompletionStreamingRunner = void 0; const resource_1 = resource; const ChatCompletionRunner_1 = ChatCompletionRunner$1; const ChatCompletionStreamingRunner_1 = ChatCompletionStreamingRunner$1; const ChatCompletionStream_1 = ChatCompletionStream$1; const parser_1 = parser$4; var ChatCompletionStreamingRunner_2 = ChatCompletionStreamingRunner$1; Object.defineProperty(exports, "ChatCompletionStreamingRunner", { enumerable: true, get: function () { return ChatCompletionStreamingRunner_2.ChatCompletionStreamingRunner; } }); var RunnableFunction_1 = RunnableFunction; Object.defineProperty(exports, "ParsingFunction", { enumerable: true, get: function () { return RunnableFunction_1.ParsingFunction; } }); Object.defineProperty(exports, "ParsingToolFunction", { enumerable: true, get: function () { return RunnableFunction_1.ParsingToolFunction; } }); var ChatCompletionStream_2 = ChatCompletionStream$1; Object.defineProperty(exports, "ChatCompletionStream", { enumerable: true, get: function () { return ChatCompletionStream_2.ChatCompletionStream; } }); var ChatCompletionRunner_2 = ChatCompletionRunner$1; Object.defineProperty(exports, "ChatCompletionRunner", { enumerable: true, get: function () { return ChatCompletionRunner_2.ChatCompletionRunner; } }); class Completions extends resource_1.APIResource { parse(body, options) { (0, parser_1.validateInputTools)(body.tools); return this._client.chat.completions .create(body, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'beta.chat.completions.parse', }, }) ._thenUnwrap((completion) => (0, parser_1.parseChatCompletion)(completion, body)); } runFunctions(body, options) { if (body.stream) { return ChatCompletionStreamingRunner_1.ChatCompletionStreamingRunner.runFunctions(this._client, body, options); } return ChatCompletionRunner_1.ChatCompletionRunner.runFunctions(this._client, body, options); } runTools(body, options) { if (body.stream) { return ChatCompletionStreamingRunner_1.ChatCompletionStreamingRunner.runTools(this._client, body, options); } return ChatCompletionRunner_1.ChatCompletionRunner.runTools(this._client, body, options); } /** * Creates a chat completion stream */ stream(body, options) { return ChatCompletionStream_1.ChatCompletionStream.createChatCompletion(this._client, body, options); } } exports.Completions = Completions; } (completions$1)); (function (exports) { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding = (commonjsGlobal && commonjsGlobal.__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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (commonjsGlobal && commonjsGlobal.__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 = resource; const CompletionsAPI = __importStar(completions$1); class Chat extends resource_1.APIResource { constructor() { super(...arguments); this.completions = new CompletionsAPI.Completions(this._client); } } exports.Chat = Chat; (function (Chat) { Chat.Completions = CompletionsAPI.Completions; })(Chat = exports.Chat || (exports.Chat = {})); } (chat)); var threads = {}; var AssistantStream$1 = {}; var __createBinding$b = (commonjsGlobal && commonjsGlobal.__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$b = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$b = (commonjsGlobal && commonjsGlobal.__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$b(result, mod, k); __setModuleDefault$b(result, mod); return result; }; var __classPrivateFieldGet$1 = (commonjsGlobal && commonjsGlobal.__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$1 = (commonjsGlobal && commonjsGlobal.__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 _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; Object.defineProperty(AssistantStream$1, "__esModule", { value: true }); AssistantStream$1.AssistantStream = void 0; const Core$3 = __importStar$b(requireCore$1()); const streaming_1 = requireStreaming(); const error_1$q = requireError(); const EventStream_1 = EventStream$1; class AssistantStream extends EventStream_1.EventStream { constructor() { super(...arguments); _AssistantStream_instances.add(this); //Track all events in a single list for reference _AssistantStream_events.set(this, []); //Used to accumulate deltas //We are accumulating many types so the value here is not strict _AssistantStream_runStepSnapshots.set(this, {}); _AssistantStream_messageSnapshots.set(this, {}); _AssistantStream_messageSnapshot.set(this, void 0); _AssistantStream_finalRun.set(this, void 0); _AssistantStream_currentContentIndex.set(this, void 0); _AssistantStream_currentContent.set(this, void 0); _AssistantStream_currentToolCallIndex.set(this, void 0); _AssistantStream_currentToolCall.set(this, void 0); //For current snapshot methods _AssistantStream_currentEvent.set(this, void 0); _AssistantStream_currentRunSnapshot.set(this, void 0); _AssistantStream_currentRunStepSnapshot.set(this, void 0); } [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { const pushQueue = []; const readQueue = []; let done = false; //Catch all for passing along all events this.on('event', (event) => { const reader = readQueue.shift(); if (reader) { reader.resolve(event); } else { pushQueue.push(event); } }); this.on('end', () => { done = true; for (const reader of readQueue) { reader.resolve(undefined); } readQueue.length = 0; }); this.on('abort', (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); this.on('error', (err) => { done = true; for (const reader of readQueue) { reader.reject(err); } readQueue.length = 0; }); return { next: async () => { if (!pushQueue.length) { if (done) { return { value: undefined, done: true }; } return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); } const chunk = pushQueue.shift(); return { value: chunk, done: false }; }, return: async () => { this.abort(); return { value: undefined, done: true }; }, }; } static fromReadableStream(stream) { const runner = new AssistantStream(); runner._run(() => runner._fromReadableStream(stream)); return runner; } async _fromReadableStream(readableStream, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } this._connected(); const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller); for await (const event of stream) { __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new error_1$q.APIUserAbortError(); } return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } toReadableStream() { const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller); return stream.toReadableStream(); } static createToolAssistantStream(threadId, runId, runs, params, options) { const runner = new AssistantStream(); runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, params, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, })); return runner; } async _createToolAssistantStream(run, threadId, runId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } const body = { ...params, stream: true }; const stream = await run.submitToolOutputs(threadId, runId, body, { ...options, signal: this.controller.signal, }); this._connected(); for await (const event of stream) { __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new error_1$q.APIUserAbortError(); } return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } static createThreadAssistantStream(params, thread, options) { const runner = new AssistantStream(); runner._run(() => runner._threadAssistantStream(params, thread, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, })); return runner; } static createAssistantStream(threadId, runs, params, options) { const runner = new AssistantStream(); runner._run(() => runner._runAssistantStream(threadId, runs, params, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, })); return runner; } currentEvent() { return __classPrivateFieldGet$1(this, _AssistantStream_currentEvent, "f"); } currentRun() { return __classPrivateFieldGet$1(this, _AssistantStream_currentRunSnapshot, "f"); } currentMessageSnapshot() { return __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f"); } currentRunStepSnapshot() { return __classPrivateFieldGet$1(this, _AssistantStream_currentRunStepSnapshot, "f"); } async finalRunSteps() { await this.done(); return Object.values(__classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")); } async finalMessages() { await this.done(); return Object.values(__classPrivateFieldGet$1(this, _AssistantStream_messageSnapshots, "f")); } async finalRun() { await this.done(); if (!__classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f")) throw Error('Final run was not received.'); return __classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f"); } async _createThreadAssistantStream(thread, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } const body = { ...params, stream: true }; const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event of stream) { __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new error_1$q.APIUserAbortError(); } return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } async _createAssistantStream(run, threadId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } const body = { ...params, stream: true }; const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event of stream) { __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new error_1$q.APIUserAbortError(); } return this._addRun(__classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } static accumulateDelta(acc, delta) { for (const [key, deltaValue] of Object.entries(delta)) { if (!acc.hasOwnProperty(key)) { acc[key] = deltaValue; continue; } let accValue = acc[key]; if (accValue === null || accValue === undefined) { acc[key] = deltaValue; continue; } // We don't accumulate these special properties if (key === 'index' || key === 'type') { acc[key] = deltaValue; continue; } // Type-specific accumulation logic if (typeof accValue === 'string' && typeof deltaValue === 'string') { accValue += deltaValue; } else if (typeof accValue === 'number' && typeof deltaValue === 'number') { accValue += deltaValue; } else if (Core$3.isObj(accValue) && Core$3.isObj(deltaValue)) { accValue = this.accumulateDelta(accValue, deltaValue); } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { accValue.push(...deltaValue); // Use spread syntax for efficient addition continue; } for (const deltaEntry of deltaValue) { if (!Core$3.isObj(deltaEntry)) { throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); } const index = deltaEntry['index']; if (index == null) { console.error(deltaEntry); throw new Error('Expected array delta entry to have an `index` property'); } if (typeof index !== 'number') { throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); } const accEntry = accValue[index]; if (accEntry == null) { accValue.push(deltaEntry); } else { accValue[index] = this.accumulateDelta(accEntry, deltaEntry); } } continue; } else { throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); } acc[key] = accValue; } return acc; } _addRun(run) { return run; } async _threadAssistantStream(params, thread, options) { return await this._createThreadAssistantStream(thread, params, options); } async _runAssistantStream(threadId, runs, params, options) { return await this._createAssistantStream(runs, threadId, params, options); } async _runToolAssistantStream(threadId, runId, runs, params, options) { return await this._createToolAssistantStream(runs, threadId, runId, params, options); } } AssistantStream$1.AssistantStream = AssistantStream; _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { if (this.ended) return; __classPrivateFieldSet$1(this, _AssistantStream_currentEvent, event, "f"); __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); switch (event.event) { case 'thread.created': //No action on this event. break; case 'thread.run.created': case 'thread.run.queued': case 'thread.run.in_progress': case 'thread.run.requires_action': case 'thread.run.completed': case 'thread.run.failed': case 'thread.run.cancelling': case 'thread.run.cancelled': case 'thread.run.expired': __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); break; case 'thread.run.step.created': case 'thread.run.step.in_progress': case 'thread.run.step.delta': case 'thread.run.step.completed': case 'thread.run.step.failed': case 'thread.run.step.cancelled': case 'thread.run.step.expired': __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); break; case 'thread.message.created': case 'thread.message.in_progress': case 'thread.message.delta': case 'thread.message.completed': case 'thread.message.incomplete': __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); break; case 'error': //This is included for completeness, but errors are processed in the SSE event processing so this should not occur throw new Error('Encountered an error event in event processing - errors should be processed earlier'); } }, _AssistantStream_endRequest = function _AssistantStream_endRequest() { if (this.ended) { throw new error_1$q.OpenAIError(`stream has ended, this shouldn't happen`); } if (!__classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f")) throw Error('Final run has not been received'); return __classPrivateFieldGet$1(this, _AssistantStream_finalRun, "f"); }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { const [accumulatedMessage, newContent] = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")); __classPrivateFieldSet$1(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; for (const content of newContent) { const snapshotContent = accumulatedMessage.content[content.index]; if (snapshotContent?.type == 'text') { this._emit('textCreated', snapshotContent.text); } } switch (event.event) { case 'thread.message.created': this._emit('messageCreated', event.data); break; case 'thread.message.in_progress': break; case 'thread.message.delta': this._emit('messageDelta', event.data.delta, accumulatedMessage); if (event.data.delta.content) { for (const content of event.data.delta.content) { //If it is text delta, emit a text delta event if (content.type == 'text' && content.text) { let textDelta = content.text; let snapshot = accumulatedMessage.content[content.index]; if (snapshot && snapshot.type == 'text') { this._emit('textDelta', textDelta, snapshot.text); } else { throw Error('The snapshot associated with this text delta is not text or missing'); } } if (content.index != __classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f")) { //See if we have in progress content if (__classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f")) { switch (__classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").type) { case 'text': this._emit('textDone', __classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")); break; case 'image_file': this._emit('imageFileDone', __classPrivateFieldGet$1(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")); break; } } __classPrivateFieldSet$1(this, _AssistantStream_currentContentIndex, content.index, "f"); } __classPrivateFieldSet$1(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); } } break; case 'thread.message.completed': case 'thread.message.incomplete': //We emit the latest content we were working on on completion (including incomplete) if (__classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f") !== undefined) { const currentContent = event.data.content[__classPrivateFieldGet$1(this, _AssistantStream_currentContentIndex, "f")]; if (currentContent) { switch (currentContent.type) { case 'image_file': this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")); break; case 'text': this._emit('textDone', currentContent.text, __classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")); break; } } } if (__classPrivateFieldGet$1(this, _AssistantStream_messageSnapshot, "f")) { this._emit('messageDone', event.data); } __classPrivateFieldSet$1(this, _AssistantStream_messageSnapshot, undefined, "f"); } }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { const accumulatedRunStep = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); __classPrivateFieldSet$1(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); switch (event.event) { case 'thread.run.step.created': this._emit('runStepCreated', event.data); break; case 'thread.run.step.delta': const delta = event.data.delta; if (delta.step_details && delta.step_details.type == 'tool_calls' && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == 'tool_calls') { for (const toolCall of delta.step_details.tool_calls) { if (toolCall.index == __classPrivateFieldGet$1(this, _AssistantStream_currentToolCallIndex, "f")) { this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); } else { if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) { this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")); } __classPrivateFieldSet$1(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) this._emit('toolCallCreated', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")); } } } this._emit('runStepDelta', event.data.delta, accumulatedRunStep); break; case 'thread.run.step.completed': case 'thread.run.step.failed': case 'thread.run.step.cancelled': case 'thread.run.step.expired': __classPrivateFieldSet$1(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); const details = event.data.step_details; if (details.type == 'tool_calls') { if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) { this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")); __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, undefined, "f"); } } this._emit('runStepDone', event.data, accumulatedRunStep); break; } }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { __classPrivateFieldGet$1(this, _AssistantStream_events, "f").push(event); this._emit('event', event); }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { switch (event.event) { case 'thread.run.step.created': __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; return event.data; case 'thread.run.step.delta': let snapshot = __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; if (!snapshot) { throw Error('Received a RunStepDelta before creation of a snapshot'); } let data = event.data; if (data.delta) { const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta); __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; } return __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; case 'thread.run.step.completed': case 'thread.run.step.failed': case 'thread.run.step.cancelled': case 'thread.run.step.expired': case 'thread.run.step.in_progress': __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; break; } if (__classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) return __classPrivateFieldGet$1(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; throw new Error('No snapshot available'); }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { let newContent = []; switch (event.event) { case 'thread.message.created': //On creation the snapshot is just the initial message return [event.data, newContent]; case 'thread.message.delta': if (!snapshot) { throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); } let data = event.data; //If this delta does not have content, nothing to process if (data.delta.content) { for (const contentElement of data.delta.content) { if (contentElement.index in snapshot.content) { let currentContent = snapshot.content[contentElement.index]; snapshot.content[contentElement.index] = __classPrivateFieldGet$1(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); } else { snapshot.content[contentElement.index] = contentElement; // This is a new element newContent.push(contentElement); } } } return [snapshot, newContent]; case 'thread.message.in_progress': case 'thread.message.completed': case 'thread.message.incomplete': //No changes on other thread events if (snapshot) { return [snapshot, newContent]; } else { throw Error('Received thread message event with no existing snapshot'); } } throw Error('Tried to accumulate a non-message event'); }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { return AssistantStream.accumulateDelta(currentContent, contentElement); }, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { __classPrivateFieldSet$1(this, _AssistantStream_currentRunSnapshot, event.data, "f"); switch (event.event) { case 'thread.run.created': break; case 'thread.run.queued': break; case 'thread.run.in_progress': break; case 'thread.run.requires_action': case 'thread.run.cancelled': case 'thread.run.failed': case 'thread.run.completed': case 'thread.run.expired': __classPrivateFieldSet$1(this, _AssistantStream_finalRun, event.data, "f"); if (__classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")) { this._emit('toolCallDone', __classPrivateFieldGet$1(this, _AssistantStream_currentToolCall, "f")); __classPrivateFieldSet$1(this, _AssistantStream_currentToolCall, undefined, "f"); } break; } }; var messages$1 = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(messages$1, "__esModule", { value: true }); messages$1.MessagesPage = messages$1.Messages = void 0; const resource_1$h = resource; const core_1$8 = requireCore$1(); const pagination_1$8 = pagination; class Messages extends resource_1$h.APIResource { /** * Create a message. */ create(threadId, body, options) { return this._client.post(`/threads/${threadId}/messages`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Retrieve a message. */ retrieve(threadId, messageId, options) { return this._client.get(`/threads/${threadId}/messages/${messageId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Modifies a message. */ update(threadId, messageId, body, options) { return this._client.post(`/threads/${threadId}/messages/${messageId}`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } list(threadId, query = {}, options) { if ((0, core_1$8.isRequestOptions)(query)) { return this.list(threadId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Deletes a message. */ del(threadId, messageId, options) { return this._client.delete(`/threads/${threadId}/messages/${messageId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } } messages$1.Messages = Messages; class MessagesPage extends pagination_1$8.CursorPage { } messages$1.MessagesPage = MessagesPage; Messages.MessagesPage = MessagesPage; var runs = {}; var steps = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(steps, "__esModule", { value: true }); steps.RunStepsPage = steps.Steps = void 0; const resource_1$g = resource; const core_1$7 = requireCore$1(); const pagination_1$7 = pagination; class Steps extends resource_1$g.APIResource { retrieve(threadId, runId, stepId, query = {}, options) { if ((0, core_1$7.isRequestOptions)(query)) { return this.retrieve(threadId, runId, stepId, {}, query); } return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } list(threadId, runId, query = {}, options) { if ((0, core_1$7.isRequestOptions)(query)) { return this.list(threadId, runId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } } steps.Steps = Steps; class RunStepsPage extends pagination_1$7.CursorPage { } steps.RunStepsPage = RunStepsPage; Steps.RunStepsPage = RunStepsPage; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$a = (commonjsGlobal && commonjsGlobal.__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$a = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$a = (commonjsGlobal && commonjsGlobal.__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$a(result, mod, k); __setModuleDefault$a(result, mod); return result; }; Object.defineProperty(runs, "__esModule", { value: true }); runs.RunsPage = runs.Runs = void 0; const resource_1$f = resource; const core_1$6 = requireCore$1(); const AssistantStream_1$1 = AssistantStream$1; const core_2$1 = requireCore$1(); const StepsAPI = __importStar$a(steps); const steps_1 = steps; const pagination_1$6 = pagination; class Runs extends resource_1$f.APIResource { constructor() { super(...arguments); this.steps = new StepsAPI.Steps(this._client); } create(threadId, params, options) { const { include, ...body } = params; return this._client.post(`/threads/${threadId}/runs`, { query: { include }, body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, stream: params.stream ?? false, }); } /** * Retrieves a run. */ retrieve(threadId, runId, options) { return this._client.get(`/threads/${threadId}/runs/${runId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Modifies a run. */ update(threadId, runId, body, options) { return this._client.post(`/threads/${threadId}/runs/${runId}`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } list(threadId, query = {}, options) { if ((0, core_1$6.isRequestOptions)(query)) { return this.list(threadId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Cancels a run that is `in_progress`. */ cancel(threadId, runId, options) { return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * A helper to create a run an poll for a terminal state. More information on Run * lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */ async createAndPoll(threadId, body, options) { const run = await this.create(threadId, body, options); return await this.poll(threadId, run.id, options); } /** * Create a Run stream * * @deprecated use `stream` instead */ createAndStream(threadId, body, options) { return AssistantStream_1$1.AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); } /** * A helper to poll a run status until it reaches a terminal state. More * information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */ async poll(threadId, runId, options) { const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; if (options?.pollIntervalMs) { headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); } while (true) { const { data: run, response } = await this.retrieve(threadId, runId, { ...options, headers: { ...options?.headers, ...headers }, }).withResponse(); switch (run.status) { //If we are in any sort of intermediate state we poll case 'queued': case 'in_progress': case 'cancelling': let sleepInterval = 5000; if (options?.pollIntervalMs) { sleepInterval = options.pollIntervalMs; } else { const headerInterval = response.headers.get('openai-poll-after-ms'); if (headerInterval) { const headerIntervalMs = parseInt(headerInterval); if (!isNaN(headerIntervalMs)) { sleepInterval = headerIntervalMs; } } } await (0, core_2$1.sleep)(sleepInterval); break; //We return the run in any terminal state. case 'requires_action': case 'incomplete': case 'cancelled': case 'completed': case 'failed': case 'expired': return run; } } } /** * Create a Run stream */ stream(threadId, body, options) { return AssistantStream_1$1.AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); } submitToolOutputs(threadId, runId, body, options) { return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, stream: body.stream ?? false, }); } /** * A helper to submit a tool output to a run and poll for a terminal run state. * More information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */ async submitToolOutputsAndPoll(threadId, runId, body, options) { const run = await this.submitToolOutputs(threadId, runId, body, options); return await this.poll(threadId, run.id, options); } /** * Submit the tool outputs from a previous run and stream the run to a terminal * state. More information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */ submitToolOutputsStream(threadId, runId, body, options) { return AssistantStream_1$1.AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options); } } runs.Runs = Runs; class RunsPage extends pagination_1$6.CursorPage { } runs.RunsPage = RunsPage; Runs.RunsPage = RunsPage; Runs.Steps = steps_1.Steps; Runs.RunStepsPage = steps_1.RunStepsPage; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$9 = (commonjsGlobal && commonjsGlobal.__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$9 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$9 = (commonjsGlobal && commonjsGlobal.__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$9(result, mod, k); __setModuleDefault$9(result, mod); return result; }; Object.defineProperty(threads, "__esModule", { value: true }); threads.Threads = void 0; const resource_1$e = resource; const core_1$5 = requireCore$1(); const AssistantStream_1 = AssistantStream$1; const MessagesAPI = __importStar$9(messages$1); const messages_1 = messages$1; const RunsAPI = __importStar$9(runs); const runs_1 = runs; class Threads extends resource_1$e.APIResource { constructor() { super(...arguments); this.runs = new RunsAPI.Runs(this._client); this.messages = new MessagesAPI.Messages(this._client); } create(body = {}, options) { if ((0, core_1$5.isRequestOptions)(body)) { return this.create({}, body); } return this._client.post('/threads', { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Retrieves a thread. */ retrieve(threadId, options) { return this._client.get(`/threads/${threadId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Modifies a thread. */ update(threadId, body, options) { return this._client.post(`/threads/${threadId}`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Delete a thread. */ del(threadId, options) { return this._client.delete(`/threads/${threadId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } createAndRun(body, options) { return this._client.post('/threads/runs', { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, stream: body.stream ?? false, }); } /** * A helper to create a thread, start a run and then poll for a terminal state. * More information on Run lifecycles can be found here: * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps */ async createAndRunPoll(body, options) { const run = await this.createAndRun(body, options); return await this.runs.poll(run.thread_id, run.id, options); } /** * Create a thread and stream the run back */ createAndRunStream(body, options) { return AssistantStream_1.AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); } } threads.Threads = Threads; Threads.Runs = runs_1.Runs; Threads.RunsPage = runs_1.RunsPage; Threads.Messages = messages_1.Messages; Threads.MessagesPage = messages_1.MessagesPage; var vectorStores = {}; var fileBatches = {}; var Util = {}; Object.defineProperty(Util, "__esModule", { value: true }); Util.allSettledWithThrow = void 0; /** * Like `Promise.allSettled()` but throws an error if any promises are rejected. */ const allSettledWithThrow = async (promises) => { const results = await Promise.allSettled(promises); const rejected = results.filter((result) => result.status === 'rejected'); if (rejected.length) { for (const result of rejected) { console.error(result.reason); } throw new Error(`${rejected.length} promise(s) failed - see the above errors`); } // Note: TS was complaining about using `.filter().map()` here for some reason const values = []; for (const result of results) { if (result.status === 'fulfilled') { values.push(result.value); } } return values; }; Util.allSettledWithThrow = allSettledWithThrow; var files$2 = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(files$2, "__esModule", { value: true }); files$2.VectorStoreFilesPage = files$2.Files = void 0; const resource_1$d = resource; const core_1$4 = requireCore$1(); const pagination_1$5 = pagination; let Files$1 = class Files extends resource_1$d.APIResource { /** * Create a vector store file by attaching a * [File](https://platform.openai.com/docs/api-reference/files) to a * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). */ create(vectorStoreId, body, options) { return this._client.post(`/vector_stores/${vectorStoreId}/files`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Retrieves a vector store file. */ retrieve(vectorStoreId, fileId, options) { return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } list(vectorStoreId, query = {}, options) { if ((0, core_1$4.isRequestOptions)(query)) { return this.list(vectorStoreId, {}, query); } return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Delete a vector store file. This will remove the file from the vector store but * the file itself will not be deleted. To delete the file, use the * [delete file](https://platform.openai.com/docs/api-reference/files/delete) * endpoint. */ del(vectorStoreId, fileId, options) { return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Attach a file to the given vector store and wait for it to be processed. */ async createAndPoll(vectorStoreId, body, options) { const file = await this.create(vectorStoreId, body, options); return await this.poll(vectorStoreId, file.id, options); } /** * Wait for the vector store file to finish processing. * * Note: this will return even if the file failed to process, you need to check * file.last_error and file.status to handle these cases */ async poll(vectorStoreId, fileId, options) { const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; if (options?.pollIntervalMs) { headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); } while (true) { const fileResponse = await this.retrieve(vectorStoreId, fileId, { ...options, headers, }).withResponse(); const file = fileResponse.data; switch (file.status) { case 'in_progress': let sleepInterval = 5000; if (options?.pollIntervalMs) { sleepInterval = options.pollIntervalMs; } else { const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); if (headerInterval) { const headerIntervalMs = parseInt(headerInterval); if (!isNaN(headerIntervalMs)) { sleepInterval = headerIntervalMs; } } } await (0, core_1$4.sleep)(sleepInterval); break; case 'failed': case 'completed': return file; } } } /** * Upload a file to the `files` API and then attach it to the given vector store. * * Note the file will be asynchronously processed (you can use the alternative * polling helper method to wait for processing to complete). */ async upload(vectorStoreId, file, options) { const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); return this.create(vectorStoreId, { file_id: fileInfo.id }, options); } /** * Add a file to a vector store and poll until processing is complete. */ async uploadAndPoll(vectorStoreId, file, options) { const fileInfo = await this.upload(vectorStoreId, file, options); return await this.poll(vectorStoreId, fileInfo.id, options); } }; files$2.Files = Files$1; class VectorStoreFilesPage extends pagination_1$5.CursorPage { } files$2.VectorStoreFilesPage = VectorStoreFilesPage; Files$1.VectorStoreFilesPage = VectorStoreFilesPage; (function (exports) { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(exports, "__esModule", { value: true }); exports.VectorStoreFilesPage = exports.FileBatches = void 0; const resource_1 = resource; const core_1 = requireCore$1(); const core_2 = requireCore$1(); const Util_1 = Util; const files_1 = files$2; Object.defineProperty(exports, "VectorStoreFilesPage", { enumerable: true, get: function () { return files_1.VectorStoreFilesPage; } }); class FileBatches extends resource_1.APIResource { /** * Create a vector store file batch. */ create(vectorStoreId, body, options) { return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Retrieves a vector store file batch. */ retrieve(vectorStoreId, batchId, options) { return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Cancel a vector store file batch. This attempts to cancel the processing of * files in this batch as soon as possible. */ cancel(vectorStoreId, batchId, options) { return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Create a vector store batch and poll until all files have been processed. */ async createAndPoll(vectorStoreId, body, options) { const batch = await this.create(vectorStoreId, body); return await this.poll(vectorStoreId, batch.id, options); } listFiles(vectorStoreId, batchId, query = {}, options) { if ((0, core_1.isRequestOptions)(query)) { return this.listFiles(vectorStoreId, batchId, {}, query); } return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, files_1.VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } }); } /** * Wait for the given file batch to be processed. * * Note: this will return even if one of the files failed to process, you need to * check batch.file_counts.failed_count to handle this case. */ async poll(vectorStoreId, batchId, options) { const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; if (options?.pollIntervalMs) { headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); } while (true) { const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, { ...options, headers, }).withResponse(); switch (batch.status) { case 'in_progress': let sleepInterval = 5000; if (options?.pollIntervalMs) { sleepInterval = options.pollIntervalMs; } else { const headerInterval = response.headers.get('openai-poll-after-ms'); if (headerInterval) { const headerIntervalMs = parseInt(headerInterval); if (!isNaN(headerIntervalMs)) { sleepInterval = headerIntervalMs; } } } await (0, core_2.sleep)(sleepInterval); break; case 'failed': case 'cancelled': case 'completed': return batch; } } } /** * Uploads the given files concurrently and then creates a vector store file batch. * * The concurrency limit is configurable using the `maxConcurrency` parameter. */ async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { if (files == null || files.length == 0) { throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); } const configuredConcurrency = options?.maxConcurrency ?? 5; // We cap the number of workers at the number of files (so we don't start any unnecessary workers) const concurrencyLimit = Math.min(configuredConcurrency, files.length); const client = this._client; const fileIterator = files.values(); const allFileIds = [...fileIds]; // This code is based on this design. The libraries don't accommodate our environment limits. // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all async function processFiles(iterator) { for (let item of iterator) { const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); allFileIds.push(fileObj.id); } } // Start workers to process results const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); // Wait for all processing to complete. await (0, Util_1.allSettledWithThrow)(workers); return await this.createAndPoll(vectorStoreId, { file_ids: allFileIds, }); } } exports.FileBatches = FileBatches; } (fileBatches)); // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$8 = (commonjsGlobal && commonjsGlobal.__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$8 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$8 = (commonjsGlobal && commonjsGlobal.__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$8(result, mod, k); __setModuleDefault$8(result, mod); return result; }; Object.defineProperty(vectorStores, "__esModule", { value: true }); vectorStores.VectorStoresPage = vectorStores.VectorStores = void 0; const resource_1$c = resource; const core_1$3 = requireCore$1(); const FileBatchesAPI = __importStar$8(fileBatches); const file_batches_1 = fileBatches; const FilesAPI = __importStar$8(files$2); const files_1 = files$2; const pagination_1$4 = pagination; class VectorStores extends resource_1$c.APIResource { constructor() { super(...arguments); this.files = new FilesAPI.Files(this._client); this.fileBatches = new FileBatchesAPI.FileBatches(this._client); } /** * Create a vector store. */ create(body, options) { return this._client.post('/vector_stores', { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Retrieves a vector store. */ retrieve(vectorStoreId, options) { return this._client.get(`/vector_stores/${vectorStoreId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Modifies a vector store. */ update(vectorStoreId, body, options) { return this._client.post(`/vector_stores/${vectorStoreId}`, { body, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } list(query = {}, options) { if ((0, core_1$3.isRequestOptions)(query)) { return this.list({}, query); } return this._client.getAPIList('/vector_stores', VectorStoresPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** * Delete a vector store. */ del(vectorStoreId, options) { return this._client.delete(`/vector_stores/${vectorStoreId}`, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } } vectorStores.VectorStores = VectorStores; class VectorStoresPage extends pagination_1$4.CursorPage { } vectorStores.VectorStoresPage = VectorStoresPage; VectorStores.VectorStoresPage = VectorStoresPage; VectorStores.Files = files_1.Files; VectorStores.VectorStoreFilesPage = files_1.VectorStoreFilesPage; VectorStores.FileBatches = file_batches_1.FileBatches; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$7 = (commonjsGlobal && commonjsGlobal.__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$7 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$7 = (commonjsGlobal && commonjsGlobal.__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$7(result, mod, k); __setModuleDefault$7(result, mod); return result; }; Object.defineProperty(beta, "__esModule", { value: true }); beta.Beta = void 0; const resource_1$b = resource; const AssistantsAPI = __importStar$7(assistants); const ChatAPI = __importStar$7(chat); const assistants_1 = assistants; const ThreadsAPI = __importStar$7(threads); const threads_1 = threads; const VectorStoresAPI = __importStar$7(vectorStores); const vector_stores_1 = vectorStores; class Beta extends resource_1$b.APIResource { constructor() { super(...arguments); this.vectorStores = new VectorStoresAPI.VectorStores(this._client); this.chat = new ChatAPI.Chat(this._client); this.assistants = new AssistantsAPI.Assistants(this._client); this.threads = new ThreadsAPI.Threads(this._client); } } beta.Beta = Beta; Beta.VectorStores = vector_stores_1.VectorStores; Beta.VectorStoresPage = vector_stores_1.VectorStoresPage; Beta.Assistants = assistants_1.Assistants; Beta.AssistantsPage = assistants_1.AssistantsPage; Beta.Threads = threads_1.Threads; var completions = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(completions, "__esModule", { value: true }); completions.Completions = void 0; const resource_1$a = resource; class Completions extends resource_1$a.APIResource { create(body, options) { return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); } } completions.Completions = Completions; var embeddings = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(embeddings, "__esModule", { value: true }); embeddings.Embeddings = void 0; const resource_1$9 = resource; class Embeddings extends resource_1$9.APIResource { /** * Creates an embedding vector representing the input text. */ create(body, options) { return this._client.post('/embeddings', { body, ...options }); } } embeddings.Embeddings = Embeddings; var files$1 = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$6 = (commonjsGlobal && commonjsGlobal.__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$6 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$6 = (commonjsGlobal && commonjsGlobal.__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$6(result, mod, k); __setModuleDefault$6(result, mod); return result; }; Object.defineProperty(files$1, "__esModule", { value: true }); files$1.FileObjectsPage = files$1.Files = void 0; const resource_1$8 = resource; const core_1$2 = requireCore$1(); const core_2 = requireCore$1(); const error_1$p = requireError(); const Core$2 = __importStar$6(requireCore$1()); const pagination_1$3 = pagination; class Files extends resource_1$8.APIResource { /** * Upload a file that can be used across various endpoints. Individual files can be * up to 512 MB, and the size of all files uploaded by one organization can be up * to 100 GB. * * The Assistants API supports files up to 2 million tokens and of specific file * types. See the * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for * details. * * The Fine-tuning API only supports `.jsonl` files. The input also has certain * required formats for fine-tuning * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) * models. * * The Batch API only supports `.jsonl` files up to 100 MB in size. The input also * has a specific required * [format](https://platform.openai.com/docs/api-reference/batch/request-input). * * Please [contact us](https://help.openai.com/) if you need to increase these * storage limits. */ create(body, options) { return this._client.post('/files', Core$2.multipartFormRequestOptions({ body, ...options })); } /** * Returns information about a specific file. */ retrieve(fileId, options) { return this._client.get(`/files/${fileId}`, options); } list(query = {}, options) { if ((0, core_1$2.isRequestOptions)(query)) { return this.list({}, query); } return this._client.getAPIList('/files', FileObjectsPage, { query, ...options }); } /** * Delete a file. */ del(fileId, options) { return this._client.delete(`/files/${fileId}`, options); } /** * Returns the contents of the specified file. */ content(fileId, options) { return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true }); } /** * Returns the contents of the specified file. * * @deprecated The `.content()` method should be used instead */ retrieveContent(fileId, options) { return this._client.get(`/files/${fileId}/content`, { ...options, headers: { Accept: 'application/json', ...options?.headers }, }); } /** * Waits for the given file to be processed, default timeout is 30 mins. */ async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); const start = Date.now(); let file = await this.retrieve(id); while (!file.status || !TERMINAL_STATES.has(file.status)) { await (0, core_2.sleep)(pollInterval); file = await this.retrieve(id); if (Date.now() - start > maxWait) { throw new error_1$p.APIConnectionTimeoutError({ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, }); } } return file; } } files$1.Files = Files; /** * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ class FileObjectsPage extends pagination_1$3.Page { } files$1.FileObjectsPage = FileObjectsPage; Files.FileObjectsPage = FileObjectsPage; var fineTuning = {}; var jobs = {}; var checkpoints = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(checkpoints, "__esModule", { value: true }); checkpoints.FineTuningJobCheckpointsPage = checkpoints.Checkpoints = void 0; const resource_1$7 = resource; const core_1$1 = requireCore$1(); const pagination_1$2 = pagination; class Checkpoints extends resource_1$7.APIResource { list(fineTuningJobId, query = {}, options) { if ((0, core_1$1.isRequestOptions)(query)) { return this.list(fineTuningJobId, {}, query); } return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options }); } } checkpoints.Checkpoints = Checkpoints; class FineTuningJobCheckpointsPage extends pagination_1$2.CursorPage { } checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$5 = (commonjsGlobal && commonjsGlobal.__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$5 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$5 = (commonjsGlobal && commonjsGlobal.__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$5(result, mod, k); __setModuleDefault$5(result, mod); return result; }; Object.defineProperty(jobs, "__esModule", { value: true }); jobs.FineTuningJobEventsPage = jobs.FineTuningJobsPage = jobs.Jobs = void 0; const resource_1$6 = resource; const core_1 = requireCore$1(); const CheckpointsAPI = __importStar$5(checkpoints); const checkpoints_1 = checkpoints; const pagination_1$1 = pagination; class Jobs extends resource_1$6.APIResource { constructor() { super(...arguments); this.checkpoints = new CheckpointsAPI.Checkpoints(this._client); } /** * Creates a fine-tuning job which begins the process of creating a new model from * a given dataset. * * Response includes details of the enqueued job including job status and the name * of the fine-tuned models once complete. * * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) */ create(body, options) { return this._client.post('/fine_tuning/jobs', { body, ...options }); } /** * Get info about a fine-tuning job. * * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) */ retrieve(fineTuningJobId, options) { return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); } list(query = {}, options) { if ((0, core_1.isRequestOptions)(query)) { return this.list({}, query); } return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); } /** * Immediately cancel a fine-tune job. */ cancel(fineTuningJobId, options) { return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); } listEvents(fineTuningJobId, query = {}, options) { if ((0, core_1.isRequestOptions)(query)) { return this.listEvents(fineTuningJobId, {}, query); } return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { query, ...options, }); } } jobs.Jobs = Jobs; class FineTuningJobsPage extends pagination_1$1.CursorPage { } jobs.FineTuningJobsPage = FineTuningJobsPage; class FineTuningJobEventsPage extends pagination_1$1.CursorPage { } jobs.FineTuningJobEventsPage = FineTuningJobEventsPage; Jobs.FineTuningJobsPage = FineTuningJobsPage; Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage; Jobs.Checkpoints = checkpoints_1.Checkpoints; Jobs.FineTuningJobCheckpointsPage = checkpoints_1.FineTuningJobCheckpointsPage; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$4 = (commonjsGlobal && commonjsGlobal.__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$4 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$4 = (commonjsGlobal && commonjsGlobal.__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$4(result, mod, k); __setModuleDefault$4(result, mod); return result; }; Object.defineProperty(fineTuning, "__esModule", { value: true }); fineTuning.FineTuning = void 0; const resource_1$5 = resource; const JobsAPI = __importStar$4(jobs); const jobs_1 = jobs; class FineTuning extends resource_1$5.APIResource { constructor() { super(...arguments); this.jobs = new JobsAPI.Jobs(this._client); } } fineTuning.FineTuning = FineTuning; FineTuning.Jobs = jobs_1.Jobs; FineTuning.FineTuningJobsPage = jobs_1.FineTuningJobsPage; FineTuning.FineTuningJobEventsPage = jobs_1.FineTuningJobEventsPage; var images = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$3 = (commonjsGlobal && commonjsGlobal.__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$3 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$3 = (commonjsGlobal && commonjsGlobal.__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$3(result, mod, k); __setModuleDefault$3(result, mod); return result; }; Object.defineProperty(images, "__esModule", { value: true }); images.Images = void 0; const resource_1$4 = resource; const Core$1 = __importStar$3(requireCore$1()); class Images extends resource_1$4.APIResource { /** * Creates a variation of a given image. */ createVariation(body, options) { return this._client.post('/images/variations', Core$1.multipartFormRequestOptions({ body, ...options })); } /** * Creates an edited or extended image given an original image and a prompt. */ edit(body, options) { return this._client.post('/images/edits', Core$1.multipartFormRequestOptions({ body, ...options })); } /** * Creates an image given a prompt. */ generate(body, options) { return this._client.post('/images/generations', { body, ...options }); } } images.Images = Images; var models = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(models, "__esModule", { value: true }); models.ModelsPage = models.Models = void 0; const resource_1$3 = resource; const pagination_1 = pagination; class Models extends resource_1$3.APIResource { /** * Retrieves a model instance, providing basic information about the model such as * the owner and permissioning. */ retrieve(model, options) { return this._client.get(`/models/${model}`, options); } /** * Lists the currently available models, and provides basic information about each * one such as the owner and availability. */ list(options) { return this._client.getAPIList('/models', ModelsPage, options); } /** * Delete a fine-tuned model. You must have the Owner role in your organization to * delete a model. */ del(model, options) { return this._client.delete(`/models/${model}`, options); } } models.Models = Models; /** * Note: no pagination actually occurs yet, this is for forwards-compatibility. */ class ModelsPage extends pagination_1.Page { } models.ModelsPage = ModelsPage; Models.ModelsPage = ModelsPage; var moderations = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. Object.defineProperty(moderations, "__esModule", { value: true }); moderations.Moderations = void 0; const resource_1$2 = resource; class Moderations extends resource_1$2.APIResource { /** * Classifies if text and/or image inputs are potentially harmful. Learn more in * the [moderation guide](https://platform.openai.com/docs/guides/moderation). */ create(body, options) { return this._client.post('/moderations', { body, ...options }); } } moderations.Moderations = Moderations; var uploads = {}; var parts = {}; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$2 = (commonjsGlobal && commonjsGlobal.__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$2 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$2 = (commonjsGlobal && commonjsGlobal.__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$2(result, mod, k); __setModuleDefault$2(result, mod); return result; }; Object.defineProperty(parts, "__esModule", { value: true }); parts.Parts = void 0; const resource_1$1 = resource; const Core = __importStar$2(requireCore$1()); class Parts extends resource_1$1.APIResource { /** * Adds a * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. * A Part represents a chunk of bytes from the file you are trying to upload. * * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload * maximum of 8 GB. * * It is possible to add multiple Parts in parallel. You can decide the intended * order of the Parts when you * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). */ create(uploadId, body, options) { return this._client.post(`/uploads/${uploadId}/parts`, Core.multipartFormRequestOptions({ body, ...options })); } } parts.Parts = Parts; // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding$1 = (commonjsGlobal && commonjsGlobal.__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$1 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar$1 = (commonjsGlobal && commonjsGlobal.__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$1(result, mod, k); __setModuleDefault$1(result, mod); return result; }; Object.defineProperty(uploads, "__esModule", { value: true }); uploads.Uploads = void 0; const resource_1 = resource; const PartsAPI = __importStar$1(parts); const parts_1 = parts; class Uploads extends resource_1.APIResource { constructor() { super(...arguments); this.parts = new PartsAPI.Parts(this._client); } /** * Creates an intermediate * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object * that you can add * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. * Currently, an Upload can accept at most 8 GB in total and expires after an hour * after you create it. * * Once you complete the Upload, we will create a * [File](https://platform.openai.com/docs/api-reference/files/object) object that * contains all the parts you uploaded. This File is usable in the rest of our * platform as a regular File object. * * For certain `purpose`s, the correct `mime_type` must be specified. Please refer * to documentation for the supported MIME types for your use case: * * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search/supported-files) * * For guidance on the proper filename extensions for each purpose, please follow * the documentation on * [creating a File](https://platform.openai.com/docs/api-reference/files/create). */ create(body, options) { return this._client.post('/uploads', { body, ...options }); } /** * Cancels the Upload. No Parts may be added after an Upload is cancelled. */ cancel(uploadId, options) { return this._client.post(`/uploads/${uploadId}/cancel`, options); } /** * Completes the * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). * * Within the returned Upload object, there is a nested * [File](https://platform.openai.com/docs/api-reference/files/object) object that * is ready to use in the rest of the platform. * * You can specify the order of the Parts by passing in an ordered list of the Part * IDs. * * The number of bytes uploaded upon completion must match the number of bytes * initially specified when creating the Upload object. No Parts may be added after * an Upload is completed. */ complete(uploadId, body, options) { return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options }); } } uploads.Uploads = Uploads; Uploads.Parts = parts_1.Parts; (function (exports) { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding = (commonjsGlobal && commonjsGlobal.__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 __exportStar = (commonjsGlobal && commonjsGlobal.__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.Uploads = exports.Moderations = exports.Models = exports.ModelsPage = exports.Images = exports.FineTuning = exports.Files = exports.FileObjectsPage = exports.Embeddings = exports.Completions = exports.Beta = exports.Batches = exports.BatchesPage = exports.Audio = void 0; __exportStar(chat$2, exports); __exportStar(shared, exports); var audio_1 = audio$1; Object.defineProperty(exports, "Audio", { enumerable: true, get: function () { return audio_1.Audio; } }); var batches_1 = batches; Object.defineProperty(exports, "BatchesPage", { enumerable: true, get: function () { return batches_1.BatchesPage; } }); Object.defineProperty(exports, "Batches", { enumerable: true, get: function () { return batches_1.Batches; } }); var beta_1 = beta; Object.defineProperty(exports, "Beta", { enumerable: true, get: function () { return beta_1.Beta; } }); var completions_1 = completions; Object.defineProperty(exports, "Completions", { enumerable: true, get: function () { return completions_1.Completions; } }); var embeddings_1 = embeddings; Object.defineProperty(exports, "Embeddings", { enumerable: true, get: function () { return embeddings_1.Embeddings; } }); var files_1 = files$1; 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_tuning_1 = fineTuning; Object.defineProperty(exports, "FineTuning", { enumerable: true, get: function () { return fine_tuning_1.FineTuning; } }); var images_1 = images; Object.defineProperty(exports, "Images", { enumerable: true, get: function () { return images_1.Images; } }); var models_1 = models; 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 = moderations; Object.defineProperty(exports, "Moderations", { enumerable: true, get: function () { return moderations_1.Moderations; } }); var uploads_1 = uploads; Object.defineProperty(exports, "Uploads", { enumerable: true, get: function () { return uploads_1.Uploads; } }); } (resources)); (function (module, exports) { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. var __createBinding = (commonjsGlobal && commonjsGlobal.__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 = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (commonjsGlobal && commonjsGlobal.__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.AzureOpenAI = 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.OpenAIError = exports.OpenAI = void 0; const qs$1 = __importStar(qs); const Core = __importStar(requireCore$1()); const Errors = __importStar(requireError()); __importStar(pagination); const Uploads = __importStar(uploads$1); const API = __importStar(resources); const batches_1 = batches; const completions_1 = completions; const embeddings_1 = embeddings; const files_1 = files$1; const images_1 = images; const models_1 = models; const moderations_1 = moderations; const audio_1 = audio$1; const beta_1 = beta; const chat_1 = chat$1; const fine_tuning_1 = fineTuning; const uploads_1 = uploads; /** * API Client for interfacing with the OpenAI API. */ class OpenAI extends Core.APIClient { /** * API Client for interfacing with the OpenAI API. * * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, project = Core.readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) { if (apiKey === undefined) { throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); } const options = { apiKey, organization, project, ...opts, baseURL: baseURL || `https://api.openai.com/v1`, }; if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); } super({ baseURL: options.baseURL, timeout: options.timeout ?? 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.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.beta = new API.Beta(this); this.batches = new API.Batches(this); this.uploads = new API.Uploads(this); this._options = options; this.apiKey = apiKey; this.organization = organization; this.project = project; } defaultQuery() { return this._options.defaultQuery; } defaultHeaders(opts) { return { ...super.defaultHeaders(opts), 'OpenAI-Organization': this.organization, 'OpenAI-Project': this.project, ...this._options.defaultHeaders, }; } authHeaders(opts) { return { Authorization: `Bearer ${this.apiKey}` }; } stringifyQuery(query) { return qs$1.stringify(query, { arrayFormat: 'brackets' }); } } exports.OpenAI = OpenAI; _a = OpenAI; OpenAI.OpenAI = _a; OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes OpenAI.OpenAIError = Errors.OpenAIError; 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; OpenAI.toFile = Uploads.toFile; OpenAI.fileFromPath = Uploads.fileFromPath; var error_1 = requireError(); Object.defineProperty(exports, "OpenAIError", { enumerable: true, get: function () { return error_1.OpenAIError; } }); Object.defineProperty(exports, "APIError", { enumerable: true, get: function () { return error_1.APIError; } }); Object.defineProperty(exports, "APIConnectionError", { enumerable: true, get: function () { return error_1.APIConnectionError; } }); Object.defineProperty(exports, "APIConnectionTimeoutError", { enumerable: true, get: function () { return error_1.APIConnectionTimeoutError; } }); Object.defineProperty(exports, "APIUserAbortError", { enumerable: true, get: function () { return error_1.APIUserAbortError; } }); Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return error_1.NotFoundError; } }); Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return error_1.ConflictError; } }); Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return error_1.RateLimitError; } }); Object.defineProperty(exports, "BadRequestError", { enumerable: true, get: function () { return error_1.BadRequestError; } }); Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return error_1.AuthenticationError; } }); Object.defineProperty(exports, "InternalServerError", { enumerable: true, get: function () { return error_1.InternalServerError; } }); Object.defineProperty(exports, "PermissionDeniedError", { enumerable: true, get: function () { return error_1.PermissionDeniedError; } }); Object.defineProperty(exports, "UnprocessableEntityError", { enumerable: true, get: function () { return error_1.UnprocessableEntityError; } }); exports.toFile = Uploads.toFile; exports.fileFromPath = Uploads.fileFromPath; OpenAI.Completions = completions_1.Completions; OpenAI.Chat = chat_1.Chat; OpenAI.Embeddings = embeddings_1.Embeddings; OpenAI.Files = files_1.Files; OpenAI.FileObjectsPage = files_1.FileObjectsPage; OpenAI.Images = images_1.Images; OpenAI.Audio = audio_1.Audio; OpenAI.Moderations = moderations_1.Moderations; OpenAI.Models = models_1.Models; OpenAI.ModelsPage = models_1.ModelsPage; OpenAI.FineTuning = fine_tuning_1.FineTuning; OpenAI.Beta = beta_1.Beta; OpenAI.Batches = batches_1.Batches; OpenAI.BatchesPage = batches_1.BatchesPage; OpenAI.Uploads = uploads_1.Uploads; /** API Client for interfacing with the Azure OpenAI API. */ class AzureOpenAI extends OpenAI { /** * API Client for interfacing with the Azure OpenAI API. * * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'), apiVersion = Core.readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { if (!apiVersion) { throw new Errors.OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); } if (typeof azureADTokenProvider === 'function') { dangerouslyAllowBrowser = true; } if (!azureADTokenProvider && !apiKey) { throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); } if (azureADTokenProvider && apiKey) { throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); } // define a sentinel value to avoid any typing issues apiKey ?? (apiKey = API_KEY_SENTINEL); opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; if (!baseURL) { if (!endpoint) { endpoint = process.env['AZURE_OPENAI_ENDPOINT']; } if (!endpoint) { throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); } baseURL = `${endpoint}/openai`; } else { if (endpoint) { throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive'); } } super({ apiKey, baseURL, ...opts, ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), }); this.apiVersion = ''; this._azureADTokenProvider = azureADTokenProvider; this.apiVersion = apiVersion; this._deployment = deployment; } buildRequest(options) { if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { if (!Core.isObj(options.body)) { throw new Error('Expected request body to be an object'); } const model = this._deployment || options.body['model']; if (model !== undefined && !this.baseURL.includes('/deployments')) { options.path = `/deployments/${model}${options.path}`; } } return super.buildRequest(options); } async _getAzureADToken() { if (typeof this._azureADTokenProvider === 'function') { const token = await this._azureADTokenProvider(); if (!token || typeof token !== 'string') { throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`); } return token; } return undefined; } authHeaders(opts) { return {}; } async prepareOptions(opts) { /** * The user should provide a bearer token provider if they want * to use Azure AD authentication. The user shouldn't set the * Authorization header manually because the header is overwritten * with the Azure AD token if a bearer token provider is provided. */ if (opts.headers?.['api-key']) { return super.prepareOptions(opts); } const token = await this._getAzureADToken(); opts.headers ?? (opts.headers = {}); if (token) { opts.headers['Authorization'] = `Bearer ${token}`; } else if (this.apiKey !== API_KEY_SENTINEL) { opts.headers['api-key'] = this.apiKey; } else { throw new Errors.OpenAIError('Unable to handle auth'); } return super.prepareOptions(opts); } } exports.AzureOpenAI = AzureOpenAI; const _deployments_endpoints = new Set([ '/completions', '/chat/completions', '/embeddings', '/audio/transcriptions', '/audio/translations', '/audio/speech', '/images/generations', ]); const API_KEY_SENTINEL = ''; // ---------------------- End Azure ---------------------- exports = module.exports = OpenAI; module.exports.AzureOpenAI = AzureOpenAI; exports.default = OpenAI; } (openai, openai.exports)); var openaiExports = openai.exports; var retryPromise = {}; var timeout = {}; Object.defineProperty(timeout, "__esModule", { value: true }); timeout.timeout = void 0; timeout.timeout = function (millies, f) { if (millies === "INFINITELY") { return f(function () { return false; }); } var done = false; var doneF = function () { return done; }; return new Promise(function (resolve, reject) { var timeoutRef = setTimeout(function () { done = true; reject(new Error("Timeout after " + millies + "ms")); }, millies); var result = f(doneF); // result.finally(() => clearTimeout(timeoutRef)); result.then(function (r) { resolve(r); clearTimeout(timeoutRef); }, function (e) { reject(e); clearTimeout(timeoutRef); }); }); }; (function (exports) { var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (commonjsGlobal && commonjsGlobal.__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 __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NotRetryableError = exports.RetryError = exports.notEmpty = exports.customizeRetry = exports.customizeDecorator = exports.retryDecorator = exports.retry = exports.wait = exports.defaultRetryConfig = void 0; var timeout_1 = timeout; var fixedBackoff = function (attempt, delay) { return delay; }; var linearBackoff = function (attempt, delay) { return attempt * delay; }; var exponentialBackoff = function (attempt, delay) { return Math.pow(delay, attempt); }; exports.defaultRetryConfig = { backoff: "FIXED", delay: 100, logger: function () { return undefined; }, maxBackOff: 5 * 60 * 1000, retries: 10, timeout: 60 * 1000, until: function () { return true; }, retryIf: function () { return true; } }; function wait(ms) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve) { return setTimeout(resolve, ms); })]; }); }); } exports.wait = wait; function retry(f, config) { return __awaiter(this, void 0, void 0, function () { var effectiveConfig; return __generator(this, function (_a) { effectiveConfig = Object.assign({}, exports.defaultRetryConfig, config); return [2 /*return*/, timeout_1.timeout(effectiveConfig.timeout, function (done) { return _retry(f, effectiveConfig, done); })]; }); }); } exports.retry = retry; function retryDecorator(func, config) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return retry(function () { return func.apply(void 0, args); }, config); }; } exports.retryDecorator = retryDecorator; function customizeDecorator(customConfig) { return function (args, config) { return retryDecorator(args, Object.assign({}, customConfig, config)); }; } exports.customizeDecorator = customizeDecorator; // tslint:disable-next-line function customizeRetry(customConfig) { return function (f, c) { var customized = Object.assign({}, customConfig, c); return retry(f, customized); }; } exports.customizeRetry = customizeRetry; function _retry(f, config, done) { return __awaiter(this, void 0, void 0, function () { var lastError, delay, retries, i, result, error_1, millisToWait; return __generator(this, function (_a) { switch (_a.label) { case 0: switch (config.backoff) { case "EXPONENTIAL": delay = exponentialBackoff; break; case "FIXED": delay = fixedBackoff; break; case "LINEAR": delay = linearBackoff; break; default: delay = config.backoff; } if (config.retries === "INFINITELY") { retries = Number.MAX_SAFE_INTEGER; } else { retries = config.retries; } i = 0; _a.label = 1; case 1: if (!(i <= retries)) return [3 /*break*/, 8]; _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4 /*yield*/, f()]; case 3: result = _a.sent(); if (config.until(result)) { return [2 /*return*/, result]; } config.logger("Until condition not met by " + result); return [3 /*break*/, 5]; case 4: error_1 = _a.sent(); if (!config.retryIf(error_1)) { throw error_1; } if (error_1.name === NotRetryableError.name) { throw new RetryError("Met not retryable error. Last error: " + error_1, error_1); } lastError = error_1; config.logger("Retry failed: " + error_1.message); return [3 /*break*/, 5]; case 5: millisToWait = delay(i + 1, config.delay); return [4 /*yield*/, wait(millisToWait > config.maxBackOff ? config.maxBackOff : millisToWait)]; case 6: _a.sent(); if (done()) { return [3 /*break*/, 8]; } _a.label = 7; case 7: i++; return [3 /*break*/, 1]; case 8: throw new RetryError("All retries failed. Last error: " + lastError, lastError); } }); }); } exports.notEmpty = function (result) { if (Array.isArray(result)) { return result.length > 0; } return result !== null && result !== undefined; }; var RetryError = /** @class */ (function (_super) { __extends(RetryError, _super); /* istanbul ignore next */ function RetryError(message, lastError) { var _this = _super.call(this, message) || this; _this.lastError = lastError; return _this; } return RetryError; }(Error)); exports.RetryError = RetryError; // tslint:disable-next-line:max-classes-per-file var BaseError = /** @class */ (function () { function BaseError(message) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } this.message = message; Error.apply(this, args); } return BaseError; }()); BaseError.prototype = new Error(); // tslint:disable-next-line:max-classes-per-file var NotRetryableError = /** @class */ (function (_super) { __extends(NotRetryableError, _super); function NotRetryableError(message) { var _this = _super.call(this, message) || this; Object.defineProperty(_this, 'name', { value: _this.constructor.name }); return _this; } return NotRetryableError; }(BaseError)); exports.NotRetryableError = NotRetryableError; } (retryPromise)); var utils$4 = {exports: {}}; var windows; var hasRequiredWindows; function requireWindows () { if (hasRequiredWindows) return windows; hasRequiredWindows = 1; windows = isexe; isexe.sync = sync; var fs = require$$0$6; function checkPathExt (path, options) { var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT; if (!pathext) { return true } pathext = pathext.split(';'); if (pathext.indexOf('') !== -1) { return true } for (var i = 0; i < pathext.length; i++) { var p = pathext[i].toLowerCase(); if (p && path.substr(-p.length).toLowerCase() === p) { return true } } return false } function checkStat (stat, path, options) { if (!stat.isSymbolicLink() && !stat.isFile()) { return false } return checkPathExt(path, options) } function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, path, options)); }); } function sync (path, options) { return checkStat(fs.statSync(path), path, options) } return windows; } var mode; var hasRequiredMode; function requireMode () { if (hasRequiredMode) return mode; hasRequiredMode = 1; mode = isexe; isexe.sync = sync; var fs = require$$0$6; function isexe (path, options, cb) { fs.stat(path, function (er, stat) { cb(er, er ? false : checkStat(stat, options)); }); } function sync (path, options) { return checkStat(fs.statSync(path), options) } function checkStat (stat, options) { return stat.isFile() && checkMode(stat, options) } function checkMode (stat, options) { var mod = stat.mode; var uid = stat.uid; var gid = stat.gid; var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid(); var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid(); var u = parseInt('100', 8); var g = parseInt('010', 8); var o = parseInt('001', 8); var ug = u | g; var ret = (mod & o) || (mod & g) && gid === myGid || (mod & u) && uid === myUid || (mod & ug) && myUid === 0; return ret } return mode; } var core$1; if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { core$1 = requireWindows(); } else { core$1 = requireMode(); } var isexe_1 = isexe$1; isexe$1.sync = sync; function isexe$1 (path, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (!cb) { if (typeof Promise !== 'function') { throw new TypeError('callback not provided') } return new Promise(function (resolve, reject) { isexe$1(path, options || {}, function (er, is) { if (er) { reject(er); } else { resolve(is); } }); }) } core$1(path, options || {}, function (er, is) { // ignore EACCES because that just means we aren't allowed to run it if (er) { if (er.code === 'EACCES' || options && options.ignoreErrors) { er = null; is = false; } } cb(er, is); }); } function sync (path, options) { // my kingdom for a filtered catch try { return core$1.sync(path, options || {}) } catch (er) { if (options && options.ignoreErrors || er.code === 'EACCES') { return false } else { throw er } } } var which_1 = which$1; which$1.sync = whichSync; var isWindows$1 = process.platform === 'win32' || process.env.OSTYPE === 'cygwin' || process.env.OSTYPE === 'msys'; var path$5 = require$$0$3; var COLON = isWindows$1 ? ';' : ':'; var isexe = isexe_1; function getNotFoundError (cmd) { var er = new Error('not found: ' + cmd); er.code = 'ENOENT'; return er } function getPathInfo (cmd, opt) { var colon = opt.colon || COLON; var pathEnv = opt.path || process.env.PATH || ''; var pathExt = ['']; pathEnv = pathEnv.split(colon); var pathExtExe = ''; if (isWindows$1) { pathEnv.unshift(process.cwd()); pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'); pathExt = pathExtExe.split(colon); // Always test the cmd itself first. isexe will check to make sure // it's found in the pathExt set. if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') pathExt.unshift(''); } // If it has a slash, then we don't bother searching the pathenv. // just check the file itself, and that's it. if (cmd.match(/\//) || isWindows$1 && cmd.match(/\\/)) pathEnv = ['']; return { env: pathEnv, ext: pathExt, extExe: pathExtExe } } function which$1 (cmd, opt, cb) { if (typeof opt === 'function') { cb = opt; opt = {}; } var info = getPathInfo(cmd, opt); var pathEnv = info.env; var pathExt = info.ext; var pathExtExe = info.extExe; var found = [] ;(function F (i, l) { if (i === l) { if (opt.all && found.length) return cb(null, found) else return cb(getNotFoundError(cmd)) } var pathPart = pathEnv[i]; if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') pathPart = pathPart.slice(1, -1); var p = path$5.join(pathPart, cmd); if (!pathPart && (/^\.[\\\/]/).test(cmd)) { p = cmd.slice(0, 2) + p; } (function E (ii, ll) { if (ii === ll) return F(i + 1, l) var ext = pathExt[ii]; isexe(p + ext, { pathExt: pathExtExe }, function (er, is) { if (!er && is) { if (opt.all) found.push(p + ext); else return cb(null, p + ext) } return E(ii + 1, ll) }); })(0, pathExt.length); })(0, pathEnv.length); } function whichSync (cmd, opt) { opt = opt || {}; var info = getPathInfo(cmd, opt); var pathEnv = info.env; var pathExt = info.ext; var pathExtExe = info.extExe; var found = []; for (var i = 0, l = pathEnv.length; i < l; i ++) { var pathPart = pathEnv[i]; if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') pathPart = pathPart.slice(1, -1); var p = path$5.join(pathPart, cmd); if (!pathPart && /^\.[\\\/]/.test(cmd)) { p = cmd.slice(0, 2) + p; } for (var j = 0, ll = pathExt.length; j < ll; j ++) { var cur = p + pathExt[j]; var is; try { is = isexe.sync(cur, { pathExt: pathExtExe }); if (is) { if (opt.all) found.push(cur); else return cur } } catch (ex) {} } } if (opt.all && found.length) return found if (opt.nothrow) return null throw getNotFoundError(cmd) } /*jshint node:true*/ require$$0$9.exec; var isWindows = require$$1.platform().match(/win(32|64)/); var which = which_1; var nlRegexp = /\r\n|\r|\n/g; var streamRegexp = /^\[?(.*?)\]?$/; var filterEscapeRegexp = /[,]/; var whichCache = {}; /** * Parse progress line from ffmpeg stderr * * @param {String} line progress line * @return progress object * @private */ function parseProgressLine(line) { var progress = {}; // Remove all spaces after = and trim line = line.replace(/=\s+/g, '=').trim(); var progressParts = line.split(' '); // Split every progress part by "=" to get key and value for(var i = 0; i < progressParts.length; i++) { var progressSplit = progressParts[i].split('=', 2); var key = progressSplit[0]; var value = progressSplit[1]; // This is not a progress line if(typeof value === 'undefined') return null; progress[key] = value; } return progress; } var utils$3 = utils$4.exports = { isWindows: isWindows, streamRegexp: streamRegexp, /** * Copy an object keys into another one * * @param {Object} source source object * @param {Object} dest destination object * @private */ copy: function(source, dest) { Object.keys(source).forEach(function(key) { dest[key] = source[key]; }); }, /** * Create an argument list * * Returns a function that adds new arguments to the list. * It also has the following methods: * - clear() empties the argument list * - get() returns the argument list * - find(arg, count) finds 'arg' in the list and return the following 'count' items, or undefined if not found * - remove(arg, count) remove 'arg' in the list as well as the following 'count' items * * @private */ args: function() { var list = []; // Append argument(s) to the list var argfunc = function() { if (arguments.length === 1 && Array.isArray(arguments[0])) { list = list.concat(arguments[0]); } else { list = list.concat([].slice.call(arguments)); } }; // Clear argument list argfunc.clear = function() { list = []; }; // Return argument list argfunc.get = function() { return list; }; // Find argument 'arg' in list, and if found, return an array of the 'count' items that follow it argfunc.find = function(arg, count) { var index = list.indexOf(arg); if (index !== -1) { return list.slice(index + 1, index + 1 + (count || 0)); } }; // Find argument 'arg' in list, and if found, remove it as well as the 'count' items that follow it argfunc.remove = function(arg, count) { var index = list.indexOf(arg); if (index !== -1) { list.splice(index, (count || 0) + 1); } }; // Clone argument list argfunc.clone = function() { var cloned = utils$3.args(); cloned(list); return cloned; }; return argfunc; }, /** * Generate filter strings * * @param {String[]|Object[]} filters filter specifications. When using objects, * each must have the following properties: * @param {String} filters.filter filter name * @param {String|Array} [filters.inputs] (array of) input stream specifier(s) for the filter, * defaults to ffmpeg automatically choosing the first unused matching streams * @param {String|Array} [filters.outputs] (array of) output stream specifier(s) for the filter, * defaults to ffmpeg automatically assigning the output to the output file * @param {Object|String|Array} [filters.options] filter options, can be omitted to not set any options * @return String[] * @private */ makeFilterStrings: function(filters) { return filters.map(function(filterSpec) { if (typeof filterSpec === 'string') { return filterSpec; } var filterString = ''; // Filter string format is: // [input1][input2]...filter[output1][output2]... // The 'filter' part can optionaly have arguments: // filter=arg1:arg2:arg3 // filter=arg1=v1:arg2=v2:arg3=v3 // Add inputs if (Array.isArray(filterSpec.inputs)) { filterString += filterSpec.inputs.map(function(streamSpec) { return streamSpec.replace(streamRegexp, '[$1]'); }).join(''); } else if (typeof filterSpec.inputs === 'string') { filterString += filterSpec.inputs.replace(streamRegexp, '[$1]'); } // Add filter filterString += filterSpec.filter; // Add options if (filterSpec.options) { if (typeof filterSpec.options === 'string' || typeof filterSpec.options === 'number') { // Option string filterString += '=' + filterSpec.options; } else if (Array.isArray(filterSpec.options)) { // Option array (unnamed options) filterString += '=' + filterSpec.options.map(function(option) { if (typeof option === 'string' && option.match(filterEscapeRegexp)) { return '\'' + option + '\''; } else { return option; } }).join(':'); } else if (Object.keys(filterSpec.options).length) { // Option object (named options) filterString += '=' + Object.keys(filterSpec.options).map(function(option) { var value = filterSpec.options[option]; if (typeof value === 'string' && value.match(filterEscapeRegexp)) { value = '\'' + value + '\''; } return option + '=' + value; }).join(':'); } } // Add outputs if (Array.isArray(filterSpec.outputs)) { filterString += filterSpec.outputs.map(function(streamSpec) { return streamSpec.replace(streamRegexp, '[$1]'); }).join(''); } else if (typeof filterSpec.outputs === 'string') { filterString += filterSpec.outputs.replace(streamRegexp, '[$1]'); } return filterString; }); }, /** * Search for an executable * * Uses 'which' or 'where' depending on platform * * @param {String} name executable name * @param {Function} callback callback with signature (err, path) * @private */ which: function(name, callback) { if (name in whichCache) { return callback(null, whichCache[name]); } which(name, function(err, result){ if (err) { // Treat errors as not found return callback(null, whichCache[name] = ''); } callback(null, whichCache[name] = result); }); }, /** * Convert a [[hh:]mm:]ss[.xxx] timemark into seconds * * @param {String} timemark timemark string * @return Number * @private */ timemarkToSeconds: function(timemark) { if (typeof timemark === 'number') { return timemark; } if (timemark.indexOf(':') === -1 && timemark.indexOf('.') >= 0) { return Number(timemark); } var parts = timemark.split(':'); // add seconds var secs = Number(parts.pop()); if (parts.length) { // add minutes secs += Number(parts.pop()) * 60; } if (parts.length) { // add hours secs += Number(parts.pop()) * 3600; } return secs; }, /** * Extract codec data from ffmpeg stderr and emit 'codecData' event if appropriate * Call it with an initially empty codec object once with each line of stderr output until it returns true * * @param {FfmpegCommand} command event emitter * @param {String} stderrLine ffmpeg stderr output line * @param {Object} codecObject object used to accumulate codec data between calls * @return {Boolean} true if codec data is complete (and event was emitted), false otherwise * @private */ extractCodecData: function(command, stderrLine, codecsObject) { var inputPattern = /Input #[0-9]+, ([^ ]+),/; var durPattern = /Duration\: ([^,]+)/; var audioPattern = /Audio\: (.*)/; var videoPattern = /Video\: (.*)/; if (!('inputStack' in codecsObject)) { codecsObject.inputStack = []; codecsObject.inputIndex = -1; codecsObject.inInput = false; } var inputStack = codecsObject.inputStack; var inputIndex = codecsObject.inputIndex; var inInput = codecsObject.inInput; var format, dur, audio, video; if (format = stderrLine.match(inputPattern)) { inInput = codecsObject.inInput = true; inputIndex = codecsObject.inputIndex = codecsObject.inputIndex + 1; inputStack[inputIndex] = { format: format[1], audio: '', video: '', duration: '' }; } else if (inInput && (dur = stderrLine.match(durPattern))) { inputStack[inputIndex].duration = dur[1]; } else if (inInput && (audio = stderrLine.match(audioPattern))) { audio = audio[1].split(', '); inputStack[inputIndex].audio = audio[0]; inputStack[inputIndex].audio_details = audio; } else if (inInput && (video = stderrLine.match(videoPattern))) { video = video[1].split(', '); inputStack[inputIndex].video = video[0]; inputStack[inputIndex].video_details = video; } else if (/Output #\d+/.test(stderrLine)) { inInput = codecsObject.inInput = false; } else if (/Stream mapping:|Press (\[q\]|ctrl-c) to stop/.test(stderrLine)) { command.emit.apply(command, ['codecData'].concat(inputStack)); return true; } return false; }, /** * Extract progress data from ffmpeg stderr and emit 'progress' event if appropriate * * @param {FfmpegCommand} command event emitter * @param {String} stderrLine ffmpeg stderr data * @private */ extractProgress: function(command, stderrLine) { var progress = parseProgressLine(stderrLine); if (progress) { // build progress report object var ret = { frames: parseInt(progress.frame, 10), currentFps: parseInt(progress.fps, 10), currentKbps: progress.bitrate ? parseFloat(progress.bitrate.replace('kbits/s', '')) : 0, targetSize: parseInt(progress.size || progress.Lsize, 10), timemark: progress.time }; // calculate percent progress using duration if (command._ffprobeData && command._ffprobeData.format && command._ffprobeData.format.duration) { var duration = Number(command._ffprobeData.format.duration); if (!isNaN(duration)) ret.percent = (utils$3.timemarkToSeconds(ret.timemark) / duration) * 100; } command.emit('progress', ret); } }, /** * Extract error message(s) from ffmpeg stderr * * @param {String} stderr ffmpeg stderr data * @return {String} * @private */ extractError: function(stderr) { // Only return the last stderr lines that don't start with a space or a square bracket return stderr.split(nlRegexp).reduce(function(messages, message) { if (message.charAt(0) === ' ' || message.charAt(0) === '[') { return []; } else { messages.push(message); return messages; } }, []).join('\n'); }, /** * Creates a line ring buffer object with the following methods: * - append(str) : appends a string or buffer * - get() : returns the whole string * - close() : prevents further append() calls and does a last call to callbacks * - callback(cb) : calls cb for each line (incl. those already in the ring) * * @param {Number} maxLines maximum number of lines to store (<= 0 for unlimited) */ linesRing: function(maxLines) { var cbs = []; var lines = []; var current = null; var closed = false; var max = maxLines - 1; function emit(line) { cbs.forEach(function(cb) { cb(line); }); } return { callback: function(cb) { lines.forEach(function(l) { cb(l); }); cbs.push(cb); }, append: function(str) { if (closed) return; if (str instanceof Buffer) str = '' + str; if (!str || str.length === 0) return; var newLines = str.split(nlRegexp); if (newLines.length === 1) { if (current !== null) { current = current + newLines.shift(); } else { current = newLines.shift(); } } else { if (current !== null) { current = current + newLines.shift(); emit(current); lines.push(current); } current = newLines.pop(); newLines.forEach(function(l) { emit(l); lines.push(l); }); if (max > -1 && lines.length > max) { lines.splice(0, lines.length - max); } } }, get: function() { if (current !== null) { return lines.concat([current]).join('\n'); } else { return lines.join('\n'); } }, close: function() { if (closed) return; if (current !== null) { emit(current); lines.push(current); if (max > -1 && lines.length > max) { lines.shift(); } current = null; } closed = true; } }; } }; var utilsExports = utils$4.exports; /*jshint node:true*/ var inputs; var hasRequiredInputs; function requireInputs () { if (hasRequiredInputs) return inputs; hasRequiredInputs = 1; var utils = utilsExports; /* *! Input-related methods */ inputs = function(proto) { /** * Add an input to command * * Also switches "current input", that is the input that will be affected * by subsequent input-related methods. * * Note: only one stream input is supported for now. * * @method FfmpegCommand#input * @category Input * @aliases mergeAdd,addInput * * @param {String|Readable} source input file path or readable stream * @return FfmpegCommand */ proto.mergeAdd = proto.addInput = proto.input = function(source) { var isFile = false; var isStream = false; if (typeof source !== 'string') { if (!('readable' in source) || !(source.readable)) { throw new Error('Invalid input'); } var hasInputStream = this._inputs.some(function(input) { return input.isStream; }); if (hasInputStream) { throw new Error('Only one input stream is supported'); } isStream = true; source.pause(); } else { var protocol = source.match(/^([a-z]{2,}):/i); isFile = !protocol || protocol[0] === 'file'; } this._inputs.push(this._currentInput = { source: source, isFile: isFile, isStream: isStream, options: utils.args() }); return this; }; /** * Specify input format for the last specified input * * @method FfmpegCommand#inputFormat * @category Input * @aliases withInputFormat,fromFormat * * @param {String} format input format * @return FfmpegCommand */ proto.withInputFormat = proto.inputFormat = proto.fromFormat = function(format) { if (!this._currentInput) { throw new Error('No input specified'); } this._currentInput.options('-f', format); return this; }; /** * Specify input FPS for the last specified input * (only valid for raw video formats) * * @method FfmpegCommand#inputFps * @category Input * @aliases withInputFps,withInputFPS,withFpsInput,withFPSInput,inputFPS,inputFps,fpsInput * * @param {Number} fps input FPS * @return FfmpegCommand */ proto.withInputFps = proto.withInputFPS = proto.withFpsInput = proto.withFPSInput = proto.inputFPS = proto.inputFps = proto.fpsInput = proto.FPSInput = function(fps) { if (!this._currentInput) { throw new Error('No input specified'); } this._currentInput.options('-r', fps); return this; }; /** * Use native framerate for the last specified input * * @method FfmpegCommand#native * @category Input * @aliases nativeFramerate,withNativeFramerate * * @return FfmmegCommand */ proto.nativeFramerate = proto.withNativeFramerate = proto.native = function() { if (!this._currentInput) { throw new Error('No input specified'); } this._currentInput.options('-re'); return this; }; /** * Specify input seek time for the last specified input * * @method FfmpegCommand#seekInput * @category Input * @aliases setStartTime,seekTo * * @param {String|Number} seek seek time in seconds or as a '[hh:[mm:]]ss[.xxx]' string * @return FfmpegCommand */ proto.setStartTime = proto.seekInput = function(seek) { if (!this._currentInput) { throw new Error('No input specified'); } this._currentInput.options('-ss', seek); return this; }; /** * Loop over the last specified input * * @method FfmpegCommand#loop * @category Input * * @param {String|Number} [duration] loop duration in seconds or as a '[[hh:]mm:]ss[.xxx]' string * @return FfmpegCommand */ proto.loop = function(duration) { if (!this._currentInput) { throw new Error('No input specified'); } this._currentInput.options('-loop', '1'); if (typeof duration !== 'undefined') { this.duration(duration); } return this; }; }; return inputs; } /*jshint node:true*/ var audio; var hasRequiredAudio; function requireAudio () { if (hasRequiredAudio) return audio; hasRequiredAudio = 1; var utils = utilsExports; /* *! Audio-related methods */ audio = function(proto) { /** * Disable audio in the output * * @method FfmpegCommand#noAudio * @category Audio * @aliases withNoAudio * @return FfmpegCommand */ proto.withNoAudio = proto.noAudio = function() { this._currentOutput.audio.clear(); this._currentOutput.audioFilters.clear(); this._currentOutput.audio('-an'); return this; }; /** * Specify audio codec * * @method FfmpegCommand#audioCodec * @category Audio * @aliases withAudioCodec * * @param {String} codec audio codec name * @return FfmpegCommand */ proto.withAudioCodec = proto.audioCodec = function(codec) { this._currentOutput.audio('-acodec', codec); return this; }; /** * Specify audio bitrate * * @method FfmpegCommand#audioBitrate * @category Audio * @aliases withAudioBitrate * * @param {String|Number} bitrate audio bitrate in kbps (with an optional 'k' suffix) * @return FfmpegCommand */ proto.withAudioBitrate = proto.audioBitrate = function(bitrate) { this._currentOutput.audio('-b:a', ('' + bitrate).replace(/k?$/, 'k')); return this; }; /** * Specify audio channel count * * @method FfmpegCommand#audioChannels * @category Audio * @aliases withAudioChannels * * @param {Number} channels channel count * @return FfmpegCommand */ proto.withAudioChannels = proto.audioChannels = function(channels) { this._currentOutput.audio('-ac', channels); return this; }; /** * Specify audio frequency * * @method FfmpegCommand#audioFrequency * @category Audio * @aliases withAudioFrequency * * @param {Number} freq audio frequency in Hz * @return FfmpegCommand */ proto.withAudioFrequency = proto.audioFrequency = function(freq) { this._currentOutput.audio('-ar', freq); return this; }; /** * Specify audio quality * * @method FfmpegCommand#audioQuality * @category Audio * @aliases withAudioQuality * * @param {Number} quality audio quality factor * @return FfmpegCommand */ proto.withAudioQuality = proto.audioQuality = function(quality) { this._currentOutput.audio('-aq', quality); return this; }; /** * Specify custom audio filter(s) * * Can be called both with one or many filters, or a filter array. * * @example * command.audioFilters('filter1'); * * @example * command.audioFilters('filter1', 'filter2=param1=value1:param2=value2'); * * @example * command.audioFilters(['filter1', 'filter2']); * * @example * command.audioFilters([ * { * filter: 'filter1' * }, * { * filter: 'filter2', * options: 'param=value:param=value' * } * ]); * * @example * command.audioFilters( * { * filter: 'filter1', * options: ['value1', 'value2'] * }, * { * filter: 'filter2', * options: { param1: 'value1', param2: 'value2' } * } * ); * * @method FfmpegCommand#audioFilters * @aliases withAudioFilter,withAudioFilters,audioFilter * @category Audio * * @param {...String|String[]|Object[]} filters audio filter strings, string array or * filter specification array, each with the following properties: * @param {String} filters.filter filter name * @param {String|String[]|Object} [filters.options] filter option string, array, or object * @return FfmpegCommand */ proto.withAudioFilter = proto.withAudioFilters = proto.audioFilter = proto.audioFilters = function(filters) { if (arguments.length > 1) { filters = [].slice.call(arguments); } if (!Array.isArray(filters)) { filters = [filters]; } this._currentOutput.audioFilters(utils.makeFilterStrings(filters)); return this; }; }; return audio; } /*jshint node:true*/ var video; var hasRequiredVideo; function requireVideo () { if (hasRequiredVideo) return video; hasRequiredVideo = 1; var utils = utilsExports; /* *! Video-related methods */ video = function(proto) { /** * Disable video in the output * * @method FfmpegCommand#noVideo * @category Video * @aliases withNoVideo * * @return FfmpegCommand */ proto.withNoVideo = proto.noVideo = function() { this._currentOutput.video.clear(); this._currentOutput.videoFilters.clear(); this._currentOutput.video('-vn'); return this; }; /** * Specify video codec * * @method FfmpegCommand#videoCodec * @category Video * @aliases withVideoCodec * * @param {String} codec video codec name * @return FfmpegCommand */ proto.withVideoCodec = proto.videoCodec = function(codec) { this._currentOutput.video('-vcodec', codec); return this; }; /** * Specify video bitrate * * @method FfmpegCommand#videoBitrate * @category Video * @aliases withVideoBitrate * * @param {String|Number} bitrate video bitrate in kbps (with an optional 'k' suffix) * @param {Boolean} [constant=false] enforce constant bitrate * @return FfmpegCommand */ proto.withVideoBitrate = proto.videoBitrate = function(bitrate, constant) { bitrate = ('' + bitrate).replace(/k?$/, 'k'); this._currentOutput.video('-b:v', bitrate); if (constant) { this._currentOutput.video( '-maxrate', bitrate, '-minrate', bitrate, '-bufsize', '3M' ); } return this; }; /** * Specify custom video filter(s) * * Can be called both with one or many filters, or a filter array. * * @example * command.videoFilters('filter1'); * * @example * command.videoFilters('filter1', 'filter2=param1=value1:param2=value2'); * * @example * command.videoFilters(['filter1', 'filter2']); * * @example * command.videoFilters([ * { * filter: 'filter1' * }, * { * filter: 'filter2', * options: 'param=value:param=value' * } * ]); * * @example * command.videoFilters( * { * filter: 'filter1', * options: ['value1', 'value2'] * }, * { * filter: 'filter2', * options: { param1: 'value1', param2: 'value2' } * } * ); * * @method FfmpegCommand#videoFilters * @category Video * @aliases withVideoFilter,withVideoFilters,videoFilter * * @param {...String|String[]|Object[]} filters video filter strings, string array or * filter specification array, each with the following properties: * @param {String} filters.filter filter name * @param {String|String[]|Object} [filters.options] filter option string, array, or object * @return FfmpegCommand */ proto.withVideoFilter = proto.withVideoFilters = proto.videoFilter = proto.videoFilters = function(filters) { if (arguments.length > 1) { filters = [].slice.call(arguments); } if (!Array.isArray(filters)) { filters = [filters]; } this._currentOutput.videoFilters(utils.makeFilterStrings(filters)); return this; }; /** * Specify output FPS * * @method FfmpegCommand#fps * @category Video * @aliases withOutputFps,withOutputFPS,withFpsOutput,withFPSOutput,withFps,withFPS,outputFPS,outputFps,fpsOutput,FPSOutput,FPS * * @param {Number} fps output FPS * @return FfmpegCommand */ proto.withOutputFps = proto.withOutputFPS = proto.withFpsOutput = proto.withFPSOutput = proto.withFps = proto.withFPS = proto.outputFPS = proto.outputFps = proto.fpsOutput = proto.FPSOutput = proto.fps = proto.FPS = function(fps) { this._currentOutput.video('-r', fps); return this; }; /** * Only transcode a certain number of frames * * @method FfmpegCommand#frames * @category Video * @aliases takeFrames,withFrames * * @param {Number} frames frame count * @return FfmpegCommand */ proto.takeFrames = proto.withFrames = proto.frames = function(frames) { this._currentOutput.video('-vframes', frames); return this; }; }; return video; } /*jshint node:true*/ var videosize; var hasRequiredVideosize; function requireVideosize () { if (hasRequiredVideosize) return videosize; hasRequiredVideosize = 1; /* *! Size helpers */ /** * Return filters to pad video to width*height, * * @param {Number} width output width * @param {Number} height output height * @param {Number} aspect video aspect ratio (without padding) * @param {Number} color padding color * @return scale/pad filters * @private */ function getScalePadFilters(width, height, aspect, color) { /* let a be the input aspect ratio, A be the requested aspect ratio if a > A, padding is done on top and bottom if a < A, padding is done on left and right */ return [ /* In both cases, we first have to scale the input to match the requested size. When using computed width/height, we truncate them to multiples of 2 */ { filter: 'scale', options: { w: 'if(gt(a,' + aspect + '),' + width + ',trunc(' + height + '*a/2)*2)', h: 'if(lt(a,' + aspect + '),' + height + ',trunc(' + width + '/a/2)*2)' } }, /* Then we pad the scaled input to match the target size (here iw and ih refer to the padding input, i.e the scaled output) */ { filter: 'pad', options: { w: width, h: height, x: 'if(gt(a,' + aspect + '),0,(' + width + '-iw)/2)', y: 'if(lt(a,' + aspect + '),0,(' + height + '-ih)/2)', color: color } } ]; } /** * Recompute size filters * * @param {Object} output * @param {String} key newly-added parameter name ('size', 'aspect' or 'pad') * @param {String} value newly-added parameter value * @return filter string array * @private */ function createSizeFilters(output, key, value) { // Store parameters var data = output.sizeData = output.sizeData || {}; data[key] = value; if (!('size' in data)) { // No size requested, keep original size return []; } // Try to match the different size string formats var fixedSize = data.size.match(/([0-9]+)x([0-9]+)/); var fixedWidth = data.size.match(/([0-9]+)x\?/); var fixedHeight = data.size.match(/\?x([0-9]+)/); var percentRatio = data.size.match(/\b([0-9]{1,3})%/); var width, height, aspect; if (percentRatio) { var ratio = Number(percentRatio[1]) / 100; return [{ filter: 'scale', options: { w: 'trunc(iw*' + ratio + '/2)*2', h: 'trunc(ih*' + ratio + '/2)*2' } }]; } else if (fixedSize) { // Round target size to multiples of 2 width = Math.round(Number(fixedSize[1]) / 2) * 2; height = Math.round(Number(fixedSize[2]) / 2) * 2; aspect = width / height; if (data.pad) { return getScalePadFilters(width, height, aspect, data.pad); } else { // No autopad requested, rescale to target size return [{ filter: 'scale', options: { w: width, h: height }}]; } } else if (fixedWidth || fixedHeight) { if ('aspect' in data) { // Specified aspect ratio width = fixedWidth ? fixedWidth[1] : Math.round(Number(fixedHeight[1]) * data.aspect); height = fixedHeight ? fixedHeight[1] : Math.round(Number(fixedWidth[1]) / data.aspect); // Round to multiples of 2 width = Math.round(width / 2) * 2; height = Math.round(height / 2) * 2; if (data.pad) { return getScalePadFilters(width, height, data.aspect, data.pad); } else { // No autopad requested, rescale to target size return [{ filter: 'scale', options: { w: width, h: height }}]; } } else { // Keep input aspect ratio if (fixedWidth) { return [{ filter: 'scale', options: { w: Math.round(Number(fixedWidth[1]) / 2) * 2, h: 'trunc(ow/a/2)*2' } }]; } else { return [{ filter: 'scale', options: { w: 'trunc(oh*a/2)*2', h: Math.round(Number(fixedHeight[1]) / 2) * 2 } }]; } } } else { throw new Error('Invalid size specified: ' + data.size); } } /* *! Video size-related methods */ videosize = function(proto) { /** * Keep display aspect ratio * * This method is useful when converting an input with non-square pixels to an output format * that does not support non-square pixels. It rescales the input so that the display aspect * ratio is the same. * * @method FfmpegCommand#keepDAR * @category Video size * @aliases keepPixelAspect,keepDisplayAspect,keepDisplayAspectRatio * * @return FfmpegCommand */ proto.keepPixelAspect = // Only for compatibility, this is not about keeping _pixel_ aspect ratio proto.keepDisplayAspect = proto.keepDisplayAspectRatio = proto.keepDAR = function() { return this.videoFilters([ { filter: 'scale', options: { w: 'if(gt(sar,1),iw*sar,iw)', h: 'if(lt(sar,1),ih/sar,ih)' } }, { filter: 'setsar', options: '1' } ]); }; /** * Set output size * * The 'size' parameter can have one of 4 forms: * - 'X%': rescale to xx % of the original size * - 'WxH': specify width and height * - 'Wx?': specify width and compute height from input aspect ratio * - '?xH': specify height and compute width from input aspect ratio * * Note: both dimensions will be truncated to multiples of 2. * * @method FfmpegCommand#size * @category Video size * @aliases withSize,setSize * * @param {String} size size string, eg. '33%', '320x240', '320x?', '?x240' * @return FfmpegCommand */ proto.withSize = proto.setSize = proto.size = function(size) { var filters = createSizeFilters(this._currentOutput, 'size', size); this._currentOutput.sizeFilters.clear(); this._currentOutput.sizeFilters(filters); return this; }; /** * Set output aspect ratio * * @method FfmpegCommand#aspect * @category Video size * @aliases withAspect,withAspectRatio,setAspect,setAspectRatio,aspectRatio * * @param {String|Number} aspect aspect ratio (number or 'X:Y' string) * @return FfmpegCommand */ proto.withAspect = proto.withAspectRatio = proto.setAspect = proto.setAspectRatio = proto.aspect = proto.aspectRatio = function(aspect) { var a = Number(aspect); if (isNaN(a)) { var match = aspect.match(/^(\d+):(\d+)$/); if (match) { a = Number(match[1]) / Number(match[2]); } else { throw new Error('Invalid aspect ratio: ' + aspect); } } var filters = createSizeFilters(this._currentOutput, 'aspect', a); this._currentOutput.sizeFilters.clear(); this._currentOutput.sizeFilters(filters); return this; }; /** * Enable auto-padding the output * * @method FfmpegCommand#autopad * @category Video size * @aliases applyAutopadding,applyAutoPadding,applyAutopad,applyAutoPad,withAutopadding,withAutoPadding,withAutopad,withAutoPad,autoPad * * @param {Boolean} [pad=true] enable/disable auto-padding * @param {String} [color='black'] pad color */ proto.applyAutopadding = proto.applyAutoPadding = proto.applyAutopad = proto.applyAutoPad = proto.withAutopadding = proto.withAutoPadding = proto.withAutopad = proto.withAutoPad = proto.autoPad = proto.autopad = function(pad, color) { // Allow autopad(color) if (typeof pad === 'string') { color = pad; pad = true; } // Allow autopad() and autopad(undefined, color) if (typeof pad === 'undefined') { pad = true; } var filters = createSizeFilters(this._currentOutput, 'pad', pad ? color || 'black' : false); this._currentOutput.sizeFilters.clear(); this._currentOutput.sizeFilters(filters); return this; }; }; return videosize; } /*jshint node:true*/ var output; var hasRequiredOutput; function requireOutput () { if (hasRequiredOutput) return output; hasRequiredOutput = 1; var utils = utilsExports; /* *! Output-related methods */ output = function(proto) { /** * Add output * * @method FfmpegCommand#output * @category Output * @aliases addOutput * * @param {String|Writable} target target file path or writable stream * @param {Object} [pipeopts={}] pipe options (only applies to streams) * @return FfmpegCommand */ proto.addOutput = proto.output = function(target, pipeopts) { var isFile = false; if (!target && this._currentOutput) { // No target is only allowed when called from constructor throw new Error('Invalid output'); } if (target && typeof target !== 'string') { if (!('writable' in target) || !(target.writable)) { throw new Error('Invalid output'); } } else if (typeof target === 'string') { var protocol = target.match(/^([a-z]{2,}):/i); isFile = !protocol || protocol[0] === 'file'; } if (target && !('target' in this._currentOutput)) { // For backwards compatibility, set target for first output this._currentOutput.target = target; this._currentOutput.isFile = isFile; this._currentOutput.pipeopts = pipeopts || {}; } else { if (target && typeof target !== 'string') { var hasOutputStream = this._outputs.some(function(output) { return typeof output.target !== 'string'; }); if (hasOutputStream) { throw new Error('Only one output stream is supported'); } } this._outputs.push(this._currentOutput = { target: target, isFile: isFile, flags: {}, pipeopts: pipeopts || {} }); var self = this; ['audio', 'audioFilters', 'video', 'videoFilters', 'sizeFilters', 'options'].forEach(function(key) { self._currentOutput[key] = utils.args(); }); if (!target) { // Call from constructor: remove target key delete this._currentOutput.target; } } return this; }; /** * Specify output seek time * * @method FfmpegCommand#seek * @category Input * @aliases seekOutput * * @param {String|Number} seek seek time in seconds or as a '[hh:[mm:]]ss[.xxx]' string * @return FfmpegCommand */ proto.seekOutput = proto.seek = function(seek) { this._currentOutput.options('-ss', seek); return this; }; /** * Set output duration * * @method FfmpegCommand#duration * @category Output * @aliases withDuration,setDuration * * @param {String|Number} duration duration in seconds or as a '[[hh:]mm:]ss[.xxx]' string * @return FfmpegCommand */ proto.withDuration = proto.setDuration = proto.duration = function(duration) { this._currentOutput.options('-t', duration); return this; }; /** * Set output format * * @method FfmpegCommand#format * @category Output * @aliases toFormat,withOutputFormat,outputFormat * * @param {String} format output format name * @return FfmpegCommand */ proto.toFormat = proto.withOutputFormat = proto.outputFormat = proto.format = function(format) { this._currentOutput.options('-f', format); return this; }; /** * Add stream mapping to output * * @method FfmpegCommand#map * @category Output * * @param {String} spec stream specification string, with optional square brackets * @return FfmpegCommand */ proto.map = function(spec) { this._currentOutput.options('-map', spec.replace(utils.streamRegexp, '[$1]')); return this; }; /** * Run flvtool2/flvmeta on output * * @method FfmpegCommand#flvmeta * @category Output * @aliases updateFlvMetadata * * @return FfmpegCommand */ proto.updateFlvMetadata = proto.flvmeta = function() { this._currentOutput.flags.flvmeta = true; return this; }; }; return output; } /*jshint node:true*/ var custom; var hasRequiredCustom; function requireCustom () { if (hasRequiredCustom) return custom; hasRequiredCustom = 1; var utils = utilsExports; /* *! Custom options methods */ custom = function(proto) { /** * Add custom input option(s) * * When passing a single string or an array, each string containing two * words is split (eg. inputOptions('-option value') is supported) for * compatibility reasons. This is not the case when passing more than * one argument. * * @example * command.inputOptions('option1'); * * @example * command.inputOptions('option1', 'option2'); * * @example * command.inputOptions(['option1', 'option2']); * * @method FfmpegCommand#inputOptions * @category Custom options * @aliases addInputOption,addInputOptions,withInputOption,withInputOptions,inputOption * * @param {...String} options option string(s) or string array * @return FfmpegCommand */ proto.addInputOption = proto.addInputOptions = proto.withInputOption = proto.withInputOptions = proto.inputOption = proto.inputOptions = function(options) { if (!this._currentInput) { throw new Error('No input specified'); } var doSplit = true; if (arguments.length > 1) { options = [].slice.call(arguments); doSplit = false; } if (!Array.isArray(options)) { options = [options]; } this._currentInput.options(options.reduce(function(options, option) { var split = String(option).split(' '); if (doSplit && split.length === 2) { options.push(split[0], split[1]); } else { options.push(option); } return options; }, [])); return this; }; /** * Add custom output option(s) * * @example * command.outputOptions('option1'); * * @example * command.outputOptions('option1', 'option2'); * * @example * command.outputOptions(['option1', 'option2']); * * @method FfmpegCommand#outputOptions * @category Custom options * @aliases addOutputOption,addOutputOptions,addOption,addOptions,withOutputOption,withOutputOptions,withOption,withOptions,outputOption * * @param {...String} options option string(s) or string array * @return FfmpegCommand */ proto.addOutputOption = proto.addOutputOptions = proto.addOption = proto.addOptions = proto.withOutputOption = proto.withOutputOptions = proto.withOption = proto.withOptions = proto.outputOption = proto.outputOptions = function(options) { var doSplit = true; if (arguments.length > 1) { options = [].slice.call(arguments); doSplit = false; } if (!Array.isArray(options)) { options = [options]; } this._currentOutput.options(options.reduce(function(options, option) { var split = String(option).split(' '); if (doSplit && split.length === 2) { options.push(split[0], split[1]); } else { options.push(option); } return options; }, [])); return this; }; /** * Specify a complex filtergraph * * Calling this method will override any previously set filtergraph, but you can set * as many filters as needed in one call. * * @example Overlay an image over a video (using a filtergraph string) * ffmpeg() * .input('video.avi') * .input('image.png') * .complexFilter('[0:v][1:v]overlay[out]', ['out']); * * @example Overlay an image over a video (using a filter array) * ffmpeg() * .input('video.avi') * .input('image.png') * .complexFilter([{ * filter: 'overlay', * inputs: ['0:v', '1:v'], * outputs: ['out'] * }], ['out']); * * @example Split video into RGB channels and output a 3x1 video with channels side to side * ffmpeg() * .input('video.avi') * .complexFilter([ * // Duplicate video stream 3 times into streams a, b, and c * { filter: 'split', options: '3', outputs: ['a', 'b', 'c'] }, * * // Create stream 'red' by cancelling green and blue channels from stream 'a' * { filter: 'lutrgb', options: { g: 0, b: 0 }, inputs: 'a', outputs: 'red' }, * * // Create stream 'green' by cancelling red and blue channels from stream 'b' * { filter: 'lutrgb', options: { r: 0, b: 0 }, inputs: 'b', outputs: 'green' }, * * // Create stream 'blue' by cancelling red and green channels from stream 'c' * { filter: 'lutrgb', options: { r: 0, g: 0 }, inputs: 'c', outputs: 'blue' }, * * // Pad stream 'red' to 3x width, keeping the video on the left, and name output 'padded' * { filter: 'pad', options: { w: 'iw*3', h: 'ih' }, inputs: 'red', outputs: 'padded' }, * * // Overlay 'green' onto 'padded', moving it to the center, and name output 'redgreen' * { filter: 'overlay', options: { x: 'w', y: 0 }, inputs: ['padded', 'green'], outputs: 'redgreen'}, * * // Overlay 'blue' onto 'redgreen', moving it to the right * { filter: 'overlay', options: { x: '2*w', y: 0 }, inputs: ['redgreen', 'blue']}, * ]); * * @method FfmpegCommand#complexFilter * @category Custom options * @aliases filterGraph * * @param {String|Array} spec filtergraph string or array of filter specification * objects, each having the following properties: * @param {String} spec.filter filter name * @param {String|Array} [spec.inputs] (array of) input stream specifier(s) for the filter, * defaults to ffmpeg automatically choosing the first unused matching streams * @param {String|Array} [spec.outputs] (array of) output stream specifier(s) for the filter, * defaults to ffmpeg automatically assigning the output to the output file * @param {Object|String|Array} [spec.options] filter options, can be omitted to not set any options * @param {Array} [map] (array of) stream specifier(s) from the graph to include in * ffmpeg output, defaults to ffmpeg automatically choosing the first matching streams. * @return FfmpegCommand */ proto.filterGraph = proto.complexFilter = function(spec, map) { this._complexFilters.clear(); if (!Array.isArray(spec)) { spec = [spec]; } this._complexFilters('-filter_complex', utils.makeFilterStrings(spec).join(';')); if (Array.isArray(map)) { var self = this; map.forEach(function(streamSpec) { self._complexFilters('-map', streamSpec.replace(utils.streamRegexp, '[$1]')); }); } else if (typeof map === 'string') { this._complexFilters('-map', map.replace(utils.streamRegexp, '[$1]')); } return this; }; }; return custom; } function commonjsRequire(path) { throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); } /*jshint node:true*/ var misc; var hasRequiredMisc; function requireMisc () { if (hasRequiredMisc) return misc; hasRequiredMisc = 1; var path = require$$0$3; /* *! Miscellaneous methods */ misc = function(proto) { /** * Use preset * * @method FfmpegCommand#preset * @category Miscellaneous * @aliases usingPreset * * @param {String|Function} preset preset name or preset function */ proto.usingPreset = proto.preset = function(preset) { if (typeof preset === 'function') { preset(this); } else { try { var modulePath = path.join(this.options.presets, preset); var module = commonjsRequire(modulePath); if (typeof module.load === 'function') { module.load(this); } else { throw new Error('preset ' + modulePath + ' has no load() function'); } } catch (err) { throw new Error('preset ' + modulePath + ' could not be loaded: ' + err.message); } } return this; }; }; return misc; } var async = {exports: {}}; /*global setImmediate: false, setTimeout: false, console: false */ var hasRequiredAsync; function requireAsync () { if (hasRequiredAsync) return async.exports; hasRequiredAsync = 1; (function (module) { (function () { var async = {}; // global on the server, window in the browser var root, previous_async; root = this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { var called = false; return function() { if (called) throw new Error("Callback was already called."); called = true; fn.apply(root, arguments); } } //// cross-browser compatiblity functions //// var _each = function (arr, iterator) { if (arr.forEach) { return arr.forEach(iterator); } for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; var _map = function (arr, iterator) { if (arr.map) { return arr.map(iterator); } var results = []; _each(arr, function (x, i, a) { results.push(iterator(x, i, a)); }); return results; }; var _reduce = function (arr, iterator, memo) { if (arr.reduce) { return arr.reduce(iterator, memo); } _each(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; }; var _keys = function (obj) { if (Object.keys) { return Object.keys(obj); } var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// if (typeof process === 'undefined' || !(process.nextTick)) { if (typeof setImmediate === 'function') { async.nextTick = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; async.setImmediate = async.nextTick; } else { async.nextTick = function (fn) { setTimeout(fn, 0); }; async.setImmediate = async.nextTick; } } else { async.nextTick = process.nextTick; if (typeof setImmediate !== 'undefined') { async.setImmediate = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; } else { async.setImmediate = async.nextTick; } } async.each = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, only_once(function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } } })); }); }; async.forEach = async.each; async.eachSeries = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; var iterate = function () { iterator(arr[completed], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } else { iterate(); } } }); }; iterate(); }; async.forEachSeries = async.eachSeries; async.eachLimit = function (arr, limit, iterator, callback) { var fn = _eachLimit(limit); fn.apply(null, [arr, iterator, callback]); }; async.forEachLimit = async.eachLimit; var _eachLimit = function (limit) { return function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length || limit <= 0) { return callback(); } var completed = 0; var started = 0; var running = 0; (function replenish () { if (completed >= arr.length) { return callback(); } while (running < limit && started < arr.length) { started += 1; running += 1; iterator(arr[started - 1], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; running -= 1; if (completed >= arr.length) { callback(); } else { replenish(); } } }); } })(); }; }; var doParallel = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.each].concat(args)); }; }; var doParallelLimit = function(limit, fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [_eachLimit(limit)].concat(args)); }; }; var doSeries = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.eachSeries].concat(args)); }; }; var _asyncMap = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (err, v) { results[x.index] = v; callback(err); }); }, function (err) { callback(err, results); }); }; async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = function (arr, limit, iterator, callback) { return _mapLimit(limit)(arr, iterator, callback); }; var _mapLimit = function(limit) { return doParallelLimit(limit, _asyncMap); }; // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.reduce = function (arr, memo, iterator, callback) { async.eachSeries(arr, function (x, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; // inject alias async.inject = async.reduce; // foldl alias async.foldl = async.reduce; async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, function (x) { return x; }).reverse(); async.reduce(reversed, memo, iterator, callback); }; // foldr alias async.foldr = async.reduceRight; var _filter = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.filter = doParallel(_filter); async.filterSeries = doSeries(_filter); // select alias async.select = async.filter; async.selectSeries = async.filterSeries; var _reject = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (!v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.reject = doParallel(_reject); async.rejectSeries = doSeries(_reject); var _detect = function (eachfn, arr, iterator, main_callback) { eachfn(arr, function (x, callback) { iterator(x, function (result) { if (result) { main_callback(x); main_callback = function () {}; } else { callback(); } }); }, function (err) { main_callback(); }); }; async.detect = doParallel(_detect); async.detectSeries = doSeries(_detect); async.some = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (v) { main_callback(true); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(false); }); }; // any alias async.any = async.some; async.every = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (!v) { main_callback(false); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(true); }); }; // all alias async.all = async.every; async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { var fn = function (left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }; callback(null, _map(results.sort(fn), function (x) { return x.value; })); } }); }; async.auto = function (tasks, callback) { callback = callback || function () {}; var keys = _keys(tasks); if (!keys.length) { return callback(null); } var results = {}; var listeners = []; var addListener = function (fn) { listeners.unshift(fn); }; var removeListener = function (fn) { for (var i = 0; i < listeners.length; i += 1) { if (listeners[i] === fn) { listeners.splice(i, 1); return; } } }; var taskComplete = function () { _each(listeners.slice(0), function (fn) { fn(); }); }; addListener(function () { if (_keys(results).length === keys.length) { callback(null, results); callback = function () {}; } }); _each(keys, function (k) { var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; var taskCallback = function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _each(_keys(results), function(rkey) { safeResults[rkey] = results[rkey]; }); safeResults[k] = args; callback(err, safeResults); // stop subsequent errors hitting callback multiple times callback = function () {}; } else { results[k] = args; async.setImmediate(taskComplete); } }; var requires = task.slice(0, Math.abs(task.length - 1)) || []; var ready = function () { return _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); }; if (ready()) { task[task.length - 1](taskCallback, results); } else { var listener = function () { if (ready()) { removeListener(listener); task[task.length - 1](taskCallback, results); } }; addListener(listener); } }); }; async.waterfall = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor !== Array) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } var wrapIterator = function (iterator) { return function (err) { if (err) { callback.apply(null, arguments); callback = function () {}; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } async.setImmediate(function () { iterator.apply(null, args); }); } }; }; wrapIterator(async.iterator(tasks))(); }; var _parallel = function(eachfn, tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { eachfn.map(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; eachfn.each(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.parallel = function (tasks, callback) { _parallel({ map: async.map, each: async.each }, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); }; async.series = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { async.mapSeries(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; async.eachSeries(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.iterator = function (tasks) { var makeCallback = function (index) { var fn = function () { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); }; fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; }; return makeCallback(0); }; async.apply = function (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply( null, args.concat(Array.prototype.slice.call(arguments)) ); }; }; var _concat = function (eachfn, arr, fn, callback) { var r = []; eachfn(arr, function (x, cb) { fn(x, function (err, y) { r = r.concat(y || []); cb(err); }); }, function (err) { callback(err, r); }); }; async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { if (test()) { iterator(function (err) { if (err) { return callback(err); } async.whilst(test, iterator, callback); }); } else { callback(); } }; async.doWhilst = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (test()) { async.doWhilst(iterator, test, callback); } else { callback(); } }); }; async.until = function (test, iterator, callback) { if (!test()) { iterator(function (err) { if (err) { return callback(err); } async.until(test, iterator, callback); }); } else { callback(); } }; async.doUntil = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (!test()) { async.doUntil(iterator, test, callback); } else { callback(); } }); }; async.queue = function (worker, concurrency) { if (concurrency === undefined) { concurrency = 1; } function _insert(q, data, pos, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { var item = { data: task, callback: typeof callback === 'function' ? callback : null }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.saturated && q.tasks.length === concurrency) { q.saturated(); } async.setImmediate(q.process); }); } var workers = 0; var q = { tasks: [], concurrency: concurrency, saturated: null, empty: null, drain: null, push: function (data, callback) { _insert(q, data, false, callback); }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (workers < q.concurrency && q.tasks.length) { var task = q.tasks.shift(); if (q.empty && q.tasks.length === 0) { q.empty(); } workers += 1; var next = function () { workers -= 1; if (task.callback) { task.callback.apply(task, arguments); } if (q.drain && q.tasks.length + workers === 0) { q.drain(); } q.process(); }; var cb = only_once(next); worker(task.data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; } }; return q; }; async.cargo = function (worker, payload) { var working = false, tasks = []; var cargo = { tasks: tasks, payload: payload, saturated: null, empty: null, drain: null, push: function (data, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { tasks.push({ data: task, callback: typeof callback === 'function' ? callback : null }); if (cargo.saturated && tasks.length === payload) { cargo.saturated(); } }); async.setImmediate(cargo.process); }, process: function process() { if (working) return; if (tasks.length === 0) { if(cargo.drain) cargo.drain(); return; } var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0); var ds = _map(ts, function (task) { return task.data; }); if(cargo.empty) cargo.empty(); working = true; worker(ds, function () { working = false; var args = arguments; _each(ts, function (data) { if (data.callback) { data.callback.apply(null, args); } }); process(); }); }, length: function () { return tasks.length; }, running: function () { return working; } }; return cargo; }; var _console_fn = function (name) { return function (fn) { var args = Array.prototype.slice.call(arguments, 1); fn.apply(null, args.concat([function (err) { var args = Array.prototype.slice.call(arguments, 1); if (typeof console !== 'undefined') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _each(args, function (x) { console[name](x); }); } } }])); }; }; async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || function (x) { return x; }; var memoized = function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { callback.apply(null, memo[key]); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([function () { memo[key] = arguments; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, arguments); } }])); } }; memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; async.times = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.map(counter, iterator, callback); }; async.timesSeries = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.mapSeries(counter, iterator, callback); }; async.compose = function (/* functions... */) { var fns = Array.prototype.reverse.call(arguments); return function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([function () { var err = arguments[0]; var nextargs = Array.prototype.slice.call(arguments, 1); cb(err, nextargs); }])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }; }; var _applyEach = function (eachfn, fns /*args...*/) { var go = function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); return eachfn(fns, function (fn, cb) { fn.apply(that, args.concat([cb])); }, callback); }; if (arguments.length > 2) { var args = Array.prototype.slice.call(arguments, 2); return go.apply(this, args); } else { return go; } }; async.applyEach = doParallel(_applyEach); async.applyEachSeries = doSeries(_applyEach); async.forever = function (fn, callback) { function next(err) { if (err) { if (callback) { return callback(err); } throw err; } fn(next); } next(); }; // AMD / RequireJS if (module.exports) { module.exports = async; } // included directly via