import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; /******/ var __webpack_modules__ = ({ /***/ 7855: /***/ ((__unused_webpack_module, exports) => { /** * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes. * * Works with anything that has a `length` property and index access properties, * including NodeList. * * @param {T[] | { length: number; [number]: T }} list * @param {function (item: T, index: number, list:T[]):boolean} predicate * @param {Partial>?} ac * Allows injecting a custom implementation in tests (`Array.prototype` by default). * @returns {T | undefined} * @template {unknown} T * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find */ function find(list, predicate, ac) { if (ac === undefined) { ac = Array.prototype; } if (list && typeof ac.find === 'function') { return ac.find.call(list, predicate); } for (var i = 0; i < list.length; i++) { if (hasOwn(list, i)) { var item = list[i]; if (predicate.call(undefined, item, i, list)) { return item; } } } } /** * "Shallow freezes" an object to render it immutable. * Uses `Object.freeze` if available, * otherwise the immutability is only in the type. * * Is used to create "enum like" objects. * * If `Object.getOwnPropertyDescriptors` is available, * a new object with all properties of object but without any prototype is created and returned * after freezing it. * * @param {T} object * The object to freeze. * @param {Pick} [oc=Object] * `Object` by default, * allows to inject custom object constructor for tests. * @returns {Readonly} * @template {Object} T * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze * @prettierignore */ function freeze(object, oc) { if (oc === undefined) { oc = Object; } if (oc && typeof oc.getOwnPropertyDescriptors === 'function') { object = oc.create(null, oc.getOwnPropertyDescriptors(object)); } return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object; } /** * Implementation for `Object.hasOwn` but ES5 compatible. * * @param {any} object * @param {string | number} key * @returns {boolean} */ function hasOwn(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } /** * Since xmldom can not rely on `Object.assign`, * it uses/provides a simplified version that is sufficient for its needs. * * @param {Object} target * @param {Object | null | undefined} source * @returns {Object} * The target with the merged/overridden properties. * @throws {TypeError} * If target is not an object. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign */ function assign(target, source) { if (target === null || typeof target !== 'object') { throw new TypeError('target is not an object'); } for (var key in source) { if (hasOwn(source, key)) { target[key] = source[key]; } } return target; } /** * A number of attributes are boolean attributes. * The presence of a boolean attribute on an element represents the `true` value, * and the absence of the attribute represents the `false` value. * * If the attribute is present, its value must either be the empty string, or a value that is * an ASCII case-insensitive match for the attribute's canonical name, * with no leading or trailing whitespace. * * Note: The values `"true"` and `"false"` are not allowed on boolean attributes. * To represent a `false` value, the attribute has to be omitted altogether. * * @see https://html.spec.whatwg.org/#boolean-attributes * @see https://html.spec.whatwg.org/#attributes-3 */ var HTML_BOOLEAN_ATTRIBUTES = freeze({ allowfullscreen: true, async: true, autofocus: true, autoplay: true, checked: true, controls: true, default: true, defer: true, disabled: true, formnovalidate: true, hidden: true, ismap: true, itemscope: true, loop: true, multiple: true, muted: true, nomodule: true, novalidate: true, open: true, playsinline: true, readonly: true, required: true, reversed: true, selected: true, }); /** * Check if `name` is matching one of the HTML boolean attribute names. * This method doesn't check if such attributes are allowed in the context of the current * document/parsing. * * @param {string} name * @returns {boolean} * @see {@link HTML_BOOLEAN_ATTRIBUTES} * @see https://html.spec.whatwg.org/#boolean-attributes * @see https://html.spec.whatwg.org/#attributes-3 */ function isHTMLBooleanAttribute(name) { return hasOwn(HTML_BOOLEAN_ATTRIBUTES, name.toLowerCase()); } /** * Void elements only have a start tag; end tags must not be specified for void elements. * These elements should be written as self-closing like this: ``. * This should not be confused with optional tags that HTML allows to omit the end tag for * (like `li`, `tr` and others), which can have content after them, * so they can not be written as self-closing. * xmldom does not have any logic for optional end tags cases, * and will report them as a warning. * Content that would go into the unopened element, * will instead be added as a sibling text node. * * @type {Readonly<{ * area: boolean; * col: boolean; * img: boolean; * wbr: boolean; * link: boolean; * hr: boolean; * source: boolean; * br: boolean; * input: boolean; * param: boolean; * meta: boolean; * embed: boolean; * track: boolean; * base: boolean; * }>} * @see https://html.spec.whatwg.org/#void-elements * @see https://html.spec.whatwg.org/#optional-tags */ var HTML_VOID_ELEMENTS = freeze({ area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, link: true, meta: true, param: true, source: true, track: true, wbr: true, }); /** * Check if `tagName` is matching one of the HTML void element names. * This method doesn't check if such tags are allowed in the context of the current * document/parsing. * * @param {string} tagName * @returns {boolean} * @see {@link HTML_VOID_ELEMENTS} * @see https://html.spec.whatwg.org/#void-elements */ function isHTMLVoidElement(tagName) { return hasOwn(HTML_VOID_ELEMENTS, tagName.toLowerCase()); } /** * Tag names that are raw text elements according to HTML spec. * The value denotes whether they are escapable or not. * * @see {@link isHTMLEscapableRawTextElement} * @see {@link isHTMLRawTextElement} * @see https://html.spec.whatwg.org/#raw-text-elements * @see https://html.spec.whatwg.org/#escapable-raw-text-elements */ var HTML_RAW_TEXT_ELEMENTS = freeze({ script: false, style: false, textarea: true, title: true, }); /** * Check if `tagName` is matching one of the HTML raw text element names. * This method doesn't check if such tags are allowed in the context of the current * document/parsing. * * @param {string} tagName * @returns {boolean} * @see {@link isHTMLEscapableRawTextElement} * @see {@link HTML_RAW_TEXT_ELEMENTS} * @see https://html.spec.whatwg.org/#raw-text-elements * @see https://html.spec.whatwg.org/#escapable-raw-text-elements */ function isHTMLRawTextElement(tagName) { var key = tagName.toLowerCase(); return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && !HTML_RAW_TEXT_ELEMENTS[key]; } /** * Check if `tagName` is matching one of the HTML escapable raw text element names. * This method doesn't check if such tags are allowed in the context of the current * document/parsing. * * @param {string} tagName * @returns {boolean} * @see {@link isHTMLRawTextElement} * @see {@link HTML_RAW_TEXT_ELEMENTS} * @see https://html.spec.whatwg.org/#raw-text-elements * @see https://html.spec.whatwg.org/#escapable-raw-text-elements */ function isHTMLEscapableRawTextElement(tagName) { var key = tagName.toLowerCase(); return hasOwn(HTML_RAW_TEXT_ELEMENTS, key) && HTML_RAW_TEXT_ELEMENTS[key]; } /** * Only returns true if `value` matches MIME_TYPE.HTML, which indicates an HTML document. * * @param {string} mimeType * @returns {mimeType is 'text/html'} * @see https://www.iana.org/assignments/media-types/text/html * @see https://en.wikipedia.org/wiki/HTML * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */ function isHTMLMimeType(mimeType) { return mimeType === MIME_TYPE.HTML; } /** * For both the `text/html` and the `application/xhtml+xml` namespace the spec defines that the * HTML namespace is provided as the default. * * @param {string} mimeType * @returns {boolean} * @see https://dom.spec.whatwg.org/#dom-document-createelement * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument */ function hasDefaultHTMLNamespace(mimeType) { return isHTMLMimeType(mimeType) || mimeType === MIME_TYPE.XML_XHTML_APPLICATION; } /** * All mime types that are allowed as input to `DOMParser.parseFromString` * * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 * MDN * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype * WHATWG HTML Spec * @see {@link DOMParser.prototype.parseFromString} */ var MIME_TYPE = freeze({ /** * `text/html`, the only mime type that triggers treating an XML document as HTML. * * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration * @see https://en.wikipedia.org/wiki/HTML Wikipedia * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring * WHATWG HTML Spec */ HTML: 'text/html', /** * `application/xml`, the standard mime type for XML documents. * * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType * registration * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia */ XML_APPLICATION: 'application/xml', /** * `text/xml`, an alias for `application/xml`. * * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303 * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia */ XML_TEXT: 'text/xml', /** * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, * but is parsed as an XML document. * * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType * registration * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec * @see https://en.wikipedia.org/wiki/XHTML Wikipedia */ XML_XHTML_APPLICATION: 'application/xhtml+xml', /** * `image/svg+xml`, * * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia */ XML_SVG_IMAGE: 'image/svg+xml', }); /** * @typedef {'application/xhtml+xml' | 'application/xml' | 'image/svg+xml' | 'text/html' | 'text/xml'} * MimeType */ /** * @type {MimeType[]} * @private * Basically `Object.values`, which is not available in ES5. */ var _MIME_TYPES = Object.keys(MIME_TYPE).map(function (key) { return MIME_TYPE[key]; }); /** * Only returns true if `mimeType` is one of the allowed values for * `DOMParser.parseFromString`. * * @param {string} mimeType * @returns {mimeType is 'application/xhtml+xml' | 'application/xml' | 'image/svg+xml' | 'text/html' | 'text/xml'} * */ function isValidMimeType(mimeType) { return _MIME_TYPES.indexOf(mimeType) > -1; } /** * Namespaces that are used in this code base. * * @see http://www.w3.org/TR/REC-xml-names */ var NAMESPACE = freeze({ /** * The XHTML namespace. * * @see http://www.w3.org/1999/xhtml */ HTML: 'http://www.w3.org/1999/xhtml', /** * The SVG namespace. * * @see http://www.w3.org/2000/svg */ SVG: 'http://www.w3.org/2000/svg', /** * The `xml:` namespace. * * @see http://www.w3.org/XML/1998/namespace */ XML: 'http://www.w3.org/XML/1998/namespace', /** * The `xmlns:` namespace. * * @see https://www.w3.org/2000/xmlns/ */ XMLNS: 'http://www.w3.org/2000/xmlns/', }); exports.assign = assign; exports.find = find; exports.freeze = freeze; exports.HTML_BOOLEAN_ATTRIBUTES = HTML_BOOLEAN_ATTRIBUTES; exports.HTML_RAW_TEXT_ELEMENTS = HTML_RAW_TEXT_ELEMENTS; exports.HTML_VOID_ELEMENTS = HTML_VOID_ELEMENTS; exports.hasDefaultHTMLNamespace = hasDefaultHTMLNamespace; exports.hasOwn = hasOwn; exports.isHTMLBooleanAttribute = isHTMLBooleanAttribute; exports.isHTMLRawTextElement = isHTMLRawTextElement; exports.isHTMLEscapableRawTextElement = isHTMLEscapableRawTextElement; exports.isHTMLMimeType = isHTMLMimeType; exports.isHTMLVoidElement = isHTMLVoidElement; exports.isValidMimeType = isValidMimeType; exports.MIME_TYPE = MIME_TYPE; exports.NAMESPACE = NAMESPACE; /***/ }), /***/ 4847: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var conventions = __nccwpck_require__(7855); var dom = __nccwpck_require__(7311); var errors = __nccwpck_require__(7368); var entities = __nccwpck_require__(4124); var sax = __nccwpck_require__(1995); var DOMImplementation = dom.DOMImplementation; var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace; var isHTMLMimeType = conventions.isHTMLMimeType; var isValidMimeType = conventions.isValidMimeType; var MIME_TYPE = conventions.MIME_TYPE; var NAMESPACE = conventions.NAMESPACE; var ParseError = errors.ParseError; var XMLReader = sax.XMLReader; /** * Normalizes line ending according to , * including some Unicode "newline" characters: * * > XML parsed entities are often stored in computer files which, * > for editing convenience, are organized into lines. * > These lines are typically separated by some combination * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA). * > * > To simplify the tasks of applications, the XML processor must behave * > as if it normalized all line breaks in external parsed entities (including the document entity) * > on input, before parsing, by translating the following to a single #xA character: * > * > 1. the two-character sequence #xD #xA, * > 2. the two-character sequence #xD #x85, * > 3. the single character #x85, * > 4. the single character #x2028, * > 5. the single character #x2029, * > 6. any #xD character that is not immediately followed by #xA or #x85. * * @param {string} input * @returns {string} * @prettierignore */ function normalizeLineEndings(input) { return input.replace(/\r[\n\u0085]/g, '\n').replace(/[\r\u0085\u2028\u2029]/g, '\n'); } /** * @typedef Locator * @property {number} [columnNumber] * @property {number} [lineNumber] */ /** * @typedef DOMParserOptions * @property {typeof assign} [assign] * The method to use instead of `conventions.assign`, which is used to copy values from * `options` before they are used for parsing. * @property {typeof DOMHandler} [domHandler] * For internal testing: The class for creating an instance for handling events from the SAX * parser. * *****Warning: By configuring a faulty implementation, the specified behavior can completely * be broken.*****. * @property {Function} [errorHandler] * DEPRECATED! use `onError` instead. * @property {function(level:ErrorLevel, message:string, context: DOMHandler):void} * [onError] * A function invoked for every error that occurs during parsing. * * If it is not provided, all errors are reported to `console.error` * and only `fatalError`s are thrown as a `ParseError`, * which prevents any further processing. * If the provided method throws, a `ParserError` is thrown, * which prevents any further processing. * * Be aware that many `warning`s are considered an error that prevents further processing in * most implementations. * @property {boolean} [locator=true] * Configures if the nodes created during parsing will have a `lineNumber` and a `columnNumber` * attribute describing their location in the XML string. * Default is true. * @property {(string) => string} [normalizeLineEndings] * used to replace line endings before parsing, defaults to exported `normalizeLineEndings`, * which normalizes line endings according to , * including some Unicode "newline" characters. * @property {Object} [xmlns] * The XML namespaces that should be assumed when parsing. * The default namespace can be provided by the key that is the empty string. * When the `mimeType` for HTML, XHTML or SVG are passed to `parseFromString`, * the default namespace that will be used, * will be overridden according to the specification. * @see {@link normalizeLineEndings} */ /** * The DOMParser interface provides the ability to parse XML or HTML source code from a string * into a DOM `Document`. * * ***xmldom is different from the spec in that it allows an `options` parameter, * to control the behavior***. * * @class * @param {DOMParserOptions} [options] * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization */ function DOMParser(options) { options = options || {}; if (options.locator === undefined) { options.locator = true; } /** * The method to use instead of `conventions.assign`, which is used to copy values from * `options` * before they are used for parsing. * * @type {conventions.assign} * @private * @see {@link conventions.assign} * @readonly */ this.assign = options.assign || conventions.assign; /** * For internal testing: The class for creating an instance for handling events from the SAX * parser. * *****Warning: By configuring a faulty implementation, the specified behavior can completely * be broken*****. * * @type {typeof DOMHandler} * @private * @readonly */ this.domHandler = options.domHandler || DOMHandler; /** * A function that is invoked for every error that occurs during parsing. * * If it is not provided, all errors are reported to `console.error` * and only `fatalError`s are thrown as a `ParseError`, * which prevents any further processing. * If the provided method throws, a `ParserError` is thrown, * which prevents any further processing. * * Be aware that many `warning`s are considered an error that prevents further processing in * most implementations. * * @type {function(level:ErrorLevel, message:string, context: DOMHandler):void} * @see {@link onErrorStopParsing} * @see {@link onWarningStopParsing} */ this.onError = options.onError || options.errorHandler; if (options.errorHandler && typeof options.errorHandler !== 'function') { throw new TypeError('errorHandler object is no longer supported, switch to onError!'); } else if (options.errorHandler) { options.errorHandler('warning', 'The `errorHandler` option has been deprecated, use `onError` instead!', this); } /** * used to replace line endings before parsing, defaults to `normalizeLineEndings` * * @type {(string) => string} * @readonly */ this.normalizeLineEndings = options.normalizeLineEndings || normalizeLineEndings; /** * Configures if the nodes created during parsing will have a `lineNumber` and a * `columnNumber` * attribute describing their location in the XML string. * Default is true. * * @type {boolean} * @readonly */ this.locator = !!options.locator; /** * The default namespace can be provided by the key that is the empty string. * When the `mimeType` for HTML, XHTML or SVG are passed to `parseFromString`, * the default namespace that will be used, * will be overridden according to the specification. * * @type {Readonly} * @readonly */ this.xmlns = this.assign(Object.create(null), options.xmlns); } /** * Parses `source` using the options in the way configured by the `DOMParserOptions` of `this` * `DOMParser`. If `mimeType` is `text/html` an HTML `Document` is created, * otherwise an XML `Document` is created. * * __It behaves different from the description in the living standard__: * - Uses the `options` passed to the `DOMParser` constructor to modify the behavior. * - Any unexpected input is reported to `onError` with either a `warning`, * `error` or `fatalError` level. * - Any `fatalError` throws a `ParseError` which prevents further processing. * - Any error thrown by `onError` is converted to a `ParseError` which prevents further * processing - If no `Document` was created during parsing it is reported as a `fatalError`. * *****Warning: By configuring a faulty DOMHandler implementation, * the specified behavior can completely be broken*****. * * @param {string} source * The XML mime type only allows string input! * @param {string} [mimeType='application/xml'] * the mimeType or contentType of the document to be created determines the `type` of document * created (XML or HTML) * @returns {Document} * The `Document` node. * @throws {ParseError} * for any `fatalError` or anything that is thrown by `onError` * @throws {TypeError} * for any invalid `mimeType` * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString * @see https://html.spec.whatwg.org/#dom-domparser-parsefromstring-dev */ DOMParser.prototype.parseFromString = function (source, mimeType) { if (!isValidMimeType(mimeType)) { throw new TypeError('DOMParser.parseFromString: the provided mimeType "' + mimeType + '" is not valid.'); } var defaultNSMap = this.assign(Object.create(null), this.xmlns); var entityMap = entities.XML_ENTITIES; var defaultNamespace = defaultNSMap[''] || null; if (hasDefaultHTMLNamespace(mimeType)) { entityMap = entities.HTML_ENTITIES; defaultNamespace = NAMESPACE.HTML; } else if (mimeType === MIME_TYPE.XML_SVG_IMAGE) { defaultNamespace = NAMESPACE.SVG; } defaultNSMap[''] = defaultNamespace; defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML; var domBuilder = new this.domHandler({ mimeType: mimeType, defaultNamespace: defaultNamespace, onError: this.onError, }); var locator = this.locator ? {} : undefined; if (this.locator) { domBuilder.setDocumentLocator(locator); } var sax = new XMLReader(); sax.errorHandler = domBuilder; sax.domBuilder = domBuilder; var isXml = !conventions.isHTMLMimeType(mimeType); if (isXml && typeof source !== 'string') { sax.errorHandler.fatalError('source is not a string'); } sax.parse(this.normalizeLineEndings(String(source)), defaultNSMap, entityMap); if (!domBuilder.doc.documentElement) { sax.errorHandler.fatalError('missing root element'); } return domBuilder.doc; }; /** * @typedef DOMHandlerOptions * @property {string} [mimeType=MIME_TYPE.XML_APPLICATION] * @property {string | null} [defaultNamespace=null] */ /** * The class that is used to handle events from the SAX parser to create the related DOM * elements. * * Some methods are only implemented as an empty function, * since they are (at least currently) not relevant for xmldom. * * @class * @param {DOMHandlerOptions} [options] * @see http://www.saxproject.org/apidoc/org/xml/sax/ext/DefaultHandler2.html */ function DOMHandler(options) { var opt = options || {}; /** * The mime type is used to determine if the DOM handler will create an XML or HTML document. * Only if it is set to `text/html` it will create an HTML document. * It defaults to MIME_TYPE.XML_APPLICATION. * * @type {string} * @see {@link MIME_TYPE} * @readonly */ this.mimeType = opt.mimeType || MIME_TYPE.XML_APPLICATION; /** * The namespace to use to create an XML document. * For the following reasons this is required: * - The SAX API for `startDocument` doesn't offer any way to pass a namespace, * since at that point there is no way for the parser to know what the default namespace from * the document will be. * - When creating using `DOMImplementation.createDocument` it is required to pass a * namespace, * to determine the correct `Document.contentType`, which should match `this.mimeType`. * - When parsing an XML document with the `application/xhtml+xml` mimeType, * the HTML namespace needs to be the default namespace. * * @type {string | null} * @private * @readonly */ this.defaultNamespace = opt.defaultNamespace || null; /** * @type {boolean} * @private */ this.cdata = false; /** * The last `Element` that was created by `startElement`. * `endElement` sets it to the `currentElement.parentNode`. * * Note: The sax parser currently sets it to white space text nodes between tags. * * @type {Element | Node | undefined} * @private */ this.currentElement = undefined; /** * The Document that is created as part of `startDocument`, * and returned by `DOMParser.parseFromString`. * * @type {Document | undefined} * @readonly */ this.doc = undefined; /** * The locator is stored as part of setDocumentLocator. * It is controlled and mutated by the SAX parser to store the current parsing position. * It is used by DOMHandler to set `columnNumber` and `lineNumber` * on the DOM nodes. * * @type {Readonly | undefined} * @private * @readonly (the * sax parser currently sometimes set's it) */ this.locator = undefined; /** * @type {function (level:ErrorLevel ,message:string, context:DOMHandler):void} * @readonly */ this.onError = opt.onError; } function position(locator, node) { node.lineNumber = locator.lineNumber; node.columnNumber = locator.columnNumber; } DOMHandler.prototype = { /** * Either creates an XML or an HTML document and stores it under `this.doc`. * If it is an XML document, `this.defaultNamespace` is used to create it, * and it will not contain any `childNodes`. * If it is an HTML document, it will be created without any `childNodes`. * * @see http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html */ startDocument: function () { var impl = new DOMImplementation(); this.doc = isHTMLMimeType(this.mimeType) ? impl.createHTMLDocument(false) : impl.createDocument(this.defaultNamespace, ''); }, startElement: function (namespaceURI, localName, qName, attrs) { var doc = this.doc; var el = doc.createElementNS(namespaceURI, qName || localName); var len = attrs.length; appendElement(this, el); this.currentElement = el; this.locator && position(this.locator, el); for (var i = 0; i < len; i++) { var namespaceURI = attrs.getURI(i); var value = attrs.getValue(i); var qName = attrs.getQName(i); var attr = doc.createAttributeNS(namespaceURI, qName); this.locator && position(attrs.getLocator(i), attr); attr.value = attr.nodeValue = value; el.setAttributeNode(attr); } }, endElement: function (namespaceURI, localName, qName) { this.currentElement = this.currentElement.parentNode; }, startPrefixMapping: function (prefix, uri) {}, endPrefixMapping: function (prefix) {}, processingInstruction: function (target, data) { var ins = this.doc.createProcessingInstruction(target, data); this.locator && position(this.locator, ins); appendElement(this, ins); }, ignorableWhitespace: function (ch, start, length) {}, characters: function (chars, start, length) { chars = _toString.apply(this, arguments); //console.log(chars) if (chars) { if (this.cdata) { var charNode = this.doc.createCDATASection(chars); } else { var charNode = this.doc.createTextNode(chars); } if (this.currentElement) { this.currentElement.appendChild(charNode); } else if (/^\s*$/.test(chars)) { this.doc.appendChild(charNode); //process xml } this.locator && position(this.locator, charNode); } }, skippedEntity: function (name) {}, endDocument: function () { this.doc.normalize(); }, /** * Stores the locator to be able to set the `columnNumber` and `lineNumber` * on the created DOM nodes. * * @param {Locator} locator */ setDocumentLocator: function (locator) { if (locator) { locator.lineNumber = 0; } this.locator = locator; }, //LexicalHandler comment: function (chars, start, length) { chars = _toString.apply(this, arguments); var comm = this.doc.createComment(chars); this.locator && position(this.locator, comm); appendElement(this, comm); }, startCDATA: function () { //used in characters() methods this.cdata = true; }, endCDATA: function () { this.cdata = false; }, startDTD: function (name, publicId, systemId, internalSubset) { var impl = this.doc.implementation; if (impl && impl.createDocumentType) { var dt = impl.createDocumentType(name, publicId, systemId, internalSubset); this.locator && position(this.locator, dt); appendElement(this, dt); this.doc.doctype = dt; } }, reportError: function (level, message) { if (typeof this.onError === 'function') { try { this.onError(level, message, this); } catch (e) { throw new ParseError('Reporting ' + level + ' "' + message + '" caused ' + e, this.locator); } } else { console.error('[xmldom ' + level + ']\t' + message, _locator(this.locator)); } }, /** * @see http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html */ warning: function (message) { this.reportError('warning', message); }, error: function (message) { this.reportError('error', message); }, /** * This function reports a fatal error and throws a ParseError. * * @param {string} message * - The message to be used for reporting and throwing the error. * @returns {never} * This function always throws an error and never returns a value. * @throws {ParseError} * Always throws a ParseError with the provided message. */ fatalError: function (message) { this.reportError('fatalError', message); throw new ParseError(message, this.locator); }, }; function _locator(l) { if (l) { return '\n@#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']'; } } function _toString(chars, start, length) { if (typeof chars == 'string') { return chars.substr(start, length); } else { //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") if (chars.length >= start + length || start) { return new java.lang.String(chars, start, length) + ''; } return chars; } } /* * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html * used method of org.xml.sax.ext.LexicalHandler: * #comment(chars, start, length) * #startCDATA() * #endCDATA() * #startDTD(name, publicId, systemId) * * * IGNORED method of org.xml.sax.ext.LexicalHandler: * #endDTD() * #startEntity(name) * #endEntity(name) * * * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html * IGNORED method of org.xml.sax.ext.DeclHandler * #attributeDecl(eName, aName, type, mode, value) * #elementDecl(name, model) * #externalEntityDecl(name, publicId, systemId) * #internalEntityDecl(name, value) * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html * IGNORED method of org.xml.sax.EntityResolver2 * #resolveEntity(String name,String publicId,String baseURI,String systemId) * #resolveEntity(publicId, systemId) * #getExternalSubset(name, baseURI) * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html * IGNORED method of org.xml.sax.DTDHandler * #notationDecl(name, publicId, systemId) {}; * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; */ 'endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl'.replace( /\w+/g, function (key) { DOMHandler.prototype[key] = function () { return null; }; } ); /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ function appendElement(handler, node) { if (!handler.currentElement) { handler.doc.appendChild(node); } else { handler.currentElement.appendChild(node); } } /** * A method that prevents any further parsing when an `error` * with level `error` is reported during parsing. * * @see {@link DOMParserOptions.onError} * @see {@link onWarningStopParsing} */ function onErrorStopParsing(level) { if (level === 'error') throw 'onErrorStopParsing'; } /** * A method that prevents any further parsing when any `error` is reported during parsing. * * @see {@link DOMParserOptions.onError} * @see {@link onErrorStopParsing} */ function onWarningStopParsing() { throw 'onWarningStopParsing'; } exports.__DOMHandler = DOMHandler; exports.DOMParser = DOMParser; exports.normalizeLineEndings = normalizeLineEndings; exports.onErrorStopParsing = onErrorStopParsing; exports.onWarningStopParsing = onWarningStopParsing; /***/ }), /***/ 7311: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var conventions = __nccwpck_require__(7855); var find = conventions.find; var hasDefaultHTMLNamespace = conventions.hasDefaultHTMLNamespace; var hasOwn = conventions.hasOwn; var isHTMLMimeType = conventions.isHTMLMimeType; var isHTMLRawTextElement = conventions.isHTMLRawTextElement; var isHTMLVoidElement = conventions.isHTMLVoidElement; var MIME_TYPE = conventions.MIME_TYPE; var NAMESPACE = conventions.NAMESPACE; /** * Private DOM Constructor symbol * * Internal symbol used for construction of all classes whose constructors should be private. * Currently used for checks in `Node`, `Document`, `Element`, `Attr`, `CharacterData`, `Text`, `Comment`, * `CDATASection`, `DocumentType`, `Notation`, `Entity`, `EntityReference`, `DocumentFragment`, `ProcessingInstruction` * so the constructor can't be used from outside the module. */ var PDC = Symbol(); var errors = __nccwpck_require__(7368); var DOMException = errors.DOMException; var DOMExceptionName = errors.DOMExceptionName; var g = __nccwpck_require__(2062); /** * Checks if the given symbol equals the Private DOM Constructor symbol (PDC) * and throws an Illegal constructor exception when the symbols don't match. * This ensures that the constructor remains private and can't be used outside this module. */ function checkSymbol(symbol) { if (symbol !== PDC) { throw new TypeError('Illegal constructor'); } } /** * A prerequisite for `[].filter`, to drop elements that are empty. * * @param {string} input * The string to be checked. * @returns {boolean} * Returns `true` if the input string is not empty, `false` otherwise. */ function notEmptyString(input) { return input !== ''; } /** * Splits a string on ASCII whitespace characters (U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, * U+0020 SPACE). * It follows the definition from the infra specification from WHATWG. * * @param {string} input * The string to be split. * @returns {string[]} * An array of the split strings. The array can be empty if the input string is empty or only * contains whitespace characters. * @see {@link https://infra.spec.whatwg.org/#split-on-ascii-whitespace} * @see {@link https://infra.spec.whatwg.org/#ascii-whitespace} */ function splitOnASCIIWhitespace(input) { // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : []; } /** * Adds element as a key to current if it is not already present. * * @param {Record} current * The current record object to which the element will be added as a key. * The object's keys are string types and values are either boolean or undefined. * @param {string} element * The string to be added as a key to the current record. * @returns {Record} * The updated record object after the addition of the new element. */ function orderedSetReducer(current, element) { if (!hasOwn(current, element)) { current[element] = true; } return current; } /** * Converts a string into an ordered set by splitting the input on ASCII whitespace and * ensuring uniqueness of elements. * This follows the definition of an ordered set from the infra specification by WHATWG. * * @param {string} input * The input string to be transformed into an ordered set. * @returns {string[]} * An array of unique strings obtained from the input, preserving the original order. * The array can be empty if the input string is empty or only contains whitespace characters. * @see {@link https://infra.spec.whatwg.org/#ordered-set} */ function toOrderedSet(input) { if (!input) return []; var list = splitOnASCIIWhitespace(input); return Object.keys(list.reduce(orderedSetReducer, {})); } /** * Uses `list.indexOf` to implement a function that behaves like `Array.prototype.includes`. * This function is used in environments where `Array.prototype.includes` may not be available. * * @param {any[]} list * The array in which to search for the element. * @returns {function(any): boolean} * A function that accepts an element and returns a boolean indicating whether the element is * included in the provided list. */ function arrayIncludes(list) { return function (element) { return list && list.indexOf(element) !== -1; }; } /** * Validates a qualified name based on the criteria provided in the DOM specification by * WHATWG. * * @param {string} qualifiedName * The qualified name to be validated. * @throws {DOMException} * With code {@link DOMException.INVALID_CHARACTER_ERR} if the qualified name contains an * invalid character. * @see {@link https://dom.spec.whatwg.org/#validate} */ function validateQualifiedName(qualifiedName) { if (!g.QName_exact.test(qualifiedName)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'invalid character in qualified name "' + qualifiedName + '"'); } } /** * Validates a qualified name and the namespace associated with it, * based on the criteria provided in the DOM specification by WHATWG. * * @param {string | null} namespace * The namespace to be validated. It can be a string or null. * @param {string} qualifiedName * The qualified name to be validated. * @returns {[namespace: string | null, prefix: string | null, localName: string]} * Returns a tuple with the namespace, * prefix and local name of the qualified name. * @throws {DOMException} * Throws a DOMException if the qualified name or the namespace is not valid. * @see {@link https://dom.spec.whatwg.org/#validate-and-extract} */ function validateAndExtract(namespace, qualifiedName) { validateQualifiedName(qualifiedName); namespace = namespace || null; /** * @type {string | null} */ var prefix = null; var localName = qualifiedName; if (qualifiedName.indexOf(':') >= 0) { var splitResult = qualifiedName.split(':'); prefix = splitResult[0]; localName = splitResult[1]; } if (prefix !== null && namespace === null) { throw new DOMException(DOMException.NAMESPACE_ERR, 'prefix is non-null and namespace is null'); } if (prefix === 'xml' && namespace !== conventions.NAMESPACE.XML) { throw new DOMException(DOMException.NAMESPACE_ERR, 'prefix is "xml" and namespace is not the XML namespace'); } if ((prefix === 'xmlns' || qualifiedName === 'xmlns') && namespace !== conventions.NAMESPACE.XMLNS) { throw new DOMException( DOMException.NAMESPACE_ERR, 'either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace' ); } if (namespace === conventions.NAMESPACE.XMLNS && prefix !== 'xmlns' && qualifiedName !== 'xmlns') { throw new DOMException( DOMException.NAMESPACE_ERR, 'namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns"' ); } return [namespace, prefix, localName]; } /** * Copies properties from one object to another. * It only copies the object's own (not inherited) properties. * * @param {Object} src * The source object from which properties are copied. * @param {Object} dest * The destination object to which properties are copied. */ function copy(src, dest) { for (var p in src) { if (hasOwn(src, p)) { dest[p] = src[p]; } } } /** * Extends a class with the properties and methods of a super class. * It uses a form of prototypal inheritance, and establishes the `constructor` property * correctly(?). * * It is not clear to the current maintainers if this implementation is making sense, * since it creates an intermediate prototype function, * which all properties of `Super` are copied onto using `_copy`. * * @param {Object} Class * The class that is to be extended. * @param {Object} Super * The super class from which properties and methods are inherited. * @private */ function _extends(Class, Super) { var pt = Class.prototype; if (!(pt instanceof Super)) { function t() {} t.prototype = Super.prototype; t = new t(); copy(pt, t); Class.prototype = pt = t; } if (pt.constructor != Class) { if (typeof Class != 'function') { console.error('unknown Class:' + Class); } pt.constructor = Class; } } var NodeType = {}; var ELEMENT_NODE = (NodeType.ELEMENT_NODE = 1); var ATTRIBUTE_NODE = (NodeType.ATTRIBUTE_NODE = 2); var TEXT_NODE = (NodeType.TEXT_NODE = 3); var CDATA_SECTION_NODE = (NodeType.CDATA_SECTION_NODE = 4); var ENTITY_REFERENCE_NODE = (NodeType.ENTITY_REFERENCE_NODE = 5); var ENTITY_NODE = (NodeType.ENTITY_NODE = 6); var PROCESSING_INSTRUCTION_NODE = (NodeType.PROCESSING_INSTRUCTION_NODE = 7); var COMMENT_NODE = (NodeType.COMMENT_NODE = 8); var DOCUMENT_NODE = (NodeType.DOCUMENT_NODE = 9); var DOCUMENT_TYPE_NODE = (NodeType.DOCUMENT_TYPE_NODE = 10); var DOCUMENT_FRAGMENT_NODE = (NodeType.DOCUMENT_FRAGMENT_NODE = 11); var NOTATION_NODE = (NodeType.NOTATION_NODE = 12); var DocumentPosition = conventions.freeze({ DOCUMENT_POSITION_DISCONNECTED: 1, DOCUMENT_POSITION_PRECEDING: 2, DOCUMENT_POSITION_FOLLOWING: 4, DOCUMENT_POSITION_CONTAINS: 8, DOCUMENT_POSITION_CONTAINED_BY: 16, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32, }); //helper functions for compareDocumentPosition /** * Finds the common ancestor in two parent chains. * * @param {Node[]} a * The first parent chain. * @param {Node[]} b * The second parent chain. * @returns {Node} * The common ancestor node if it exists. If there is no common ancestor, the function will * return `null`. */ function commonAncestor(a, b) { if (b.length < a.length) return commonAncestor(b, a); var c = null; for (var n in a) { if (a[n] !== b[n]) return c; c = a[n]; } return c; } /** * Assigns a unique identifier to a document to ensure consistency while comparing unrelated * nodes. * * @param {Document} doc * The document to which a unique identifier is to be assigned. * @returns {string} * The unique identifier of the document. If the document already had a unique identifier, the * function will return the existing one. */ function docGUID(doc) { if (!doc.guid) doc.guid = Math.random(); return doc.guid; } //-- end of helper functions /** * The NodeList interface provides the abstraction of an ordered collection of nodes, * without defining or constraining how this collection is implemented. * NodeList objects in the DOM are live. * The items in the NodeList are accessible via an integral index, starting from 0. * You can also access the items of the NodeList with a `for...of` loop. * * @class NodeList * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 * @constructs NodeList */ function NodeList() {} NodeList.prototype = { /** * The number of nodes in the list. The range of valid child node indices is 0 to length-1 * inclusive. * * @type {number} */ length: 0, /** * Returns the item at `index`. If index is greater than or equal to the number of nodes in * the list, this returns null. * * @param index * Unsigned long Index into the collection. * @returns {Node | null} * The node at position `index` in the NodeList, * or null if that is not a valid index. */ item: function (index) { return index >= 0 && index < this.length ? this[index] : null; }, /** * Returns a string representation of the NodeList. * * Accepts the same `options` object as `XMLSerializer.prototype.serializeToString` * (`requireWellFormed`, `splitCDATASections`, `nodeFilter`). Passing a function is treated as * a legacy `nodeFilter` for backward compatibility. * * @param {Object | function} [options] * @param {boolean} [options.requireWellFormed=false] * @param {boolean} [options.splitCDATASections=true] * @param {function} [options.nodeFilter] * @returns {string} */ toString: function (options) { var opts; if (typeof options === 'function') { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options }; } else if (!!options) { opts = { requireWellFormed: !!options.requireWellFormed, splitCDATASections: options.splitCDATASections !== false, nodeFilter: options.nodeFilter || null, }; } else { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null }; } for (var buf = [], i = 0; i < this.length; i++) { serializeToString(this[i], buf, null, opts); } return buf.join(''); }, /** * Filters the NodeList based on a predicate. * * @param {function(Node): boolean} predicate * - A predicate function to filter the NodeList. * @returns {Node[]} * An array of nodes that satisfy the predicate. * @private */ filter: function (predicate) { return Array.prototype.filter.call(this, predicate); }, /** * Returns the first index at which a given node can be found in the NodeList, or -1 if it is * not present. * * @param {Node} item * - The Node item to locate in the NodeList. * @returns {number} * The first index of the node in the NodeList; -1 if not found. * @private */ indexOf: function (item) { return Array.prototype.indexOf.call(this, item); }, }; NodeList.prototype[Symbol.iterator] = function () { var me = this; var index = 0; return { next: function () { if (index < me.length) { return { value: me[index++], done: false, }; } else { return { done: true, }; } }, return: function () { return { done: true, }; }, }; }; /** * Represents a live collection of nodes that is automatically updated when its associated * document changes. * * @class LiveNodeList * @param {Node} node * The associated node. * @param {function} refresh * The function to refresh the live node list. * @augments NodeList * @constructs LiveNodeList */ function LiveNodeList(node, refresh) { this._node = node; this._refresh = refresh; _updateLiveList(this); } /** * Updates the live node list. * * @param {LiveNodeList} list * The live node list to update. * @private */ function _updateLiveList(list) { var inc = list._node._inc || list._node.ownerDocument._inc; if (list._inc !== inc) { var ls = list._refresh(list._node); __set__(list, 'length', ls.length); if (!list.$$length || ls.length < list.$$length) { for (var i = ls.length; i in list; i++) { if (hasOwn(list, i)) { delete list[i]; } } } copy(ls, list); list._inc = inc; } } /** * Returns the node at position `index` in the LiveNodeList, or null if that is not a valid * index. * * @param {number} i * Index into the collection. * @returns {Node | null} * The node at position `index` in the LiveNodeList, or null if that is not a valid index. */ LiveNodeList.prototype.item = function (i) { _updateLiveList(this); return this[i] || null; }; _extends(LiveNodeList, NodeList); /** * Objects implementing the NamedNodeMap interface are used to represent collections of nodes * that can be accessed by name. * Note that NamedNodeMap does not inherit from NodeList; * NamedNodeMaps are not maintained in any particular order. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal * index, * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, * and does not imply that the DOM specifies an order to these Nodes. * NamedNodeMap objects in the DOM are live. * used for attributes or DocumentType entities * * This implementation only supports property indices, but does not support named properties, * as specified in the living standard. * * @class NamedNodeMap * @see https://dom.spec.whatwg.org/#interface-namednodemap * @see https://webidl.spec.whatwg.org/#dfn-supported-property-names * @constructs NamedNodeMap */ function NamedNodeMap() {} /** * Returns the index of a node within the list. * * @param {Array} list * The list of nodes. * @param {Node} node * The node to find. * @returns {number} * The index of the node within the list, or -1 if not found. * @private */ function _findNodeIndex(list, node) { var i = 0; while (i < list.length) { if (list[i] === node) { return i; } i++; } } /** * Adds a new attribute to the list and updates the owner element of the attribute. * * @param {Element} el * The element which will become the owner of the new attribute. * @param {NamedNodeMap} list * The list to which the new attribute will be added. * @param {Attr} newAttr * The new attribute to be added. * @param {Attr} oldAttr * The old attribute to be replaced, or null if no attribute is to be replaced. * @returns {void} * @private */ function _addNamedNode(el, list, newAttr, oldAttr) { if (oldAttr) { list[_findNodeIndex(list, oldAttr)] = newAttr; } else { list[list.length] = newAttr; list.length++; } if (el) { newAttr.ownerElement = el; var doc = el.ownerDocument; if (doc) { oldAttr && _onRemoveAttribute(doc, el, oldAttr); _onAddAttribute(doc, el, newAttr); } } } /** * Removes an attribute from the list and updates the owner element of the attribute. * * @param {Element} el * The element which is the current owner of the attribute. * @param {NamedNodeMap} list * The list from which the attribute will be removed. * @param {Attr} attr * The attribute to be removed. * @returns {void} * @private */ function _removeNamedNode(el, list, attr) { //console.log('remove attr:'+attr) var i = _findNodeIndex(list, attr); if (i >= 0) { var lastIndex = list.length - 1; while (i <= lastIndex) { list[i] = list[++i]; } list.length = lastIndex; if (el) { var doc = el.ownerDocument; if (doc) { _onRemoveAttribute(doc, el, attr); } attr.ownerElement = null; } } } NamedNodeMap.prototype = { length: 0, item: NodeList.prototype.item, /** * Get an attribute by name. Note: Name is in lower case in case of HTML namespace and * document. * * @param {string} localName * The local name of the attribute. * @returns {Attr | null} * The attribute with the given local name, or null if no such attribute exists. * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name */ getNamedItem: function (localName) { if (this._ownerElement && this._ownerElement._isInHTMLDocumentAndNamespace()) { localName = localName.toLowerCase(); } var i = 0; while (i < this.length) { var attr = this[i]; if (attr.nodeName === localName) { return attr; } i++; } return null; }, /** * Set an attribute. * * @param {Attr} attr * The attribute to set. * @returns {Attr | null} * The old attribute with the same local name and namespace URI as the new one, or null if no * such attribute exists. * @throws {DOMException} * With code: * - {@link INUSE_ATTRIBUTE_ERR} - If the attribute is already an attribute of another * element. * @see https://dom.spec.whatwg.org/#concept-element-attributes-set */ setNamedItem: function (attr) { var el = attr.ownerElement; if (el && el !== this._ownerElement) { throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR); } var oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName); if (oldAttr === attr) { return attr; } _addNamedNode(this._ownerElement, this, attr, oldAttr); return oldAttr; }, /** * Set an attribute, replacing an existing attribute with the same local name and namespace * URI if one exists. * * @param {Attr} attr * The attribute to set. * @returns {Attr | null} * The old attribute with the same local name and namespace URI as the new one, or null if no * such attribute exists. * @throws {DOMException} * Throws a DOMException with the name "InUseAttributeError" if the attribute is already an * attribute of another element. * @see https://dom.spec.whatwg.org/#concept-element-attributes-set */ setNamedItemNS: function (attr) { return this.setNamedItem(attr); }, /** * Removes an attribute specified by the local name. * * @param {string} localName * The local name of the attribute to be removed. * @returns {Attr} * The attribute node that was removed. * @throws {DOMException} * With code: * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given name is found. * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditem * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-name */ removeNamedItem: function (localName) { var attr = this.getNamedItem(localName); if (!attr) { throw new DOMException(DOMException.NOT_FOUND_ERR, localName); } _removeNamedNode(this._ownerElement, this, attr); return attr; }, /** * Removes an attribute specified by the namespace and local name. * * @param {string | null} namespaceURI * The namespace URI of the attribute to be removed. * @param {string} localName * The local name of the attribute to be removed. * @returns {Attr} * The attribute node that was removed. * @throws {DOMException} * With code: * - {@link DOMException.NOT_FOUND_ERR} if no attribute with the given namespace URI and local * name is found. * @see https://dom.spec.whatwg.org/#dom-namednodemap-removenameditemns * @see https://dom.spec.whatwg.org/#concept-element-attributes-remove-by-namespace */ removeNamedItemNS: function (namespaceURI, localName) { var attr = this.getNamedItemNS(namespaceURI, localName); if (!attr) { throw new DOMException(DOMException.NOT_FOUND_ERR, namespaceURI ? namespaceURI + ' : ' + localName : localName); } _removeNamedNode(this._ownerElement, this, attr); return attr; }, /** * Get an attribute by namespace and local name. * * @param {string | null} namespaceURI * The namespace URI of the attribute. * @param {string} localName * The local name of the attribute. * @returns {Attr | null} * The attribute with the given namespace URI and local name, or null if no such attribute * exists. * @see https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace */ getNamedItemNS: function (namespaceURI, localName) { if (!namespaceURI) { namespaceURI = null; } var i = 0; while (i < this.length) { var node = this[i]; if (node.localName === localName && node.namespaceURI === namespaceURI) { return node; } i++; } return null; }, }; NamedNodeMap.prototype[Symbol.iterator] = function () { var me = this; var index = 0; return { next: function () { if (index < me.length) { return { value: me[index++], done: false, }; } else { return { done: true, }; } }, return: function () { return { done: true, }; }, }; }; /** * The DOMImplementation interface provides a number of methods for performing operations that * are independent of any particular instance of the document object model. * * The DOMImplementation interface represents an object providing methods which are not * dependent on any particular document. * Such an object is returned by the `Document.implementation` property. * * **The individual methods describe the differences compared to the specs**. * * @class DOMImplementation * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core * (Initial) * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard * @constructs DOMImplementation */ function DOMImplementation() {} DOMImplementation.prototype = { /** * Test if the DOM implementation implements a specific feature and version, as specified in * {@link https://www.w3.org/TR/DOM-Level-3-Core/core.html#DOMFeatures DOM Features}. * * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given * feature is supported. The different implementations fairly diverged in what kind of * features were reported. The latest version of the spec settled to force this method to * always return true, where the functionality was accurate and in use. * * @deprecated * It is deprecated and modern browsers return true in all cases. * @function DOMImplementation#hasFeature * @param {string} feature * The name of the feature to test. * @param {string} [version] * This is the version number of the feature to test. * @returns {boolean} * Always returns true. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-5CED94D7 DOM Level 3 Core */ hasFeature: function (feature, version) { return true; }, /** * Creates a DOM Document object of the specified type with its document element. Note that * based on the {@link DocumentType} * given to create the document, the implementation may instantiate specialized * {@link Document} objects that support additional features than the "Core", such as "HTML" * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML}. * On the other hand, setting the {@link DocumentType} after the document was created makes * this very unlikely to happen. Alternatively, specialized {@link Document} creation methods, * such as createHTMLDocument * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#DOM2HTML DOM Level 2 HTML}, * can be used to obtain specific types of {@link Document} objects. * * __It behaves slightly different from the description in the living standard__: * - There is no interface/class `XMLDocument`, it returns a `Document` * instance (with it's `type` set to `'xml'`). * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * * @function DOMImplementation.createDocument * @param {string | null} namespaceURI * The * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-namespaceURI namespace URI} * of the document element to create or null. * @param {string | null} qualifiedName * The * {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified name} * of the document element to be created or null. * @param {DocumentType | null} [doctype=null] * The type of document to be created or null. When doctype is not null, its * {@link Node#ownerDocument} attribute is set to the document being created. Default is * `null` * @returns {Document} * A new {@link Document} object with its document element. If the NamespaceURI, * qualifiedName, and doctype are null, the returned {@link Document} is empty with no * document element. * @throws {DOMException} * With code: * * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}. * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed, if the qualifiedName has a * prefix and the namespaceURI is null, or if the qualifiedName is null and the namespaceURI * is different from null, or if the qualifiedName has a prefix that is "xml" and the * namespaceURI is different from "{@link http://www.w3.org/XML/1998/namespace}" * {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#Namespaces XML Namespaces}, * or if the DOM implementation does not support the "XML" feature but a non-null namespace * URI was provided, since namespaces were defined by XML. * - `WRONG_DOCUMENT_ERR`: Raised if doctype has already been used with a different document * or was created from a different implementation. * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature * "XML" and the language exposed through the Document does not support XML Namespaces (such * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}). * @since DOM Level 2. * @see {@link #createHTMLDocument} * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Living Standard * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-2-Core-DOM-createDocument DOM * Level 3 Core * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM * Level 2 Core (initial) */ createDocument: function (namespaceURI, qualifiedName, doctype) { var contentType = MIME_TYPE.XML_APPLICATION; if (namespaceURI === NAMESPACE.HTML) { contentType = MIME_TYPE.XML_XHTML_APPLICATION; } else if (namespaceURI === NAMESPACE.SVG) { contentType = MIME_TYPE.XML_SVG_IMAGE; } var doc = new Document(PDC, { contentType: contentType }); doc.implementation = this; doc.childNodes = new NodeList(); doc.doctype = doctype || null; if (doctype) { doc.appendChild(doctype); } if (qualifiedName) { var root = doc.createElementNS(namespaceURI, qualifiedName); doc.appendChild(root); } return doc; }, /** * Creates an empty DocumentType node. Entity declarations and notations are not made * available. Entity reference expansions and default attribute additions do not occur. * * **This behavior is slightly different from the one in the specs**: * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * - `publicId` and `systemId` contain the raw data including any possible quotes, * so they can always be serialized back to the original value * - `internalSubset` contains the raw string between `[` and `]` if present, * but is not parsed or validated in any form. * * @function DOMImplementation#createDocumentType * @param {string} qualifiedName * The {@link https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-qualifiedname qualified * name} of the document type to be created. * @param {string} [publicId] * The external subset public identifier. Stored verbatim including surrounding quotes. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value is non-empty and does not match the XML `PubidLiteral` production * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [12]). Creation-time validation is not * enforced — deferred to a future breaking release. * @param {string} [systemId] * The external subset system identifier. Stored verbatim including surrounding quotes. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value is non-empty and does not match the XML `SystemLiteral` production * (W3C DOM Parsing §3.2.1.3; XML 1.0 production [11]). Creation-time validation is not * enforced — deferred to a future breaking release. * @param {string} [internalSubset] * The internal subset or an empty string if it is not present. Stored verbatim. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value contains `"]>"`. Creation-time validation is not enforced. * @returns {DocumentType} * A new {@link DocumentType} node with {@link Node#ownerDocument} set to null. * @throws {DOMException} * With code: * * - `INVALID_CHARACTER_ERR`: Raised if the specified qualified name is not an XML name * according to {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#XML XML 1.0}. * - `NAMESPACE_ERR`: Raised if the qualifiedName is malformed. * - `NOT_SUPPORTED_ERR`: May be raised if the implementation does not support the feature * "XML" and the language exposed through the Document does not support XML Namespaces (such * as {@link https://www.w3.org/TR/DOM-Level-3-Core/references.html#HTML40 HTML 4.01}). * @since DOM Level 2. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType * MDN * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living * Standard * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Level-3-Core-DOM-createDocType DOM * Level 3 Core * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM * Level 2 Core * @see https://github.com/xmldom/xmldom/blob/master/CHANGELOG.md#050 * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-Core-DocType-internalSubset * @prettierignore */ createDocumentType: function (qualifiedName, publicId, systemId, internalSubset) { validateQualifiedName(qualifiedName); var node = new DocumentType(PDC); node.name = qualifiedName; node.nodeName = qualifiedName; node.publicId = publicId || ''; node.systemId = systemId || ''; node.internalSubset = internalSubset || ''; node.childNodes = new NodeList(); return node; }, /** * Returns an HTML document, that might already have a basic DOM structure. * * __It behaves slightly different from the description in the living standard__: * - If the first argument is `false` no initial nodes are added (steps 3-7 in the specs are * omitted) * - `encoding`, `mode`, `origin`, `url` fields are currently not declared. * * @param {string | false} [title] * A string containing the title to give the new HTML document. * @returns {Document} * The HTML document. * @since WHATWG Living Standard. * @see {@link #createDocument} * @see https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument * @see https://dom.spec.whatwg.org/#html-document */ createHTMLDocument: function (title) { var doc = new Document(PDC, { contentType: MIME_TYPE.HTML }); doc.implementation = this; doc.childNodes = new NodeList(); if (title !== false) { doc.doctype = this.createDocumentType('html'); doc.doctype.ownerDocument = doc; doc.appendChild(doc.doctype); var htmlNode = doc.createElement('html'); doc.appendChild(htmlNode); var headNode = doc.createElement('head'); htmlNode.appendChild(headNode); if (typeof title === 'string') { var titleNode = doc.createElement('title'); titleNode.appendChild(doc.createTextNode(title)); headNode.appendChild(titleNode); } htmlNode.appendChild(doc.createElement('body')); } return doc; }, }; /** * The DOM Node interface is an abstract base class upon which many other DOM API objects are * based, thus letting those object types to be used similarly and often interchangeably. As an * abstract class, there is no such thing as a plain Node object. All objects that implement * Node functionality are based on one of its subclasses. Most notable are Document, Element, * and DocumentFragment. * * In addition, every kind of DOM node is represented by an interface based on Node. These * include Attr, CharacterData (which Text, Comment, CDATASection and ProcessingInstruction are * all based on), and DocumentType. * * In some cases, a particular feature of the base Node interface may not apply to one of its * child interfaces; in that case, the inheriting node may return null or throw an exception, * depending on circumstances. For example, attempting to add children to a node type that * cannot have children will throw an exception. * * **This behavior is slightly different from the in the specs**: * - unimplemented interfaces: `EventTarget` * * @class * @abstract * @param {Symbol} symbol * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 * @see https://dom.spec.whatwg.org/#node * @prettierignore */ function Node(symbol) { checkSymbol(symbol); } Node.prototype = { /** * The first child of this node. * * @type {Node | null} */ firstChild: null, /** * The last child of this node. * * @type {Node | null} */ lastChild: null, /** * The previous sibling of this node. * * @type {Node | null} */ previousSibling: null, /** * The next sibling of this node. * * @type {Node | null} */ nextSibling: null, /** * The parent node of this node. * * @type {Node | null} */ parentNode: null, /** * The parent element of this node. * * @type {Element | null} */ get parentElement() { return this.parentNode && this.parentNode.nodeType === this.ELEMENT_NODE ? this.parentNode : null; }, /** * The child nodes of this node. * * @type {NodeList} */ childNodes: null, /** * The document object associated with this node. * * @type {Document | null} */ ownerDocument: null, /** * The value of this node. * * @type {string | null} */ nodeValue: null, /** * The namespace URI of this node. * * @type {string | null} */ namespaceURI: null, /** * The prefix of the namespace for this node. * * @type {string | null} */ prefix: null, /** * The local part of the qualified name of this node. * * @type {string | null} */ localName: null, /** * The baseURI is currently always `about:blank`, * since that's what happens when you create a document from scratch. * * @type {'about:blank'} */ baseURI: 'about:blank', /** * Is true if this node is part of a document. * * @type {boolean} */ get isConnected() { var rootNode = this.getRootNode(); return rootNode && rootNode.nodeType === rootNode.DOCUMENT_NODE; }, /** * Checks whether `other` is an inclusive descendant of this node. * * @param {Node | null | undefined} other * The node to check. * @returns {boolean} * True if `other` is an inclusive descendant of this node; false otherwise. * @see https://dom.spec.whatwg.org/#dom-node-contains */ contains: function (other) { if (!other) return false; var parent = other; do { if (this === parent) return true; parent = parent.parentNode; } while (parent); return false; }, /** * @typedef GetRootNodeOptions * @property {boolean} [composed=false] */ /** * Searches for the root node of this node. * * **This behavior is slightly different from the in the specs**: * - ignores `options.composed`, since `ShadowRoot`s are unsupported, always returns root. * * @param {GetRootNodeOptions} [options] * @returns {Node} * Root node. * @see https://dom.spec.whatwg.org/#dom-node-getrootnode * @see https://dom.spec.whatwg.org/#concept-shadow-including-root */ getRootNode: function (options) { var parent = this; do { if (!parent.parentNode) { return parent; } parent = parent.parentNode; } while (parent); }, /** * Checks whether the given node is equal to this node. * * Two nodes are equal when they have the same type, defining characteristics (for the type), * and the same childNodes. The comparison is iterative to avoid stack overflows on * deeply-nested trees. Attribute nodes of each Element pair are also pushed onto the stack * and compared the same way. * * @param {Node} [otherNode] * @returns {boolean} * @see https://dom.spec.whatwg.org/#concept-node-equals * @see ../docs/walk-dom.md. */ isEqualNode: function (otherNode) { if (!otherNode) return false; // Use an explicit {node, other} pair stack to avoid call-stack overflow on deep trees. // walkDOM cannot be used here — parallel two-tree traversal requires pairing // corresponding nodes at each step across both trees simultaneously. var stack = [{ node: this, other: otherNode }]; while (stack.length > 0) { var pair = stack.pop(); var node = pair.node; var other = pair.other; if (node.nodeType !== other.nodeType) return false; switch (node.nodeType) { case node.DOCUMENT_TYPE_NODE: if (node.name !== other.name) return false; if (node.publicId !== other.publicId) return false; if (node.systemId !== other.systemId) return false; break; case node.ELEMENT_NODE: if (node.namespaceURI !== other.namespaceURI) return false; if (node.prefix !== other.prefix) return false; if (node.localName !== other.localName) return false; if (node.attributes.length !== other.attributes.length) return false; for (var i = 0; i < node.attributes.length; i++) { var attr = node.attributes.item(i); var otherAttr = other.getAttributeNodeNS(attr.namespaceURI, attr.localName); if (!otherAttr) return false; stack.push({ node: attr, other: otherAttr }); } break; case node.ATTRIBUTE_NODE: if (node.namespaceURI !== other.namespaceURI) return false; if (node.localName !== other.localName) return false; if (node.value !== other.value) return false; break; case node.PROCESSING_INSTRUCTION_NODE: if (node.target !== other.target || node.data !== other.data) return false; break; case node.TEXT_NODE: case node.CDATA_SECTION_NODE: case node.COMMENT_NODE: if (node.data !== other.data) return false; break; } if (node.childNodes.length !== other.childNodes.length) return false; // Push children in reverse order so index 0 is processed first (LIFO). for (var i = node.childNodes.length - 1; i >= 0; i--) { stack.push({ node: node.childNodes[i], other: other.childNodes[i] }); } } return true; }, /** * Checks whether or not the given node is this node. * * @param {Node} [otherNode] */ isSameNode: function (otherNode) { return this === otherNode; }, /** * Inserts a node before a reference node as a child of this node. * * @param {Node} newChild * The new child node to be inserted. * @param {Node | null} refChild * The reference node before which newChild will be inserted. * @returns {Node} * The new child node successfully inserted. * @throws {DOMException} * Throws a DOMException if inserting the node would result in a DOM tree that is not * well-formed, or if `child` is provided but is not a child of `parent`. * See {@link _insertBefore} for more details. * @since Modified in DOM L2 */ insertBefore: function (newChild, refChild) { return _insertBefore(this, newChild, refChild); }, /** * Replaces an old child node with a new child node within this node. * * @param {Node} newChild * The new node that is to replace the old node. * If it already exists in the DOM, it is removed from its original position. * @param {Node} oldChild * The existing child node to be replaced. * @returns {Node} * Returns the replaced child node. * @throws {DOMException} * Throws a DOMException if replacing the node would result in a DOM tree that is not * well-formed, or if `oldChild` is not a child of `this`. * This can also occur if the pre-replacement validity assertion fails. * See {@link _insertBefore}, {@link Node.removeChild}, and * {@link assertPreReplacementValidityInDocument} for more details. * @see https://dom.spec.whatwg.org/#concept-node-replace */ replaceChild: function (newChild, oldChild) { _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); if (oldChild) { this.removeChild(oldChild); } }, /** * Removes an existing child node from this node. * * @param {Node} oldChild * The child node to be removed. * @returns {Node} * Returns the removed child node. * @throws {DOMException} * Throws a DOMException if `oldChild` is not a child of `this`. * See {@link _removeChild} for more details. */ removeChild: function (oldChild) { return _removeChild(this, oldChild); }, /** * Appends a child node to this node. * * @param {Node} newChild * The child node to be appended to this node. * If it already exists in the DOM, it is removed from its original position. * @returns {Node} * Returns the appended child node. * @throws {DOMException} * Throws a DOMException if appending the node would result in a DOM tree that is not * well-formed, or if `newChild` is not a valid Node. * See {@link insertBefore} for more details. */ appendChild: function (newChild) { return this.insertBefore(newChild, null); }, /** * Determines whether this node has any child nodes. * * @returns {boolean} * Returns true if this node has any child nodes, and false otherwise. */ hasChildNodes: function () { return this.firstChild != null; }, /** * Creates a copy of the calling node. * * @param {boolean} deep * If true, the contents of the node are recursively copied. * If false, only the node itself (and its attributes, if it is an element) are copied. * @returns {Node} * Returns the newly created copy of the node. * @throws {DOMException} * May throw a DOMException if operations within {@link Element#setAttributeNode} or * {@link Node#appendChild} (which are potentially invoked in this method) do not meet their * specific constraints. * @see {@link cloneNode} */ cloneNode: function (deep) { return cloneNode(this.ownerDocument || this, this, deep); }, /** * Puts the specified node and all of its subtree into a "normalized" form. In a normalized * subtree, no text nodes in the subtree are empty and there are no adjacent text nodes. * * Specifically, this method merges any adjacent text nodes (i.e., nodes for which `nodeType` * is `TEXT_NODE`) into a single node with the combined data. It also removes any empty text * nodes. * * This method iterativly traverses all child nodes to normalize all descendent nodes within * the subtree. * * @throws {DOMException} * May throw a DOMException if operations within removeChild or appendData (which are * potentially invoked in this method) do not meet their specific constraints. * @since Modified in DOM Level 2 * @see {@link Node.removeChild} * @see {@link CharacterData.appendData} * @see ../docs/walk-dom.md. */ normalize: function () { walkDOM(this, null, { enter: function (node) { // Merge adjacent text children of node before walkDOM schedules them. // walkDOM reads lastChild/previousSibling after enter returns, so the // surviving post-merge children are what it descends into. var child = node.firstChild; while (child) { var next = child.nextSibling; if (next !== null && next.nodeType === TEXT_NODE && child.nodeType === TEXT_NODE) { node.removeChild(next); child.appendData(next.data); // Do not advance child: re-check new nextSibling for another text run } else { child = next; } } return true; // descend into surviving children }, }); }, /** * Checks whether the DOM implementation implements a specific feature and its version. * * @deprecated * Since `DOMImplementation.hasFeature` is deprecated and always returns true. * @param {string} feature * The package name of the feature to test. This is the same name that can be passed to the * method `hasFeature` on `DOMImplementation`. * @param {string} version * This is the version number of the package name to test. * @returns {boolean} * Returns true in all cases in the current implementation. * @since Introduced in DOM Level 2 * @see {@link DOMImplementation.hasFeature} */ isSupported: function (feature, version) { return this.ownerDocument.implementation.hasFeature(feature, version); }, /** * Look up the prefix associated to the given namespace URI, starting from this node. * **The default namespace declarations are ignored by this method.** * See Namespace Prefix Lookup for details on the algorithm used by this method. * * **This behavior is different from the in the specs**: * - no node type specific handling * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes * * @param {string | null} namespaceURI * The namespace URI for which to find the associated prefix. * @returns {string | null} * The associated prefix, if found; otherwise, null. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix * @see https://github.com/xmldom/xmldom/issues/322 * @prettierignore */ lookupPrefix: function (namespaceURI) { var el = this; while (el) { var map = el._nsMap; //console.dir(map) if (map) { for (var n in map) { if (hasOwn(map, n) && map[n] === namespaceURI) { return n; } } } el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode; } return null; }, /** * This function is used to look up the namespace URI associated with the given prefix, * starting from this node. * * **This behavior is different from the in the specs**: * - no node type specific handling * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes * * @param {string | null} prefix * The prefix for which to find the associated namespace URI. * @returns {string | null} * The associated namespace URI, if found; otherwise, null. * @since DOM Level 3 * @see https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI * @prettierignore */ lookupNamespaceURI: function (prefix) { var el = this; while (el) { var map = el._nsMap; //console.dir(map) if (map) { if (hasOwn(map, prefix)) { return map[prefix]; } } el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode; } return null; }, /** * Determines whether the given namespace URI is the default namespace. * * The function works by looking up the prefix associated with the given namespace URI. If no * prefix is found (i.e., the namespace URI is not registered in the namespace map of this * node or any of its ancestors), it returns `true`, implying the namespace URI is considered * the default. * * **This behavior is different from the in the specs**: * - no node type specific handling * - uses the internal attribute _nsMap for resolving namespaces that is updated when changing attributes * * @param {string | null} namespaceURI * The namespace URI to be checked. * @returns {boolean} * Returns true if the given namespace URI is the default namespace, false otherwise. * @since DOM Level 3 * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace * @see https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace * @prettierignore */ isDefaultNamespace: function (namespaceURI) { var prefix = this.lookupPrefix(namespaceURI); return prefix == null; }, /** * Compares the reference node with a node with regard to their position in the document and * according to the document order. * * @param {Node} other * The node to compare the reference node to. * @returns {number} * Returns how the node is positioned relatively to the reference node according to the * bitmask. 0 if reference node and given node are the same. * @since DOM Level 3 * @see https://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#Node3-compare * @see https://dom.spec.whatwg.org/#dom-node-comparedocumentposition */ compareDocumentPosition: function (other) { if (this === other) return 0; var node1 = other; var node2 = this; var attr1 = null; var attr2 = null; if (node1 instanceof Attr) { attr1 = node1; node1 = attr1.ownerElement; } if (node2 instanceof Attr) { attr2 = node2; node2 = attr2.ownerElement; if (attr1 && node1 && node2 === node1) { for (var i = 0, attr; (attr = node2.attributes[i]); i++) { if (attr === attr1) return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_PRECEDING; if (attr === attr2) return DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + DocumentPosition.DOCUMENT_POSITION_FOLLOWING; } } } if (!node1 || !node2 || node2.ownerDocument !== node1.ownerDocument) { return ( DocumentPosition.DOCUMENT_POSITION_DISCONNECTED + DocumentPosition.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC + (docGUID(node2.ownerDocument) > docGUID(node1.ownerDocument) ? DocumentPosition.DOCUMENT_POSITION_FOLLOWING : DocumentPosition.DOCUMENT_POSITION_PRECEDING) ); } if (attr2 && node1 === node2) { return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING; } if (attr1 && node1 === node2) { return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING; } var chain1 = []; var ancestor1 = node1.parentNode; while (ancestor1) { if (!attr2 && ancestor1 === node2) { return DocumentPosition.DOCUMENT_POSITION_CONTAINED_BY + DocumentPosition.DOCUMENT_POSITION_FOLLOWING; } chain1.push(ancestor1); ancestor1 = ancestor1.parentNode; } chain1.reverse(); var chain2 = []; var ancestor2 = node2.parentNode; while (ancestor2) { if (!attr1 && ancestor2 === node1) { return DocumentPosition.DOCUMENT_POSITION_CONTAINS + DocumentPosition.DOCUMENT_POSITION_PRECEDING; } chain2.push(ancestor2); ancestor2 = ancestor2.parentNode; } chain2.reverse(); var ca = commonAncestor(chain1, chain2); for (var n in ca.childNodes) { var child = ca.childNodes[n]; if (child === node2) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING; if (child === node1) return DocumentPosition.DOCUMENT_POSITION_PRECEDING; if (chain2.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_FOLLOWING; if (chain1.indexOf(child) >= 0) return DocumentPosition.DOCUMENT_POSITION_PRECEDING; } return 0; }, }; /** * Encodes special XML characters to their corresponding entities. * * @param {string} c * The character to be encoded. * @returns {string} * The encoded character. * @private */ function _xmlEncoder(c) { return ( (c == '<' && '<') || (c == '>' && '>') || (c == '&' && '&') || (c == '"' && '"') || '&#' + c.charCodeAt() + ';' ); } copy(NodeType, Node); copy(NodeType, Node.prototype); copy(DocumentPosition, Node); copy(DocumentPosition, Node.prototype); /** * Visits every node in the subtree rooted at `node` in depth-first pre-order. * * Delegates to {@link walkDOM} for traversal. The `callback` is called on each node; * if it returns a truthy value, traversal stops immediately. * * @param {Node} node * Root of the subtree to visit. * @param {function(Node): *} callback * Called for each node. A truthy return value stops traversal early. */ function _visitNode(node, callback) { walkDOM(node, null, { enter: function (n) { return callback(n) ? walkDOM.STOP : true; }, }); } /** * Depth-first pre/post-order DOM tree walker. * * Visits every node in the subtree rooted at `node`. For each node: * * 1. Calls `callbacks.enter(node, context)` before descending into the node's children. The * return value becomes the `context` passed to each child's `enter` call and to the matching * `exit` call. * 2. If `enter` returns `null` or `undefined`, the node's children are skipped; * sibling traversal continues normally. * 3. If `enter` returns `walkDOM.STOP`, the entire traversal is aborted immediately — no * further `enter` or `exit` calls are made. * 4. `lastChild` and `previousSibling` are read **after** `enter` returns, so `enter` may * safely modify the node's own child list before the walker descends. Modifying siblings of * the current node or any other part of the tree produces unpredictable results: nodes already * queued on the stack are visited regardless of DOM changes, and newly inserted nodes outside * the current child list are never visited. * 5. Calls `callbacks.exit(node, context)` (if provided) after all of a node's children have * been visited, passing the same `context` that `enter` * returned for that node. * * This implementation uses an explicit stack and does not recurse — it is safe on arbitrarily * deep trees. * * @param {Node} node * Root of the subtree to walk. * @param {*} context * Initial context value passed to the root node's `enter`. * @param {{ enter: function(Node, *): *, exit?: function(Node, *): void }} callbacks * @returns {void | walkDOM.STOP} * @see ../docs/walk-dom.md. */ function walkDOM(node, context, callbacks) { // Each stack frame is {node, context, phase}: // walkDOM.ENTER — call enter, then push children // walkDOM.EXIT — call exit var stack = [{ node: node, context: context, phase: walkDOM.ENTER }]; while (stack.length > 0) { var frame = stack.pop(); if (frame.phase === walkDOM.ENTER) { var childContext = callbacks.enter(frame.node, frame.context); if (childContext === walkDOM.STOP) { return walkDOM.STOP; } // Push exit frame before children so it fires after all children are processed (Last In First Out) stack.push({ node: frame.node, context: childContext, phase: walkDOM.EXIT }); if (childContext === null || childContext === undefined) { continue; // skip children } // lastChild is read after enter returns, so enter may modify the child list. var child = frame.node.lastChild; // Traverse from lastChild backwards so that pushing onto the stack // naturally yields firstChild on top (processed first). while (child) { stack.push({ node: child, context: childContext, phase: walkDOM.ENTER }); child = child.previousSibling; } } else { // frame.phase === walkDOM.EXIT if (callbacks.exit) { callbacks.exit(frame.node, frame.context); } } } } /** * Sentinel value returned from a `walkDOM` `enter` callback to abort the entire traversal * immediately. * * @type {symbol} */ walkDOM.STOP = Symbol('walkDOM.STOP'); /** * Phase constant for a stack frame that has not yet been visited. * The `enter` callback is called and children are scheduled. * * @type {number} */ walkDOM.ENTER = 0; /** * Phase constant for a stack frame whose subtree has been fully visited. * The `exit` callback is called. * * @type {number} */ walkDOM.EXIT = 1; /** * @typedef DocumentOptions * @property {string} [contentType=MIME_TYPE.XML_APPLICATION] */ /** * The Document interface describes the common properties and methods for any kind of document. * * It should usually be created using `new DOMImplementation().createDocument(...)` * or `new DOMImplementation().createHTMLDocument(...)`. * * The constructor is considered a private API and offers to initially set the `contentType` * property via it's options parameter. * * @class * @param {Symbol} symbol * @param {DocumentOptions} [options] * @augments Node * @private * @see https://developer.mozilla.org/en-US/docs/Web/API/Document * @see https://dom.spec.whatwg.org/#interface-document */ function Document(symbol, options) { checkSymbol(symbol); var opt = options || {}; this.ownerDocument = this; /** * The mime type of the document is determined at creation time and can not be modified. * * @type {string} * @see https://dom.spec.whatwg.org/#concept-document-content-type * @see {@link DOMImplementation} * @see {@link MIME_TYPE} * @readonly */ this.contentType = opt.contentType || MIME_TYPE.XML_APPLICATION; /** * @type {'html' | 'xml'} * @see https://dom.spec.whatwg.org/#concept-document-type * @see {@link DOMImplementation} * @readonly */ this.type = isHTMLMimeType(this.contentType) ? 'html' : 'xml'; } /** * Updates the namespace mapping of an element when a new attribute is added. * * @param {Document} doc * The document that the element belongs to. * @param {Element} el * The element to which the attribute is being added. * @param {Attr} newAttr * The new attribute being added. * @private */ function _onAddAttribute(doc, el, newAttr) { doc && doc._inc++; var ns = newAttr.namespaceURI; if (ns === NAMESPACE.XMLNS) { //update namespace el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value; } } /** * Updates the namespace mapping of an element when an attribute is removed. * * @param {Document} doc * The document that the element belongs to. * @param {Element} el * The element from which the attribute is being removed. * @param {Attr} newAttr * The attribute being removed. * @param {boolean} remove * Indicates whether the attribute is to be removed. * @private */ function _onRemoveAttribute(doc, el, newAttr, remove) { doc && doc._inc++; var ns = newAttr.namespaceURI; if (ns === NAMESPACE.XMLNS) { //update namespace delete el._nsMap[newAttr.prefix ? newAttr.localName : '']; } } /** * Updates `parent.childNodes`, adjusting the indexed items and its `length`. * If `newChild` is provided and has no nextSibling, it will be appended. * Otherwise, it's assumed that an item has been removed or inserted, * and `parent.firstNode` and its `.nextSibling` to re-indexing all child nodes of `parent`. * * @param {Document} doc * The parent document of `el`. * @param {Node} parent * The parent node whose childNodes list needs to be updated. * @param {Node} [newChild] * The new child node to be appended. If not provided, the function assumes a node has been * removed. * @private */ function _onUpdateChild(doc, parent, newChild) { if (doc && doc._inc) { doc._inc++; var childNodes = parent.childNodes; // assumes nextSibling and previousSibling were already configured upfront if (newChild && !newChild.nextSibling) { // if an item has been appended, we only need to update the last index and the length childNodes[childNodes.length++] = newChild; } else { // otherwise we need to reindex all items, // which can take a while when processing nodes with a lot of children var child = parent.firstChild; var i = 0; while (child) { childNodes[i++] = child; child = child.nextSibling; } childNodes.length = i; delete childNodes[childNodes.length]; } } } /** * Removes the connections between `parentNode` and `child` * and any existing `child.previousSibling` or `child.nextSibling`. * * @param {Node} parentNode * The parent node from which the child node is to be removed. * @param {Node} child * The child node to be removed from the parentNode. * @returns {Node} * Returns the child node that was removed. * @throws {DOMException} * With code: * - {@link DOMException.NOT_FOUND_ERR} If the parentNode is not the parent of the child node. * @private * @see https://github.com/xmldom/xmldom/issues/135 * @see https://github.com/xmldom/xmldom/issues/145 */ function _removeChild(parentNode, child) { if (parentNode !== child.parentNode) { throw new DOMException(DOMException.NOT_FOUND_ERR, "child's parent is not parent"); } var oldPreviousSibling = child.previousSibling; var oldNextSibling = child.nextSibling; if (oldPreviousSibling) { oldPreviousSibling.nextSibling = oldNextSibling; } else { parentNode.firstChild = oldNextSibling; } if (oldNextSibling) { oldNextSibling.previousSibling = oldPreviousSibling; } else { parentNode.lastChild = oldPreviousSibling; } _onUpdateChild(parentNode.ownerDocument, parentNode); child.parentNode = null; child.previousSibling = null; child.nextSibling = null; return child; } /** * Returns `true` if `node` can be a parent for insertion. * * @param {Node} node * @returns {boolean} */ function hasValidParentNodeType(node) { return ( node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE) ); } /** * Returns `true` if `node` can be inserted according to it's `nodeType`. * * @param {Node} node * @returns {boolean} */ function hasInsertableNodeType(node) { return ( node && (node.nodeType === Node.CDATA_SECTION_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.DOCUMENT_TYPE_NODE || node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE || node.nodeType === Node.TEXT_NODE) ); } /** * Returns true if `node` is a DOCTYPE node. * * @param {Node} node * @returns {boolean} */ function isDocTypeNode(node) { return node && node.nodeType === Node.DOCUMENT_TYPE_NODE; } /** * Returns true if the node is an element. * * @param {Node} node * @returns {boolean} */ function isElementNode(node) { return node && node.nodeType === Node.ELEMENT_NODE; } /** * Returns true if `node` is a text node. * * @param {Node} node * @returns {boolean} */ function isTextNode(node) { return node && node.nodeType === Node.TEXT_NODE; } /** * Check if en element node can be inserted before `child`, or at the end if child is falsy, * according to the presence and position of a doctype node on the same level. * * @param {Document} doc * The document node. * @param {Node} child * The node that would become the nextSibling if the element would be inserted. * @returns {boolean} * `true` if an element can be inserted before child. * @private */ function isElementInsertionPossible(doc, child) { var parentChildNodes = doc.childNodes || []; if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) { return false; } var docTypeNode = find(parentChildNodes, isDocTypeNode); return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); } /** * Check if en element node can be inserted before `child`, or at the end if child is falsy, * according to the presence and position of a doctype node on the same level. * * @param {Node} doc * The document node. * @param {Node} child * The node that would become the nextSibling if the element would be inserted. * @returns {boolean} * `true` if an element can be inserted before child. * @private */ function isElementReplacementPossible(doc, child) { var parentChildNodes = doc.childNodes || []; function hasElementChildThatIsNotChild(node) { return isElementNode(node) && node !== child; } if (find(parentChildNodes, hasElementChildThatIsNotChild)) { return false; } var docTypeNode = find(parentChildNodes, isDocTypeNode); return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); } /** * Asserts pre-insertion validity of a node into a parent before a child. * Throws errors for invalid node combinations that would result in an ill-formed DOM. * * @param {Node} parent * The parent node to insert `node` into. * @param {Node} node * The node to insert. * @param {Node | null} child * The node that should become the `nextSibling` of `node`. If null, no sibling is considered. * @throws {DOMException} * With code: * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `parent` is not a Document, * DocumentFragment, or Element node. * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `node` is a host-including inclusive * ancestor of `parent`. (Currently not implemented) * - {@link DOMException.NOT_FOUND_ERR} If `child` is non-null and its `parent` is not * `parent`. * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `node` is not a DocumentFragment, * DocumentType, Element, or CharacterData node. * - {@link DOMException.HIERARCHY_REQUEST_ERR} If either `node` is a Text node and `parent` is * a document, or if `node` is a doctype and `parent` is not a document. * @private * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity * @see https://dom.spec.whatwg.org/#concept-node-replace */ function assertPreInsertionValidity1to5(parent, node, child) { // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException. if (!hasValidParentNodeType(parent)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType); } // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException. // not implemented! // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException. if (child && child.parentNode !== parent) { throw new DOMException(DOMException.NOT_FOUND_ERR, 'child not in parent'); } if ( // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document, // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. (isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) ) { throw new DOMException( DOMException.HIERARCHY_REQUEST_ERR, 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType ); } } /** * Asserts pre-insertion validity of a node into a document before a child. * Throws errors for invalid node combinations that would result in an ill-formed DOM. * * @param {Document} parent * The parent node to insert `node` into. * @param {Node} node * The node to insert. * @param {Node | undefined} child * The node that should become the `nextSibling` of `node`. If undefined, no sibling is * considered. * @returns {Node} * @throws {DOMException} * With code: * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `node` is a DocumentFragment with more than * one element child or has a Text node child. * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `node` is a DocumentFragment with one * element child and either `parent` has an element child, `child` is a doctype, or `child` is * non-null and a doctype is following `child`. * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `node` is an Element and `parent` has an * element child, `child` is a doctype, or `child` is non-null and a doctype is following * `child`. * - {@link DOMException.HIERARCHY_REQUEST_ERR} If `node` is a DocumentType and `parent` has a * doctype child, `child` is non-null and an element is preceding `child`, or `child` is null * and `parent` has an element child. * @private * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity * @see https://dom.spec.whatwg.org/#concept-node-replace */ function assertPreInsertionValidityInDocument(parent, node, child) { var parentChildNodes = parent.childNodes || []; var nodeChildNodes = node.childNodes || []; // DocumentFragment if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { var nodeChildElements = nodeChildNodes.filter(isElementNode); // If node has more than one element child or has a Text node child. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); } // Otherwise, if `node` has one element child and either `parent` has an element child, // `child` is a doctype, or `child` is non-null and a doctype is following `child`. if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); } } // Element if (isElementNode(node)) { // `parent` has an element child, `child` is a doctype, // or `child` is non-null and a doctype is following `child`. if (!isElementInsertionPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); } } // DocumentType if (isDocTypeNode(node)) { // `parent` has a doctype child, if (find(parentChildNodes, isDocTypeNode)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); } var parentElementChild = find(parentChildNodes, isElementNode); // `child` is non-null and an element is preceding `child`, if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); } // or `child` is null and `parent` has an element child. if (!child && parentElementChild) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present'); } } } /** * @param {Document} parent * The parent node to insert `node` into. * @param {Node} node * The node to insert. * @param {Node | undefined} child * the node that should become the `nextSibling` of `node` * @returns {Node} * @throws {DOMException} * For several node combinations that would create a DOM that is not well-formed. * @throws {DOMException} * If `child` is provided but is not a child of `parent`. * @private * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity * @see https://dom.spec.whatwg.org/#concept-node-replace */ function assertPreReplacementValidityInDocument(parent, node, child) { var parentChildNodes = parent.childNodes || []; var nodeChildNodes = node.childNodes || []; // DocumentFragment if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { var nodeChildElements = nodeChildNodes.filter(isElementNode); // If `node` has more than one element child or has a Text node child. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); } // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`. if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); } } // Element if (isElementNode(node)) { // `parent` has an element child that is not `child` or a doctype is following `child`. if (!isElementReplacementPossible(parent, child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); } } // DocumentType if (isDocTypeNode(node)) { function hasDoctypeChildThatIsNotChild(node) { return isDocTypeNode(node) && node !== child; } // `parent` has a doctype child that is not `child`, if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); } var parentElementChild = find(parentChildNodes, isElementNode); // or an element is preceding `child`. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); } } } /** * Inserts a node into a parent node before a child node. * * @param {Node} parent * The parent node to insert the node into. * @param {Node} node * The node to insert into the parent. * @param {Node | null} child * The node that should become the next sibling of the node. * If null, the function inserts the node at the end of the children of the parent node. * @param {Function} [_inDocumentAssertion] * An optional function to check pre-insertion validity if parent is a document node. * Defaults to {@link assertPreInsertionValidityInDocument} * @returns {Node} * Returns the inserted node. * @throws {DOMException} * Throws a DOMException if inserting the node would result in a DOM tree that is not * well-formed. See {@link assertPreInsertionValidity1to5}, * {@link assertPreInsertionValidityInDocument}. * @throws {DOMException} * Throws a DOMException if child is provided but is not a child of the parent. See * {@link Node.removeChild} * @private * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity */ function _insertBefore(parent, node, child, _inDocumentAssertion) { // To ensure pre-insertion validity of a node into a parent before a child, run these steps: assertPreInsertionValidity1to5(parent, node, child); // If parent is a document, and any of the statements below, switched on the interface node implements, // are true, then throw a "HierarchyRequestError" DOMException. if (parent.nodeType === Node.DOCUMENT_NODE) { (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); } var cp = node.parentNode; if (cp) { cp.removeChild(node); //remove and update } if (node.nodeType === DOCUMENT_FRAGMENT_NODE) { var newFirst = node.firstChild; if (newFirst == null) { return node; } var newLast = node.lastChild; } else { newFirst = newLast = node; } var pre = child ? child.previousSibling : parent.lastChild; newFirst.previousSibling = pre; newLast.nextSibling = child; if (pre) { pre.nextSibling = newFirst; } else { parent.firstChild = newFirst; } if (child == null) { parent.lastChild = newLast; } else { child.previousSibling = newLast; } do { newFirst.parentNode = parent; } while (newFirst !== newLast && (newFirst = newFirst.nextSibling)); _onUpdateChild(parent.ownerDocument || parent, parent, node); if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { node.firstChild = node.lastChild = null; } return node; } Document.prototype = { /** * The implementation that created this document. * * @type DOMImplementation * @readonly */ implementation: null, nodeName: '#document', nodeType: DOCUMENT_NODE, /** * The DocumentType node of the document. * * @type DocumentType * @readonly */ doctype: null, documentElement: null, _inc: 1, insertBefore: function (newChild, refChild) { //raises if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) { var child = newChild.firstChild; while (child) { var next = child.nextSibling; this.insertBefore(child, refChild); child = next; } return newChild; } _insertBefore(this, newChild, refChild); newChild.ownerDocument = this; if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) { this.documentElement = newChild; } return newChild; }, removeChild: function (oldChild) { var removed = _removeChild(this, oldChild); if (removed === this.documentElement) { this.documentElement = null; } return removed; }, replaceChild: function (newChild, oldChild) { //raises _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); newChild.ownerDocument = this; if (oldChild) { this.removeChild(oldChild); } if (isElementNode(newChild)) { this.documentElement = newChild; } }, /** * Imports a node from another document into this document, creating a new copy owned by this * document. The source node and its subtree are not modified. * * @param {Node} importedNode * The node to import. * @param {boolean} deep * If true, the contents of the node are recursively imported. * If false, only the node itself (and its attributes, if it is an element) are imported. * @returns {Node} * Returns the newly created import of the node. * @see {@link importNode} * @see {@link https://dom.spec.whatwg.org/#dom-document-importnode} */ importNode: function (importedNode, deep) { return importNode(this, importedNode, deep); }, // Introduced in DOM Level 2: getElementById: function (id) { var rtv = null; _visitNode(this.documentElement, function (node) { if (node.nodeType == ELEMENT_NODE) { if (node.getAttribute('id') == id) { rtv = node; return true; } } }); return rtv; }, /** * Creates a new `Element` that is owned by this `Document`. * In HTML Documents `localName` is the lower cased `tagName`, * otherwise no transformation is being applied. * When `contentType` implies the HTML namespace, it will be set as `namespaceURI`. * * __This implementation differs from the specification:__ - The provided name is not checked * against the `Name` production, * so no related error will be thrown. * - There is no interface `HTMLElement`, it is always an `Element`. * - There is no support for a second argument to indicate using custom elements. * * @param {string} tagName * @returns {Element} * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement * @see https://dom.spec.whatwg.org/#dom-document-createelement * @see https://dom.spec.whatwg.org/#concept-create-element */ createElement: function (tagName) { var node = new Element(PDC); node.ownerDocument = this; if (this.type === 'html') { tagName = tagName.toLowerCase(); } if (hasDefaultHTMLNamespace(this.contentType)) { node.namespaceURI = NAMESPACE.HTML; } node.nodeName = tagName; node.tagName = tagName; node.localName = tagName; node.childNodes = new NodeList(); var attrs = (node.attributes = new NamedNodeMap()); attrs._ownerElement = node; return node; }, /** * @returns {DocumentFragment} */ createDocumentFragment: function () { var node = new DocumentFragment(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); return node; }, /** * @param {string} data * @returns {Text} */ createTextNode: function (data) { var node = new Text(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.appendData(data); return node; }, /** * @param {string} data * @returns {Comment} * @see https://dom.spec.whatwg.org/#dom-document-createcomment * @see https://www.w3.org/TR/xml/#NT-Comment XML 1.0 production [15] * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.3 * * Note: no validation is performed at creation time. When the resulting document is * serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the comment data contains `--` anywhere, ends with `-`, or contains characters * outside the XML Char production (W3C DOM Parsing §3.2.1.3). Without that option the * data is emitted verbatim. */ createComment: function (data) { var node = new Comment(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.appendData(data); return node; }, /** * Returns a new CDATASection node whose data is `data`. * * __This implementation differs from the specification:__ - calling this method on an HTML * document does not throw `NotSupportedError`. * * @param {string} data * @returns {CDATASection} * @throws {DOMException} * With code `INVALID_CHARACTER_ERR` if `data` contains `"]]>"`. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createCDATASection * @see https://dom.spec.whatwg.org/#dom-document-createcdatasection */ createCDATASection: function (data) { if (data.indexOf(']]>') !== -1) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'data contains "]]>"'); } var node = new CDATASection(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.appendData(data); return node; }, /** * Returns a ProcessingInstruction node whose target is target and data is data. * * __This behavior is slightly different from the in the specs__: * - it does not do any input validation on the arguments and doesn't throw * "InvalidCharacterError". * * Note: When the resulting document is serialized with `requireWellFormed: true`, the * serializer throws `InvalidStateError` if `.target` contains `:` or is an ASCII * case-insensitive match for `"xml"`, or if `.data` contains `?>` or characters outside the * XML Char production (W3C DOM Parsing §3.2.1.7). Without that option the data is emitted * verbatim. * * @param {string} target * @param {string} data * @returns {ProcessingInstruction} * @see https://developer.mozilla.org/docs/Web/API/Document/createProcessingInstruction * @see https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction * @see https://www.w3.org/TR/DOM-Parsing/#dfn-concept-serialize-xml §3.2.1.7 */ createProcessingInstruction: function (target, data) { var node = new ProcessingInstruction(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.nodeName = node.target = target; node.nodeValue = node.data = data; return node; }, /** * Creates an `Attr` node that is owned by this document. * In HTML Documents `localName` is the lower cased `name`, * otherwise no transformation is being applied. * * __This implementation differs from the specification:__ - The provided name is not checked * against the `Name` production, * so no related error will be thrown. * * @param {string} name * @returns {Attr} * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createAttribute * @see https://dom.spec.whatwg.org/#dom-document-createattribute */ createAttribute: function (name) { if (!g.QName_exact.test(name)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'invalid character in name "' + name + '"'); } if (this.type === 'html') { name = name.toLowerCase(); } return this._createAttribute(name); }, _createAttribute: function (name) { var node = new Attr(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.name = name; node.nodeName = name; node.localName = name; node.specified = true; return node; }, /** * Creates an EntityReference object. * The current implementation does not fill the `childNodes` with those of the corresponding * `Entity` * * @deprecated * In DOM Level 4. * @param {string} name * The name of the entity to reference. No namespace well-formedness checks are performed. * @returns {EntityReference} * @throws {DOMException} * With code `INVALID_CHARACTER_ERR` when `name` is not valid. * @throws {DOMException} * with code `NOT_SUPPORTED_ERR` when the document is of type `html` * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-392B75AE */ createEntityReference: function (name) { if (!g.Name.test(name)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, 'not a valid xml name "' + name + '"'); } if (this.type === 'html') { throw new DOMException('document is an html document', DOMExceptionName.NotSupportedError); } var node = new EntityReference(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.nodeName = name; return node; }, // Introduced in DOM Level 2: /** * @param {string} namespaceURI * @param {string} qualifiedName * @returns {Element} */ createElementNS: function (namespaceURI, qualifiedName) { var validated = validateAndExtract(namespaceURI, qualifiedName); var node = new Element(PDC); var attrs = (node.attributes = new NamedNodeMap()); node.childNodes = new NodeList(); node.ownerDocument = this; node.nodeName = qualifiedName; node.tagName = qualifiedName; node.namespaceURI = validated[0]; node.prefix = validated[1]; node.localName = validated[2]; attrs._ownerElement = node; return node; }, // Introduced in DOM Level 2: /** * @param {string} namespaceURI * @param {string} qualifiedName * @returns {Attr} */ createAttributeNS: function (namespaceURI, qualifiedName) { var validated = validateAndExtract(namespaceURI, qualifiedName); var node = new Attr(PDC); node.ownerDocument = this; node.childNodes = new NodeList(); node.nodeName = qualifiedName; node.name = qualifiedName; node.specified = true; node.namespaceURI = validated[0]; node.prefix = validated[1]; node.localName = validated[2]; return node; }, }; _extends(Document, Node); function Element(symbol) { checkSymbol(symbol); this._nsMap = Object.create(null); } Element.prototype = { nodeType: ELEMENT_NODE, /** * The attributes of this element. * * @type {NamedNodeMap | null} */ attributes: null, getQualifiedName: function () { return this.prefix ? this.prefix + ':' + this.localName : this.localName; }, _isInHTMLDocumentAndNamespace: function () { return this.ownerDocument.type === 'html' && this.namespaceURI === NAMESPACE.HTML; }, /** * Implementaton of Level2 Core function hasAttributes. * * @returns {boolean} * True if attribute list is not empty. * @see https://www.w3.org/TR/DOM-Level-2-Core/#core-ID-NodeHasAttrs */ hasAttributes: function () { return !!(this.attributes && this.attributes.length); }, hasAttribute: function (name) { return !!this.getAttributeNode(name); }, /** * Returns element’s first attribute whose qualified name is `name`, and `null` * if there is no such attribute. * * @param {string} name * @returns {string | null} */ getAttribute: function (name) { var attr = this.getAttributeNode(name); return attr ? attr.value : null; }, getAttributeNode: function (name) { if (this._isInHTMLDocumentAndNamespace()) { name = name.toLowerCase(); } return this.attributes.getNamedItem(name); }, /** * Sets the value of element’s first attribute whose qualified name is qualifiedName to value. * * @param {string} name * @param {string} value */ setAttribute: function (name, value) { if (this._isInHTMLDocumentAndNamespace()) { name = name.toLowerCase(); } var attr = this.getAttributeNode(name); if (attr) { attr.value = attr.nodeValue = '' + value; } else { attr = this.ownerDocument._createAttribute(name); attr.value = attr.nodeValue = '' + value; this.setAttributeNode(attr); } }, removeAttribute: function (name) { var attr = this.getAttributeNode(name); attr && this.removeAttributeNode(attr); }, setAttributeNode: function (newAttr) { return this.attributes.setNamedItem(newAttr); }, setAttributeNodeNS: function (newAttr) { return this.attributes.setNamedItemNS(newAttr); }, removeAttributeNode: function (oldAttr) { //console.log(this == oldAttr.ownerElement) return this.attributes.removeNamedItem(oldAttr.nodeName); }, //get real attribute name,and remove it by removeAttributeNode removeAttributeNS: function (namespaceURI, localName) { var old = this.getAttributeNodeNS(namespaceURI, localName); old && this.removeAttributeNode(old); }, hasAttributeNS: function (namespaceURI, localName) { return this.getAttributeNodeNS(namespaceURI, localName) != null; }, /** * Returns element’s attribute whose namespace is `namespaceURI` and local name is * `localName`, * or `null` if there is no such attribute. * * @param {string} namespaceURI * @param {string} localName * @returns {string | null} */ getAttributeNS: function (namespaceURI, localName) { var attr = this.getAttributeNodeNS(namespaceURI, localName); return attr ? attr.value : null; }, /** * Sets the value of element’s attribute whose namespace is `namespaceURI` and local name is * `localName` to value. * * @param {string} namespaceURI * @param {string} qualifiedName * @param {string} value * @see https://dom.spec.whatwg.org/#dom-element-setattributens */ setAttributeNS: function (namespaceURI, qualifiedName, value) { var validated = validateAndExtract(namespaceURI, qualifiedName); var localName = validated[2]; var attr = this.getAttributeNodeNS(namespaceURI, localName); if (attr) { attr.value = attr.nodeValue = '' + value; } else { attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); attr.value = attr.nodeValue = '' + value; this.setAttributeNode(attr); } }, getAttributeNodeNS: function (namespaceURI, localName) { return this.attributes.getNamedItemNS(namespaceURI, localName); }, /** * Returns a LiveNodeList of all child elements which have **all** of the given class name(s). * * Returns an empty list if `classNames` is an empty string or only contains HTML white space * characters. * * Warning: This returns a live LiveNodeList. * Changes in the DOM will reflect in the array as the changes occur. * If an element selected by this array no longer qualifies for the selector, * it will automatically be removed. Be aware of this for iteration purposes. * * @param {string} classNames * Is a string representing the class name(s) to match; multiple class names are separated by * (ASCII-)whitespace. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname */ getElementsByClassName: function (classNames) { var classNamesSet = toOrderedSet(classNames); return new LiveNodeList(this, function (base) { var ls = []; if (classNamesSet.length > 0) { _visitNode(base, function (node) { if (node !== base && node.nodeType === ELEMENT_NODE) { var nodeClassNames = node.getAttribute('class'); // can be null if the attribute does not exist if (nodeClassNames) { // before splitting and iterating just compare them for the most common case var matches = classNames === nodeClassNames; if (!matches) { var nodeClassNamesSet = toOrderedSet(nodeClassNames); matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)); } if (matches) { ls.push(node); } } } }); } return ls; }); }, /** * Returns a LiveNodeList of elements with the given qualifiedName. * Searching for all descendants can be done by passing `*` as `qualifiedName`. * * All descendants of the specified element are searched, but not the element itself. * The returned list is live, which means it updates itself with the DOM tree automatically. * Therefore, there is no need to call `Element.getElementsByTagName()` * with the same element and arguments repeatedly if the DOM changes in between calls. * * When called on an HTML element in an HTML document, * `getElementsByTagName` lower-cases the argument before searching for it. * This is undesirable when trying to match camel-cased SVG elements (such as * ``) in an HTML document. * Instead, use `Element.getElementsByTagNameNS()`, * which preserves the capitalization of the tag name. * * `Element.getElementsByTagName` is similar to `Document.getElementsByTagName()`, * except that it only searches for elements that are descendants of the specified element. * * @param {string} qualifiedName * @returns {LiveNodeList} * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName * @see https://dom.spec.whatwg.org/#concept-getelementsbytagname */ getElementsByTagName: function (qualifiedName) { var isHTMLDocument = (this.nodeType === DOCUMENT_NODE ? this : this.ownerDocument).type === 'html'; var lowerQualifiedName = qualifiedName.toLowerCase(); return new LiveNodeList(this, function (base) { var ls = []; _visitNode(base, function (node) { if (node === base || node.nodeType !== ELEMENT_NODE) { return; } if (qualifiedName === '*') { ls.push(node); } else { var nodeQualifiedName = node.getQualifiedName(); var matchingQName = isHTMLDocument && node.namespaceURI === NAMESPACE.HTML ? lowerQualifiedName : qualifiedName; if (nodeQualifiedName === matchingQName) { ls.push(node); } } }); return ls; }); }, getElementsByTagNameNS: function (namespaceURI, localName) { return new LiveNodeList(this, function (base) { var ls = []; _visitNode(base, function (node) { if ( node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName) ) { ls.push(node); } }); return ls; }); }, }; Document.prototype.getElementsByClassName = Element.prototype.getElementsByClassName; Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; _extends(Element, Node); function Attr(symbol) { checkSymbol(symbol); this.namespaceURI = null; this.prefix = null; this.ownerElement = null; } Attr.prototype.nodeType = ATTRIBUTE_NODE; _extends(Attr, Node); function CharacterData(symbol) { checkSymbol(symbol); } CharacterData.prototype = { data: '', substringData: function (offset, count) { return this.data.substring(offset, offset + count); }, appendData: function (text) { text = this.data + text; this.nodeValue = this.data = text; this.length = text.length; }, insertData: function (offset, text) { this.replaceData(offset, 0, text); }, deleteData: function (offset, count) { this.replaceData(offset, count, ''); }, replaceData: function (offset, count, text) { var start = this.data.substring(0, offset); var end = this.data.substring(offset + count); text = start + text + end; this.nodeValue = this.data = text; this.length = text.length; }, }; _extends(CharacterData, Node); function Text(symbol) { checkSymbol(symbol); } Text.prototype = { nodeName: '#text', nodeType: TEXT_NODE, splitText: function (offset) { var text = this.data; var newText = text.substring(offset); text = text.substring(0, offset); this.data = this.nodeValue = text; this.length = text.length; var newNode = this.ownerDocument.createTextNode(newText); if (this.parentNode) { this.parentNode.insertBefore(newNode, this.nextSibling); } return newNode; }, }; _extends(Text, CharacterData); function Comment(symbol) { checkSymbol(symbol); } Comment.prototype = { nodeName: '#comment', nodeType: COMMENT_NODE, }; _extends(Comment, CharacterData); function CDATASection(symbol) { checkSymbol(symbol); } CDATASection.prototype = { nodeName: '#cdata-section', nodeType: CDATA_SECTION_NODE, }; _extends(CDATASection, Text); /** * @class DocumentType * @augments Node * @property {string} publicId * The external subset public identifier, stored verbatim (including surrounding quotes). * Declared `readonly` by the WHATWG DOM spec; xmldom does not enforce this constraint — * direct property writes succeed and the written value is serialized verbatim. * When serialized with `requireWellFormed: true`, the serializer validates the value against * the XML `PubidLiteral` production and throws `InvalidStateError` if it does not match. * @property {string} systemId * The external subset system identifier, stored verbatim (including surrounding quotes). * Declared `readonly` by the WHATWG DOM spec; xmldom does not enforce this constraint — * direct property writes succeed and the written value is serialized verbatim. * When serialized with `requireWellFormed: true`, the serializer validates the value against * the XML `SystemLiteral` production and throws `InvalidStateError` if it does not match. * @property {string} internalSubset * The internal subset string (the raw content between `[` and `]`), or an empty string. * Declared `readonly` by the WHATWG DOM spec; xmldom does not enforce this constraint — * direct property writes succeed and the written value is serialized verbatim. * When serialized with `requireWellFormed: true`, the serializer throws `InvalidStateError` * if the value contains `"]>"`. * @see https://developer.mozilla.org/en-US/docs/Web/API/DocumentType MDN * @see https://dom.spec.whatwg.org/#interface-documenttype WHATWG DOM * @prettierignore */ function DocumentType(symbol) { checkSymbol(symbol); } DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; _extends(DocumentType, Node); function Notation(symbol) { checkSymbol(symbol); } Notation.prototype.nodeType = NOTATION_NODE; _extends(Notation, Node); function Entity(symbol) { checkSymbol(symbol); } Entity.prototype.nodeType = ENTITY_NODE; _extends(Entity, Node); function EntityReference(symbol) { checkSymbol(symbol); } EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; _extends(EntityReference, Node); function DocumentFragment(symbol) { checkSymbol(symbol); } DocumentFragment.prototype.nodeName = '#document-fragment'; DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; _extends(DocumentFragment, Node); function ProcessingInstruction(symbol) { checkSymbol(symbol); } ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; _extends(ProcessingInstruction, CharacterData); function XMLSerializer() {} /** * Returns the result of serializing `node` to XML. * * When `options.requireWellFormed` is `true`, the serializer throws `InvalidStateError` for * content that would produce ill-formed XML (e.g. CDATASection data containing `"]]>"`, Text * data containing characters outside the XML Char production, or a Document with no * `documentElement`). * * When `options.splitCDATASections` is `false`, CDATASection data is emitted verbatim even * when it contains `"]]>"`. When `true` (the default), `"]]>"` sequences are split across * concatenated CDATA sections — this behavior is **deprecated** and will be removed in the * next breaking release. Callers should migrate to `{ requireWellFormed: true }`, which throws * `InvalidStateError` instead of transforming. * * __This implementation differs from the specification:__ - CDATASection serialization is not * specified by W3C DOM Parsing or WHATWG DOM Parsing (see * {@link https://github.com/w3c/DOM-Parsing/issues/38 w3c/DOM-Parsing#38}). * When `splitCDATASections` is `true` (the default), `"]]>"` sequences in CDATASection data * are split across concatenated CDATA sections — this mechanism is derived from DOM Level 3 * Core and is **deprecated**. The split mechanics will be removed in the next breaking * release. Callers that rely on this behavior should migrate to `{ requireWellFormed: true }`. * - W3C DOM Parsing §3.2.1.1 requires well-formedness checks on Element `localName`s, * prefixes, * and attribute serialization (duplicate attributes, namespace declarations, attribute value * characters) when `requireWellFormed` is `true`. These checks are **not implemented** in this * release — see the tracking issue filed against the next breaking milestone. * * @param {Node} node * @param {Object | function} [options] * Options object, or a legacy nodeFilter function (backward compatible). * @param {boolean} [options.requireWellFormed=false] * When `true`, throws `InvalidStateError` for content that would produce ill-formed XML. * @param {boolean} [options.splitCDATASections=true] * When `true` (default), splits `"]]>"` sequences in CDATASection data across concatenated * CDATA sections. **Deprecated** — will be removed in the next breaking release. * @param {function} [options.nodeFilter] * A filter function applied to each node before serialization. * @returns {string} * @throws {DOMException} * With name `InvalidStateError` when `requireWellFormed` is `true` and any of the following * conditions hold: * - CDATASection data contains `"]]>"` * - Text data contains characters outside the XML Char production * - a Comment node's data contains `--` anywhere or ends with `-` * - a ProcessingInstruction's target contains `:` or is an ASCII case-insensitive match for * `"xml"`, or its data contains `?>` or characters outside the XML Char production * - a DocumentType's `publicId` is non-empty and does not match the XML `PubidLiteral` * production (W3C DOM Parsing §3.2.1.3; XML 1.0 production [12]) * - a DocumentType's `systemId` is non-empty and does not match the XML `SystemLiteral` * production (W3C DOM Parsing §3.2.1.3; XML 1.0 production [11]) * - a DocumentType's `internalSubset` contains `"]>"` * - the Document has no `documentElement` * @see https://developer.mozilla.org/docs/Web/API/XMLSerializer/serializeToString * @see https://html.spec.whatwg.org/#dom-xmlserializer-serializetostring * @see https://github.com/w3c/DOM-Parsing/issues/84 * @prettierignore */ XMLSerializer.prototype.serializeToString = function (node, options) { return nodeSerializeToString.call(node, options); }; Node.prototype.toString = nodeSerializeToString; function nodeSerializeToString(options) { // Normalize the user-supplied options into a single internal opts object so that the // internal serializer always works with a consistent shape rather than positional flags. var opts; if (typeof options === 'function') { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: options }; } else if (options != null) { opts = { requireWellFormed: !!options.requireWellFormed, splitCDATASections: options.splitCDATASections !== false, nodeFilter: options.nodeFilter || null, }; } else { opts = { requireWellFormed: false, splitCDATASections: true, nodeFilter: null }; } var buf = []; var refNode = (this.nodeType === DOCUMENT_NODE && this.documentElement) || this; var prefix = refNode.prefix; var uri = refNode.namespaceURI; if (uri && prefix == null) { var prefix = refNode.lookupPrefix(uri); if (prefix == null) { var visibleNamespaces = [ { namespace: uri, prefix: null }, //{namespace:uri,prefix:''} ]; } } serializeToString(this, buf, visibleNamespaces, opts); return buf.join(''); } function needNamespaceDefine(node, isHTML, visibleNamespaces) { var prefix = node.prefix || ''; var uri = node.namespaceURI; // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) , // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl : // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using) // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared : // > [...] Furthermore, the attribute value [...] must not be an empty string. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document. if (!uri) { return false; } if ((prefix === 'xml' && uri === NAMESPACE.XML) || uri === NAMESPACE.XMLNS) { return false; } var i = visibleNamespaces.length; while (i--) { var ns = visibleNamespaces[i]; // get namespace prefix if (ns.prefix === prefix) { return ns.namespace !== uri; } } return true; } /** * Literal whitespace other than space that appear in attribute values are serialized as * their entity references, so they will be preserved. * (In contrast to whitespace literals in the input which are normalized to spaces). * * Well-formed constraint: No < in Attribute Values: * > The replacement text of any entity referred to directly or indirectly * > in an attribute value must not contain a <. * * @see https://www.w3.org/TR/xml11/#CleanAttrVals * @see https://www.w3.org/TR/xml11/#NT-AttValue * @see https://www.w3.org/TR/xml11/#AVNormalize * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes * @prettierignore */ function addSerializedAttribute(buf, qualifiedName, value) { buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"'); } function serializeToString(node, buf, visibleNamespaces, opts) { if (!visibleNamespaces) { visibleNamespaces = []; } var nodeFilter = opts.nodeFilter; var requireWellFormed = opts.requireWellFormed; var splitCDATASections = opts.splitCDATASections; var doc = node.nodeType === DOCUMENT_NODE ? node : node.ownerDocument; var isHTML = doc.type === 'html'; walkDOM( node, { ns: visibleNamespaces }, { enter: function (n, ctx) { var namespaces = ctx.ns; if (nodeFilter) { n = nodeFilter(n); if (n) { if (typeof n == 'string') { buf.push(n); return null; } } else { return null; } } switch (n.nodeType) { case ELEMENT_NODE: var attrs = n.attributes; var len = attrs.length; var nodeName = n.tagName; var prefixedNodeName = nodeName; if (!isHTML && !n.prefix && n.namespaceURI) { var defaultNS; // lookup current default ns from `xmlns` attribute for (var ai = 0; ai < attrs.length; ai++) { if (attrs.item(ai).name === 'xmlns') { defaultNS = attrs.item(ai).value; break; } } if (!defaultNS) { // lookup current default ns in visibleNamespaces for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) { var nsEntry = namespaces[nsi]; if (nsEntry.prefix === '' && nsEntry.namespace === n.namespaceURI) { defaultNS = nsEntry.namespace; break; } } } if (defaultNS !== n.namespaceURI) { for (var nsi = namespaces.length - 1; nsi >= 0; nsi--) { var nsEntry = namespaces[nsi]; if (nsEntry.namespace === n.namespaceURI) { if (nsEntry.prefix) { prefixedNodeName = nsEntry.prefix + ':' + nodeName; } break; } } } } buf.push('<', prefixedNodeName); // Build a fresh namespace snapshot for this element's children. // The slice prevents sibling elements from inheriting each other's declarations. var childNamespaces = namespaces.slice(); for (var i = 0; i < len; i++) { // add namespaces for attributes var attr = attrs.item(i); if (attr.prefix == 'xmlns') { childNamespaces.push({ prefix: attr.localName, namespace: attr.value, }); } else if (attr.nodeName == 'xmlns') { childNamespaces.push({ prefix: '', namespace: attr.value }); } } for (var i = 0; i < len; i++) { var attr = attrs.item(i); if (needNamespaceDefine(attr, isHTML, childNamespaces)) { var attrPrefix = attr.prefix || ''; var uri = attr.namespaceURI; addSerializedAttribute(buf, attrPrefix ? 'xmlns:' + attrPrefix : 'xmlns', uri); childNamespaces.push({ prefix: attrPrefix, namespace: uri }); } // Apply nodeFilter and serialize the attribute. var filteredAttr = nodeFilter ? nodeFilter(attr) : attr; if (filteredAttr) { if (typeof filteredAttr === 'string') { buf.push(filteredAttr); } else { addSerializedAttribute(buf, filteredAttr.name, filteredAttr.value); } } } // add namespace for current node if (nodeName === prefixedNodeName && needNamespaceDefine(n, isHTML, childNamespaces)) { var nodePrefix = n.prefix || ''; var uri = n.namespaceURI; addSerializedAttribute(buf, nodePrefix ? 'xmlns:' + nodePrefix : 'xmlns', uri); childNamespaces.push({ prefix: nodePrefix, namespace: uri }); } // in XML elements can be closed when they have no children var canCloseTag = !n.firstChild; if (canCloseTag && (isHTML || n.namespaceURI === NAMESPACE.HTML)) { // in HTML (doc or ns) only void elements can be closed right away canCloseTag = isHTMLVoidElement(nodeName); } if (canCloseTag) { buf.push('/>'); // Self-closing: no children and no closing tag needed from exit. return null; } buf.push('>'); // HTML raw text elements: serialize children as raw data without further descent. if (isHTML && isHTMLRawTextElement(nodeName)) { var child = n.firstChild; while (child) { if (child.data) { buf.push(child.data); } else { serializeToString(child, buf, childNamespaces.slice(), opts); } child = child.nextSibling; } buf.push(''); // Children handled manually above; prevent walkDOM from also traversing them. return null; } // Return child context so walkDOM descends; exit will emit the closing tag. return { ns: childNamespaces, tag: prefixedNodeName }; case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: if (requireWellFormed && n.nodeType === DOCUMENT_NODE && n.documentElement == null) { throw new DOMException('The Document has no documentElement', DOMExceptionName.InvalidStateError); } // Pass namespaces through; each child element will slice independently. return { ns: namespaces }; case ATTRIBUTE_NODE: addSerializedAttribute(buf, n.name, n.value); return null; case TEXT_NODE: /* * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, * except when used as markup delimiters, or within a comment, a processing instruction, * or a CDATA section. * If they are needed elsewhere, they must be escaped using either numeric character * references or the strings `&` and `<` respectively. * The right angle bracket (>) may be represented using the string " > ", * and must, for compatibility, be escaped using either `>`, * or a character reference when it appears in the string `]]>` in content, * when that string is not marking the end of a CDATA section. * * In the content of elements, character data is any string of characters which does not * contain the start-delimiter of any markup and does not include the CDATA-section-close * delimiter, `]]>`. * * @see https://www.w3.org/TR/xml/#NT-CharData * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node */ if (requireWellFormed && g.InvalidChar.test(n.data)) { throw new DOMException( 'The Text node data contains characters outside the XML Char production', DOMExceptionName.InvalidStateError ); } buf.push(n.data.replace(/[<&>]/g, _xmlEncoder)); return null; case CDATA_SECTION_NODE: if (requireWellFormed && n.data.indexOf(']]>') !== -1) { throw new DOMException('The CDATASection data contains "]]>"', DOMExceptionName.InvalidStateError); } if (splitCDATASections) { buf.push(g.CDATA_START, n.data.replace(/]]>/g, ']]]]>'), g.CDATA_END); } else { buf.push(g.CDATA_START, n.data, g.CDATA_END); } return null; case COMMENT_NODE: if (requireWellFormed) { if (g.InvalidChar.test(n.data)) { throw new DOMException( 'The comment node data contains characters outside the XML Char production', DOMExceptionName.InvalidStateError ); } if (n.data.indexOf('--') !== -1 || n.data[n.data.length - 1] === '-') { throw new DOMException( 'The comment node data contains "--" or ends with "-"', DOMExceptionName.InvalidStateError ); } } buf.push(g.COMMENT_START, n.data, g.COMMENT_END); return null; case DOCUMENT_TYPE_NODE: var pubid = n.publicId; var sysid = n.systemId; if (requireWellFormed) { if (pubid && !g.PubidLiteral_match.test(pubid)) { throw new DOMException('DocumentType publicId is not a valid PubidLiteral', DOMExceptionName.InvalidStateError); } if (sysid && sysid !== '.' && !g.SystemLiteral_match.test(sysid)) { throw new DOMException('DocumentType systemId is not a valid SystemLiteral', DOMExceptionName.InvalidStateError); } if (n.internalSubset && n.internalSubset.indexOf(']>') !== -1) { throw new DOMException('DocumentType internalSubset contains "]>"', DOMExceptionName.InvalidStateError); } } buf.push(g.DOCTYPE_DECL_START, ' ', n.name); if (pubid) { buf.push(' ', g.PUBLIC, ' ', pubid); if (sysid && sysid !== '.') { buf.push(' ', sysid); } } else if (sysid && sysid !== '.') { buf.push(' ', g.SYSTEM, ' ', sysid); } if (n.internalSubset) { buf.push(' [', n.internalSubset, ']'); } buf.push('>'); return null; case PROCESSING_INSTRUCTION_NODE: if (requireWellFormed) { if (n.target.indexOf(':') !== -1 || n.target.toLowerCase() === 'xml') { throw new DOMException('The ProcessingInstruction target is not well-formed', DOMExceptionName.InvalidStateError); } if (g.InvalidChar.test(n.data)) { throw new DOMException( 'The ProcessingInstruction data contains characters outside the XML Char production', DOMExceptionName.InvalidStateError ); } if (n.data.indexOf('?>') !== -1) { throw new DOMException('The ProcessingInstruction data contains "?>"', DOMExceptionName.InvalidStateError); } } buf.push(''); return null; case ENTITY_REFERENCE_NODE: buf.push('&', n.nodeName, ';'); return null; //case ENTITY_NODE: //case NOTATION_NODE: default: buf.push('??', n.nodeName); return null; } }, exit: function (n, childCtx) { // Emit the closing tag for elements that were opened (not self-closed, not raw text). if (childCtx && childCtx.tag) { buf.push(''); } }, } ); } /** * Imports a node from a different document into `doc`, creating a new copy. * Delegates to {@link walkDOM} for traversal. Each node in the subtree is shallow-cloned, * stamped with `doc` as its `ownerDocument`, and detached (`parentNode` set to `null`). * Children are imported recursively when `deep` is `true`; for {@link Attr} nodes `deep` is * always forced to `true` * because an attribute's value lives in a child text node. * * @param {Document} doc * The document that will own the imported node. * @param {Node} node * The node to import. * @param {boolean} deep * If `true`, descendants are imported recursively. * @returns {Node} * The newly imported node, now owned by `doc`. */ function importNode(doc, node, deep) { var destRoot; walkDOM(node, null, { enter: function (srcNode, destParent) { // Shallow-clone the node and stamp it into the target document. var destNode = srcNode.cloneNode(false); destNode.ownerDocument = doc; destNode.parentNode = null; // capture as the root of the imported subtree or attach to parent. if (destParent === null) { destRoot = destNode; } else { destParent.appendChild(destNode); } // ATTRIBUTE_NODE must always be imported deeply: its value lives in a child text node. var shouldDeep = srcNode.nodeType === ATTRIBUTE_NODE || deep; return shouldDeep ? destNode : null; }, }); return destRoot; } /** * Creates a copy of a node from an existing one. * * @param {Document} doc * The Document object representing the document that the new node will belong to. * @param {Node} node * The node to clone. * @param {boolean} deep * If true, the contents of the node are recursively copied. * If false, only the node itself (and its attributes, if it is an element) are copied. * @returns {Node} * Returns the newly created copy of the node. * @throws {DOMException} * May throw a DOMException if operations within setAttributeNode or appendChild (which are * potentially invoked in this function) do not meet their specific constraints. */ function cloneNode(doc, node, deep) { var destRoot; walkDOM(node, null, { enter: function (srcNode, destParent) { // 1. Create a blank node of the same type and copy all scalar own properties. var destNode = new srcNode.constructor(PDC); for (var n in srcNode) { if (hasOwn(srcNode, n)) { var v = srcNode[n]; if (typeof v != 'object') { if (v != destNode[n]) { destNode[n] = v; } } } } if (srcNode.childNodes) { destNode.childNodes = new NodeList(); } destNode.ownerDocument = doc; // 2. Handle node-type-specific setup. // Attributes are not DOM children, so they are cloned inline here // rather than by walkDOM descent. // ATTRIBUTE_NODE forces deep=true so its own children are walked. var shouldDeep = deep; switch (destNode.nodeType) { case ELEMENT_NODE: var attrs = srcNode.attributes; var attrs2 = (destNode.attributes = new NamedNodeMap()); var len = attrs.length; attrs2._ownerElement = destNode; for (var i = 0; i < len; i++) { destNode.setAttributeNode(cloneNode(doc, attrs.item(i), true)); } break; case ATTRIBUTE_NODE: shouldDeep = true; } // 3. Attach to parent, or capture as the root of the cloned subtree. if (destParent !== null) { destParent.appendChild(destNode); } else { destRoot = destNode; } // 4. Return destNode as the context for children (causes walkDOM to descend), // or null to skip children (shallow clone). return shouldDeep ? destNode : null; }, }); return destRoot; } function __set__(object, key, value) { object[key] = value; } // Returns a new array of direct Element children. // Passed to LiveNodeList to implement ParentNode.children. // https://dom.spec.whatwg.org/#dom-parentnode-children function childrenRefresh(node) { var ls = []; var child = node.firstChild; while (child) { if (child.nodeType === ELEMENT_NODE) { ls.push(child); } child = child.nextSibling; } return ls; } //do dynamic try { if (Object.defineProperty) { Object.defineProperty(LiveNodeList.prototype, 'length', { get: function () { _updateLiveList(this); return this.$$length; }, }); /** * The text content of this node and its descendants. * * For {@link Element} and {@link DocumentFragment} nodes, returns the concatenation of the * `nodeValue` of every descendant text node, excluding processing instruction and comment * nodes. For all other node types, returns `nodeValue`. * * Setting `textContent` on an element or document fragment replaces all child nodes with a * single text node; on other nodes it sets `data`, `value`, and `nodeValue` directly. * * @type {string | null} * @see {@link https://dom.spec.whatwg.org/#dom-node-textcontent} */ Object.defineProperty(Node.prototype, 'textContent', { get: function () { if (this.nodeType === ELEMENT_NODE || this.nodeType === DOCUMENT_FRAGMENT_NODE) { var buf = []; walkDOM(this, null, { enter: function (n) { if (n.nodeType === ELEMENT_NODE || n.nodeType === DOCUMENT_FRAGMENT_NODE) { return true; // enter children } if (n.nodeType === PROCESSING_INSTRUCTION_NODE || n.nodeType === COMMENT_NODE) { return null; // excluded from text content } buf.push(n.nodeValue); }, }); return buf.join(''); } return this.nodeValue; }, set: function (data) { switch (this.nodeType) { case ELEMENT_NODE: case DOCUMENT_FRAGMENT_NODE: while (this.firstChild) { this.removeChild(this.firstChild); } if (data || String(data)) { this.appendChild(this.ownerDocument.createTextNode(data)); } break; default: this.data = data; this.value = data; this.nodeValue = data; } }, }); Object.defineProperty(Element.prototype, 'children', { get: function () { return new LiveNodeList(this, childrenRefresh); }, }); Object.defineProperty(Document.prototype, 'children', { get: function () { return new LiveNodeList(this, childrenRefresh); }, }); Object.defineProperty(DocumentFragment.prototype, 'children', { get: function () { return new LiveNodeList(this, childrenRefresh); }, }); __set__ = function (object, key, value) { //console.log(value) object['$$' + key] = value; }; } } catch (e) { //ie8 } exports._updateLiveList = _updateLiveList; exports.Attr = Attr; exports.CDATASection = CDATASection; exports.CharacterData = CharacterData; exports.Comment = Comment; exports.Document = Document; exports.DocumentFragment = DocumentFragment; exports.DocumentType = DocumentType; exports.DOMImplementation = DOMImplementation; exports.Element = Element; exports.Entity = Entity; exports.EntityReference = EntityReference; exports.LiveNodeList = LiveNodeList; exports.NamedNodeMap = NamedNodeMap; exports.Node = Node; exports.NodeList = NodeList; exports.Notation = Notation; exports.Text = Text; exports.ProcessingInstruction = ProcessingInstruction; exports.walkDOM = walkDOM; exports.XMLSerializer = XMLSerializer; /***/ }), /***/ 4124: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var freeze = (__nccwpck_require__(7855).freeze); /** * The entities that are predefined in every XML document. * * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1 * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0 * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML * Wikipedia */ exports.XML_ENTITIES = freeze({ amp: '&', apos: "'", gt: '>', lt: '<', quot: '"', }); /** * A map of all entities that are detected in an HTML document. * They contain all entries from `XML_ENTITIES`. * * @see {@link XML_ENTITIES} * @see {@link DOMParser.parseFromString} * @see {@link DOMImplementation.prototype.createHTMLDocument} * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) * Spec * @see https://html.spec.whatwg.org/entities.json JSON * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML * Wikipedia (HTML) * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML * Wikpedia (XHTML) */ exports.HTML_ENTITIES = freeze({ Aacute: '\u00C1', aacute: '\u00E1', Abreve: '\u0102', abreve: '\u0103', ac: '\u223E', acd: '\u223F', acE: '\u223E\u0333', Acirc: '\u00C2', acirc: '\u00E2', acute: '\u00B4', Acy: '\u0410', acy: '\u0430', AElig: '\u00C6', aelig: '\u00E6', af: '\u2061', Afr: '\uD835\uDD04', afr: '\uD835\uDD1E', Agrave: '\u00C0', agrave: '\u00E0', alefsym: '\u2135', aleph: '\u2135', Alpha: '\u0391', alpha: '\u03B1', Amacr: '\u0100', amacr: '\u0101', amalg: '\u2A3F', AMP: '\u0026', amp: '\u0026', And: '\u2A53', and: '\u2227', andand: '\u2A55', andd: '\u2A5C', andslope: '\u2A58', andv: '\u2A5A', ang: '\u2220', ange: '\u29A4', angle: '\u2220', angmsd: '\u2221', angmsdaa: '\u29A8', angmsdab: '\u29A9', angmsdac: '\u29AA', angmsdad: '\u29AB', angmsdae: '\u29AC', angmsdaf: '\u29AD', angmsdag: '\u29AE', angmsdah: '\u29AF', angrt: '\u221F', angrtvb: '\u22BE', angrtvbd: '\u299D', angsph: '\u2222', angst: '\u00C5', angzarr: '\u237C', Aogon: '\u0104', aogon: '\u0105', Aopf: '\uD835\uDD38', aopf: '\uD835\uDD52', ap: '\u2248', apacir: '\u2A6F', apE: '\u2A70', ape: '\u224A', apid: '\u224B', apos: '\u0027', ApplyFunction: '\u2061', approx: '\u2248', approxeq: '\u224A', Aring: '\u00C5', aring: '\u00E5', Ascr: '\uD835\uDC9C', ascr: '\uD835\uDCB6', Assign: '\u2254', ast: '\u002A', asymp: '\u2248', asympeq: '\u224D', Atilde: '\u00C3', atilde: '\u00E3', Auml: '\u00C4', auml: '\u00E4', awconint: '\u2233', awint: '\u2A11', backcong: '\u224C', backepsilon: '\u03F6', backprime: '\u2035', backsim: '\u223D', backsimeq: '\u22CD', Backslash: '\u2216', Barv: '\u2AE7', barvee: '\u22BD', Barwed: '\u2306', barwed: '\u2305', barwedge: '\u2305', bbrk: '\u23B5', bbrktbrk: '\u23B6', bcong: '\u224C', Bcy: '\u0411', bcy: '\u0431', bdquo: '\u201E', becaus: '\u2235', Because: '\u2235', because: '\u2235', bemptyv: '\u29B0', bepsi: '\u03F6', bernou: '\u212C', Bernoullis: '\u212C', Beta: '\u0392', beta: '\u03B2', beth: '\u2136', between: '\u226C', Bfr: '\uD835\uDD05', bfr: '\uD835\uDD1F', bigcap: '\u22C2', bigcirc: '\u25EF', bigcup: '\u22C3', bigodot: '\u2A00', bigoplus: '\u2A01', bigotimes: '\u2A02', bigsqcup: '\u2A06', bigstar: '\u2605', bigtriangledown: '\u25BD', bigtriangleup: '\u25B3', biguplus: '\u2A04', bigvee: '\u22C1', bigwedge: '\u22C0', bkarow: '\u290D', blacklozenge: '\u29EB', blacksquare: '\u25AA', blacktriangle: '\u25B4', blacktriangledown: '\u25BE', blacktriangleleft: '\u25C2', blacktriangleright: '\u25B8', blank: '\u2423', blk12: '\u2592', blk14: '\u2591', blk34: '\u2593', block: '\u2588', bne: '\u003D\u20E5', bnequiv: '\u2261\u20E5', bNot: '\u2AED', bnot: '\u2310', Bopf: '\uD835\uDD39', bopf: '\uD835\uDD53', bot: '\u22A5', bottom: '\u22A5', bowtie: '\u22C8', boxbox: '\u29C9', boxDL: '\u2557', boxDl: '\u2556', boxdL: '\u2555', boxdl: '\u2510', boxDR: '\u2554', boxDr: '\u2553', boxdR: '\u2552', boxdr: '\u250C', boxH: '\u2550', boxh: '\u2500', boxHD: '\u2566', boxHd: '\u2564', boxhD: '\u2565', boxhd: '\u252C', boxHU: '\u2569', boxHu: '\u2567', boxhU: '\u2568', boxhu: '\u2534', boxminus: '\u229F', boxplus: '\u229E', boxtimes: '\u22A0', boxUL: '\u255D', boxUl: '\u255C', boxuL: '\u255B', boxul: '\u2518', boxUR: '\u255A', boxUr: '\u2559', boxuR: '\u2558', boxur: '\u2514', boxV: '\u2551', boxv: '\u2502', boxVH: '\u256C', boxVh: '\u256B', boxvH: '\u256A', boxvh: '\u253C', boxVL: '\u2563', boxVl: '\u2562', boxvL: '\u2561', boxvl: '\u2524', boxVR: '\u2560', boxVr: '\u255F', boxvR: '\u255E', boxvr: '\u251C', bprime: '\u2035', Breve: '\u02D8', breve: '\u02D8', brvbar: '\u00A6', Bscr: '\u212C', bscr: '\uD835\uDCB7', bsemi: '\u204F', bsim: '\u223D', bsime: '\u22CD', bsol: '\u005C', bsolb: '\u29C5', bsolhsub: '\u27C8', bull: '\u2022', bullet: '\u2022', bump: '\u224E', bumpE: '\u2AAE', bumpe: '\u224F', Bumpeq: '\u224E', bumpeq: '\u224F', Cacute: '\u0106', cacute: '\u0107', Cap: '\u22D2', cap: '\u2229', capand: '\u2A44', capbrcup: '\u2A49', capcap: '\u2A4B', capcup: '\u2A47', capdot: '\u2A40', CapitalDifferentialD: '\u2145', caps: '\u2229\uFE00', caret: '\u2041', caron: '\u02C7', Cayleys: '\u212D', ccaps: '\u2A4D', Ccaron: '\u010C', ccaron: '\u010D', Ccedil: '\u00C7', ccedil: '\u00E7', Ccirc: '\u0108', ccirc: '\u0109', Cconint: '\u2230', ccups: '\u2A4C', ccupssm: '\u2A50', Cdot: '\u010A', cdot: '\u010B', cedil: '\u00B8', Cedilla: '\u00B8', cemptyv: '\u29B2', cent: '\u00A2', CenterDot: '\u00B7', centerdot: '\u00B7', Cfr: '\u212D', cfr: '\uD835\uDD20', CHcy: '\u0427', chcy: '\u0447', check: '\u2713', checkmark: '\u2713', Chi: '\u03A7', chi: '\u03C7', cir: '\u25CB', circ: '\u02C6', circeq: '\u2257', circlearrowleft: '\u21BA', circlearrowright: '\u21BB', circledast: '\u229B', circledcirc: '\u229A', circleddash: '\u229D', CircleDot: '\u2299', circledR: '\u00AE', circledS: '\u24C8', CircleMinus: '\u2296', CirclePlus: '\u2295', CircleTimes: '\u2297', cirE: '\u29C3', cire: '\u2257', cirfnint: '\u2A10', cirmid: '\u2AEF', cirscir: '\u29C2', ClockwiseContourIntegral: '\u2232', CloseCurlyDoubleQuote: '\u201D', CloseCurlyQuote: '\u2019', clubs: '\u2663', clubsuit: '\u2663', Colon: '\u2237', colon: '\u003A', Colone: '\u2A74', colone: '\u2254', coloneq: '\u2254', comma: '\u002C', commat: '\u0040', comp: '\u2201', compfn: '\u2218', complement: '\u2201', complexes: '\u2102', cong: '\u2245', congdot: '\u2A6D', Congruent: '\u2261', Conint: '\u222F', conint: '\u222E', ContourIntegral: '\u222E', Copf: '\u2102', copf: '\uD835\uDD54', coprod: '\u2210', Coproduct: '\u2210', COPY: '\u00A9', copy: '\u00A9', copysr: '\u2117', CounterClockwiseContourIntegral: '\u2233', crarr: '\u21B5', Cross: '\u2A2F', cross: '\u2717', Cscr: '\uD835\uDC9E', cscr: '\uD835\uDCB8', csub: '\u2ACF', csube: '\u2AD1', csup: '\u2AD0', csupe: '\u2AD2', ctdot: '\u22EF', cudarrl: '\u2938', cudarrr: '\u2935', cuepr: '\u22DE', cuesc: '\u22DF', cularr: '\u21B6', cularrp: '\u293D', Cup: '\u22D3', cup: '\u222A', cupbrcap: '\u2A48', CupCap: '\u224D', cupcap: '\u2A46', cupcup: '\u2A4A', cupdot: '\u228D', cupor: '\u2A45', cups: '\u222A\uFE00', curarr: '\u21B7', curarrm: '\u293C', curlyeqprec: '\u22DE', curlyeqsucc: '\u22DF', curlyvee: '\u22CE', curlywedge: '\u22CF', curren: '\u00A4', curvearrowleft: '\u21B6', curvearrowright: '\u21B7', cuvee: '\u22CE', cuwed: '\u22CF', cwconint: '\u2232', cwint: '\u2231', cylcty: '\u232D', Dagger: '\u2021', dagger: '\u2020', daleth: '\u2138', Darr: '\u21A1', dArr: '\u21D3', darr: '\u2193', dash: '\u2010', Dashv: '\u2AE4', dashv: '\u22A3', dbkarow: '\u290F', dblac: '\u02DD', Dcaron: '\u010E', dcaron: '\u010F', Dcy: '\u0414', dcy: '\u0434', DD: '\u2145', dd: '\u2146', ddagger: '\u2021', ddarr: '\u21CA', DDotrahd: '\u2911', ddotseq: '\u2A77', deg: '\u00B0', Del: '\u2207', Delta: '\u0394', delta: '\u03B4', demptyv: '\u29B1', dfisht: '\u297F', Dfr: '\uD835\uDD07', dfr: '\uD835\uDD21', dHar: '\u2965', dharl: '\u21C3', dharr: '\u21C2', DiacriticalAcute: '\u00B4', DiacriticalDot: '\u02D9', DiacriticalDoubleAcute: '\u02DD', DiacriticalGrave: '\u0060', DiacriticalTilde: '\u02DC', diam: '\u22C4', Diamond: '\u22C4', diamond: '\u22C4', diamondsuit: '\u2666', diams: '\u2666', die: '\u00A8', DifferentialD: '\u2146', digamma: '\u03DD', disin: '\u22F2', div: '\u00F7', divide: '\u00F7', divideontimes: '\u22C7', divonx: '\u22C7', DJcy: '\u0402', djcy: '\u0452', dlcorn: '\u231E', dlcrop: '\u230D', dollar: '\u0024', Dopf: '\uD835\uDD3B', dopf: '\uD835\uDD55', Dot: '\u00A8', dot: '\u02D9', DotDot: '\u20DC', doteq: '\u2250', doteqdot: '\u2251', DotEqual: '\u2250', dotminus: '\u2238', dotplus: '\u2214', dotsquare: '\u22A1', doublebarwedge: '\u2306', DoubleContourIntegral: '\u222F', DoubleDot: '\u00A8', DoubleDownArrow: '\u21D3', DoubleLeftArrow: '\u21D0', DoubleLeftRightArrow: '\u21D4', DoubleLeftTee: '\u2AE4', DoubleLongLeftArrow: '\u27F8', DoubleLongLeftRightArrow: '\u27FA', DoubleLongRightArrow: '\u27F9', DoubleRightArrow: '\u21D2', DoubleRightTee: '\u22A8', DoubleUpArrow: '\u21D1', DoubleUpDownArrow: '\u21D5', DoubleVerticalBar: '\u2225', DownArrow: '\u2193', Downarrow: '\u21D3', downarrow: '\u2193', DownArrowBar: '\u2913', DownArrowUpArrow: '\u21F5', DownBreve: '\u0311', downdownarrows: '\u21CA', downharpoonleft: '\u21C3', downharpoonright: '\u21C2', DownLeftRightVector: '\u2950', DownLeftTeeVector: '\u295E', DownLeftVector: '\u21BD', DownLeftVectorBar: '\u2956', DownRightTeeVector: '\u295F', DownRightVector: '\u21C1', DownRightVectorBar: '\u2957', DownTee: '\u22A4', DownTeeArrow: '\u21A7', drbkarow: '\u2910', drcorn: '\u231F', drcrop: '\u230C', Dscr: '\uD835\uDC9F', dscr: '\uD835\uDCB9', DScy: '\u0405', dscy: '\u0455', dsol: '\u29F6', Dstrok: '\u0110', dstrok: '\u0111', dtdot: '\u22F1', dtri: '\u25BF', dtrif: '\u25BE', duarr: '\u21F5', duhar: '\u296F', dwangle: '\u29A6', DZcy: '\u040F', dzcy: '\u045F', dzigrarr: '\u27FF', Eacute: '\u00C9', eacute: '\u00E9', easter: '\u2A6E', Ecaron: '\u011A', ecaron: '\u011B', ecir: '\u2256', Ecirc: '\u00CA', ecirc: '\u00EA', ecolon: '\u2255', Ecy: '\u042D', ecy: '\u044D', eDDot: '\u2A77', Edot: '\u0116', eDot: '\u2251', edot: '\u0117', ee: '\u2147', efDot: '\u2252', Efr: '\uD835\uDD08', efr: '\uD835\uDD22', eg: '\u2A9A', Egrave: '\u00C8', egrave: '\u00E8', egs: '\u2A96', egsdot: '\u2A98', el: '\u2A99', Element: '\u2208', elinters: '\u23E7', ell: '\u2113', els: '\u2A95', elsdot: '\u2A97', Emacr: '\u0112', emacr: '\u0113', empty: '\u2205', emptyset: '\u2205', EmptySmallSquare: '\u25FB', emptyv: '\u2205', EmptyVerySmallSquare: '\u25AB', emsp: '\u2003', emsp13: '\u2004', emsp14: '\u2005', ENG: '\u014A', eng: '\u014B', ensp: '\u2002', Eogon: '\u0118', eogon: '\u0119', Eopf: '\uD835\uDD3C', eopf: '\uD835\uDD56', epar: '\u22D5', eparsl: '\u29E3', eplus: '\u2A71', epsi: '\u03B5', Epsilon: '\u0395', epsilon: '\u03B5', epsiv: '\u03F5', eqcirc: '\u2256', eqcolon: '\u2255', eqsim: '\u2242', eqslantgtr: '\u2A96', eqslantless: '\u2A95', Equal: '\u2A75', equals: '\u003D', EqualTilde: '\u2242', equest: '\u225F', Equilibrium: '\u21CC', equiv: '\u2261', equivDD: '\u2A78', eqvparsl: '\u29E5', erarr: '\u2971', erDot: '\u2253', Escr: '\u2130', escr: '\u212F', esdot: '\u2250', Esim: '\u2A73', esim: '\u2242', Eta: '\u0397', eta: '\u03B7', ETH: '\u00D0', eth: '\u00F0', Euml: '\u00CB', euml: '\u00EB', euro: '\u20AC', excl: '\u0021', exist: '\u2203', Exists: '\u2203', expectation: '\u2130', ExponentialE: '\u2147', exponentiale: '\u2147', fallingdotseq: '\u2252', Fcy: '\u0424', fcy: '\u0444', female: '\u2640', ffilig: '\uFB03', fflig: '\uFB00', ffllig: '\uFB04', Ffr: '\uD835\uDD09', ffr: '\uD835\uDD23', filig: '\uFB01', FilledSmallSquare: '\u25FC', FilledVerySmallSquare: '\u25AA', fjlig: '\u0066\u006A', flat: '\u266D', fllig: '\uFB02', fltns: '\u25B1', fnof: '\u0192', Fopf: '\uD835\uDD3D', fopf: '\uD835\uDD57', ForAll: '\u2200', forall: '\u2200', fork: '\u22D4', forkv: '\u2AD9', Fouriertrf: '\u2131', fpartint: '\u2A0D', frac12: '\u00BD', frac13: '\u2153', frac14: '\u00BC', frac15: '\u2155', frac16: '\u2159', frac18: '\u215B', frac23: '\u2154', frac25: '\u2156', frac34: '\u00BE', frac35: '\u2157', frac38: '\u215C', frac45: '\u2158', frac56: '\u215A', frac58: '\u215D', frac78: '\u215E', frasl: '\u2044', frown: '\u2322', Fscr: '\u2131', fscr: '\uD835\uDCBB', gacute: '\u01F5', Gamma: '\u0393', gamma: '\u03B3', Gammad: '\u03DC', gammad: '\u03DD', gap: '\u2A86', Gbreve: '\u011E', gbreve: '\u011F', Gcedil: '\u0122', Gcirc: '\u011C', gcirc: '\u011D', Gcy: '\u0413', gcy: '\u0433', Gdot: '\u0120', gdot: '\u0121', gE: '\u2267', ge: '\u2265', gEl: '\u2A8C', gel: '\u22DB', geq: '\u2265', geqq: '\u2267', geqslant: '\u2A7E', ges: '\u2A7E', gescc: '\u2AA9', gesdot: '\u2A80', gesdoto: '\u2A82', gesdotol: '\u2A84', gesl: '\u22DB\uFE00', gesles: '\u2A94', Gfr: '\uD835\uDD0A', gfr: '\uD835\uDD24', Gg: '\u22D9', gg: '\u226B', ggg: '\u22D9', gimel: '\u2137', GJcy: '\u0403', gjcy: '\u0453', gl: '\u2277', gla: '\u2AA5', glE: '\u2A92', glj: '\u2AA4', gnap: '\u2A8A', gnapprox: '\u2A8A', gnE: '\u2269', gne: '\u2A88', gneq: '\u2A88', gneqq: '\u2269', gnsim: '\u22E7', Gopf: '\uD835\uDD3E', gopf: '\uD835\uDD58', grave: '\u0060', GreaterEqual: '\u2265', GreaterEqualLess: '\u22DB', GreaterFullEqual: '\u2267', GreaterGreater: '\u2AA2', GreaterLess: '\u2277', GreaterSlantEqual: '\u2A7E', GreaterTilde: '\u2273', Gscr: '\uD835\uDCA2', gscr: '\u210A', gsim: '\u2273', gsime: '\u2A8E', gsiml: '\u2A90', Gt: '\u226B', GT: '\u003E', gt: '\u003E', gtcc: '\u2AA7', gtcir: '\u2A7A', gtdot: '\u22D7', gtlPar: '\u2995', gtquest: '\u2A7C', gtrapprox: '\u2A86', gtrarr: '\u2978', gtrdot: '\u22D7', gtreqless: '\u22DB', gtreqqless: '\u2A8C', gtrless: '\u2277', gtrsim: '\u2273', gvertneqq: '\u2269\uFE00', gvnE: '\u2269\uFE00', Hacek: '\u02C7', hairsp: '\u200A', half: '\u00BD', hamilt: '\u210B', HARDcy: '\u042A', hardcy: '\u044A', hArr: '\u21D4', harr: '\u2194', harrcir: '\u2948', harrw: '\u21AD', Hat: '\u005E', hbar: '\u210F', Hcirc: '\u0124', hcirc: '\u0125', hearts: '\u2665', heartsuit: '\u2665', hellip: '\u2026', hercon: '\u22B9', Hfr: '\u210C', hfr: '\uD835\uDD25', HilbertSpace: '\u210B', hksearow: '\u2925', hkswarow: '\u2926', hoarr: '\u21FF', homtht: '\u223B', hookleftarrow: '\u21A9', hookrightarrow: '\u21AA', Hopf: '\u210D', hopf: '\uD835\uDD59', horbar: '\u2015', HorizontalLine: '\u2500', Hscr: '\u210B', hscr: '\uD835\uDCBD', hslash: '\u210F', Hstrok: '\u0126', hstrok: '\u0127', HumpDownHump: '\u224E', HumpEqual: '\u224F', hybull: '\u2043', hyphen: '\u2010', Iacute: '\u00CD', iacute: '\u00ED', ic: '\u2063', Icirc: '\u00CE', icirc: '\u00EE', Icy: '\u0418', icy: '\u0438', Idot: '\u0130', IEcy: '\u0415', iecy: '\u0435', iexcl: '\u00A1', iff: '\u21D4', Ifr: '\u2111', ifr: '\uD835\uDD26', Igrave: '\u00CC', igrave: '\u00EC', ii: '\u2148', iiiint: '\u2A0C', iiint: '\u222D', iinfin: '\u29DC', iiota: '\u2129', IJlig: '\u0132', ijlig: '\u0133', Im: '\u2111', Imacr: '\u012A', imacr: '\u012B', image: '\u2111', ImaginaryI: '\u2148', imagline: '\u2110', imagpart: '\u2111', imath: '\u0131', imof: '\u22B7', imped: '\u01B5', Implies: '\u21D2', in: '\u2208', incare: '\u2105', infin: '\u221E', infintie: '\u29DD', inodot: '\u0131', Int: '\u222C', int: '\u222B', intcal: '\u22BA', integers: '\u2124', Integral: '\u222B', intercal: '\u22BA', Intersection: '\u22C2', intlarhk: '\u2A17', intprod: '\u2A3C', InvisibleComma: '\u2063', InvisibleTimes: '\u2062', IOcy: '\u0401', iocy: '\u0451', Iogon: '\u012E', iogon: '\u012F', Iopf: '\uD835\uDD40', iopf: '\uD835\uDD5A', Iota: '\u0399', iota: '\u03B9', iprod: '\u2A3C', iquest: '\u00BF', Iscr: '\u2110', iscr: '\uD835\uDCBE', isin: '\u2208', isindot: '\u22F5', isinE: '\u22F9', isins: '\u22F4', isinsv: '\u22F3', isinv: '\u2208', it: '\u2062', Itilde: '\u0128', itilde: '\u0129', Iukcy: '\u0406', iukcy: '\u0456', Iuml: '\u00CF', iuml: '\u00EF', Jcirc: '\u0134', jcirc: '\u0135', Jcy: '\u0419', jcy: '\u0439', Jfr: '\uD835\uDD0D', jfr: '\uD835\uDD27', jmath: '\u0237', Jopf: '\uD835\uDD41', jopf: '\uD835\uDD5B', Jscr: '\uD835\uDCA5', jscr: '\uD835\uDCBF', Jsercy: '\u0408', jsercy: '\u0458', Jukcy: '\u0404', jukcy: '\u0454', Kappa: '\u039A', kappa: '\u03BA', kappav: '\u03F0', Kcedil: '\u0136', kcedil: '\u0137', Kcy: '\u041A', kcy: '\u043A', Kfr: '\uD835\uDD0E', kfr: '\uD835\uDD28', kgreen: '\u0138', KHcy: '\u0425', khcy: '\u0445', KJcy: '\u040C', kjcy: '\u045C', Kopf: '\uD835\uDD42', kopf: '\uD835\uDD5C', Kscr: '\uD835\uDCA6', kscr: '\uD835\uDCC0', lAarr: '\u21DA', Lacute: '\u0139', lacute: '\u013A', laemptyv: '\u29B4', lagran: '\u2112', Lambda: '\u039B', lambda: '\u03BB', Lang: '\u27EA', lang: '\u27E8', langd: '\u2991', langle: '\u27E8', lap: '\u2A85', Laplacetrf: '\u2112', laquo: '\u00AB', Larr: '\u219E', lArr: '\u21D0', larr: '\u2190', larrb: '\u21E4', larrbfs: '\u291F', larrfs: '\u291D', larrhk: '\u21A9', larrlp: '\u21AB', larrpl: '\u2939', larrsim: '\u2973', larrtl: '\u21A2', lat: '\u2AAB', lAtail: '\u291B', latail: '\u2919', late: '\u2AAD', lates: '\u2AAD\uFE00', lBarr: '\u290E', lbarr: '\u290C', lbbrk: '\u2772', lbrace: '\u007B', lbrack: '\u005B', lbrke: '\u298B', lbrksld: '\u298F', lbrkslu: '\u298D', Lcaron: '\u013D', lcaron: '\u013E', Lcedil: '\u013B', lcedil: '\u013C', lceil: '\u2308', lcub: '\u007B', Lcy: '\u041B', lcy: '\u043B', ldca: '\u2936', ldquo: '\u201C', ldquor: '\u201E', ldrdhar: '\u2967', ldrushar: '\u294B', ldsh: '\u21B2', lE: '\u2266', le: '\u2264', LeftAngleBracket: '\u27E8', LeftArrow: '\u2190', Leftarrow: '\u21D0', leftarrow: '\u2190', LeftArrowBar: '\u21E4', LeftArrowRightArrow: '\u21C6', leftarrowtail: '\u21A2', LeftCeiling: '\u2308', LeftDoubleBracket: '\u27E6', LeftDownTeeVector: '\u2961', LeftDownVector: '\u21C3', LeftDownVectorBar: '\u2959', LeftFloor: '\u230A', leftharpoondown: '\u21BD', leftharpoonup: '\u21BC', leftleftarrows: '\u21C7', LeftRightArrow: '\u2194', Leftrightarrow: '\u21D4', leftrightarrow: '\u2194', leftrightarrows: '\u21C6', leftrightharpoons: '\u21CB', leftrightsquigarrow: '\u21AD', LeftRightVector: '\u294E', LeftTee: '\u22A3', LeftTeeArrow: '\u21A4', LeftTeeVector: '\u295A', leftthreetimes: '\u22CB', LeftTriangle: '\u22B2', LeftTriangleBar: '\u29CF', LeftTriangleEqual: '\u22B4', LeftUpDownVector: '\u2951', LeftUpTeeVector: '\u2960', LeftUpVector: '\u21BF', LeftUpVectorBar: '\u2958', LeftVector: '\u21BC', LeftVectorBar: '\u2952', lEg: '\u2A8B', leg: '\u22DA', leq: '\u2264', leqq: '\u2266', leqslant: '\u2A7D', les: '\u2A7D', lescc: '\u2AA8', lesdot: '\u2A7F', lesdoto: '\u2A81', lesdotor: '\u2A83', lesg: '\u22DA\uFE00', lesges: '\u2A93', lessapprox: '\u2A85', lessdot: '\u22D6', lesseqgtr: '\u22DA', lesseqqgtr: '\u2A8B', LessEqualGreater: '\u22DA', LessFullEqual: '\u2266', LessGreater: '\u2276', lessgtr: '\u2276', LessLess: '\u2AA1', lesssim: '\u2272', LessSlantEqual: '\u2A7D', LessTilde: '\u2272', lfisht: '\u297C', lfloor: '\u230A', Lfr: '\uD835\uDD0F', lfr: '\uD835\uDD29', lg: '\u2276', lgE: '\u2A91', lHar: '\u2962', lhard: '\u21BD', lharu: '\u21BC', lharul: '\u296A', lhblk: '\u2584', LJcy: '\u0409', ljcy: '\u0459', Ll: '\u22D8', ll: '\u226A', llarr: '\u21C7', llcorner: '\u231E', Lleftarrow: '\u21DA', llhard: '\u296B', lltri: '\u25FA', Lmidot: '\u013F', lmidot: '\u0140', lmoust: '\u23B0', lmoustache: '\u23B0', lnap: '\u2A89', lnapprox: '\u2A89', lnE: '\u2268', lne: '\u2A87', lneq: '\u2A87', lneqq: '\u2268', lnsim: '\u22E6', loang: '\u27EC', loarr: '\u21FD', lobrk: '\u27E6', LongLeftArrow: '\u27F5', Longleftarrow: '\u27F8', longleftarrow: '\u27F5', LongLeftRightArrow: '\u27F7', Longleftrightarrow: '\u27FA', longleftrightarrow: '\u27F7', longmapsto: '\u27FC', LongRightArrow: '\u27F6', Longrightarrow: '\u27F9', longrightarrow: '\u27F6', looparrowleft: '\u21AB', looparrowright: '\u21AC', lopar: '\u2985', Lopf: '\uD835\uDD43', lopf: '\uD835\uDD5D', loplus: '\u2A2D', lotimes: '\u2A34', lowast: '\u2217', lowbar: '\u005F', LowerLeftArrow: '\u2199', LowerRightArrow: '\u2198', loz: '\u25CA', lozenge: '\u25CA', lozf: '\u29EB', lpar: '\u0028', lparlt: '\u2993', lrarr: '\u21C6', lrcorner: '\u231F', lrhar: '\u21CB', lrhard: '\u296D', lrm: '\u200E', lrtri: '\u22BF', lsaquo: '\u2039', Lscr: '\u2112', lscr: '\uD835\uDCC1', Lsh: '\u21B0', lsh: '\u21B0', lsim: '\u2272', lsime: '\u2A8D', lsimg: '\u2A8F', lsqb: '\u005B', lsquo: '\u2018', lsquor: '\u201A', Lstrok: '\u0141', lstrok: '\u0142', Lt: '\u226A', LT: '\u003C', lt: '\u003C', ltcc: '\u2AA6', ltcir: '\u2A79', ltdot: '\u22D6', lthree: '\u22CB', ltimes: '\u22C9', ltlarr: '\u2976', ltquest: '\u2A7B', ltri: '\u25C3', ltrie: '\u22B4', ltrif: '\u25C2', ltrPar: '\u2996', lurdshar: '\u294A', luruhar: '\u2966', lvertneqq: '\u2268\uFE00', lvnE: '\u2268\uFE00', macr: '\u00AF', male: '\u2642', malt: '\u2720', maltese: '\u2720', Map: '\u2905', map: '\u21A6', mapsto: '\u21A6', mapstodown: '\u21A7', mapstoleft: '\u21A4', mapstoup: '\u21A5', marker: '\u25AE', mcomma: '\u2A29', Mcy: '\u041C', mcy: '\u043C', mdash: '\u2014', mDDot: '\u223A', measuredangle: '\u2221', MediumSpace: '\u205F', Mellintrf: '\u2133', Mfr: '\uD835\uDD10', mfr: '\uD835\uDD2A', mho: '\u2127', micro: '\u00B5', mid: '\u2223', midast: '\u002A', midcir: '\u2AF0', middot: '\u00B7', minus: '\u2212', minusb: '\u229F', minusd: '\u2238', minusdu: '\u2A2A', MinusPlus: '\u2213', mlcp: '\u2ADB', mldr: '\u2026', mnplus: '\u2213', models: '\u22A7', Mopf: '\uD835\uDD44', mopf: '\uD835\uDD5E', mp: '\u2213', Mscr: '\u2133', mscr: '\uD835\uDCC2', mstpos: '\u223E', Mu: '\u039C', mu: '\u03BC', multimap: '\u22B8', mumap: '\u22B8', nabla: '\u2207', Nacute: '\u0143', nacute: '\u0144', nang: '\u2220\u20D2', nap: '\u2249', napE: '\u2A70\u0338', napid: '\u224B\u0338', napos: '\u0149', napprox: '\u2249', natur: '\u266E', natural: '\u266E', naturals: '\u2115', nbsp: '\u00A0', nbump: '\u224E\u0338', nbumpe: '\u224F\u0338', ncap: '\u2A43', Ncaron: '\u0147', ncaron: '\u0148', Ncedil: '\u0145', ncedil: '\u0146', ncong: '\u2247', ncongdot: '\u2A6D\u0338', ncup: '\u2A42', Ncy: '\u041D', ncy: '\u043D', ndash: '\u2013', ne: '\u2260', nearhk: '\u2924', neArr: '\u21D7', nearr: '\u2197', nearrow: '\u2197', nedot: '\u2250\u0338', NegativeMediumSpace: '\u200B', NegativeThickSpace: '\u200B', NegativeThinSpace: '\u200B', NegativeVeryThinSpace: '\u200B', nequiv: '\u2262', nesear: '\u2928', nesim: '\u2242\u0338', NestedGreaterGreater: '\u226B', NestedLessLess: '\u226A', NewLine: '\u000A', nexist: '\u2204', nexists: '\u2204', Nfr: '\uD835\uDD11', nfr: '\uD835\uDD2B', ngE: '\u2267\u0338', nge: '\u2271', ngeq: '\u2271', ngeqq: '\u2267\u0338', ngeqslant: '\u2A7E\u0338', nges: '\u2A7E\u0338', nGg: '\u22D9\u0338', ngsim: '\u2275', nGt: '\u226B\u20D2', ngt: '\u226F', ngtr: '\u226F', nGtv: '\u226B\u0338', nhArr: '\u21CE', nharr: '\u21AE', nhpar: '\u2AF2', ni: '\u220B', nis: '\u22FC', nisd: '\u22FA', niv: '\u220B', NJcy: '\u040A', njcy: '\u045A', nlArr: '\u21CD', nlarr: '\u219A', nldr: '\u2025', nlE: '\u2266\u0338', nle: '\u2270', nLeftarrow: '\u21CD', nleftarrow: '\u219A', nLeftrightarrow: '\u21CE', nleftrightarrow: '\u21AE', nleq: '\u2270', nleqq: '\u2266\u0338', nleqslant: '\u2A7D\u0338', nles: '\u2A7D\u0338', nless: '\u226E', nLl: '\u22D8\u0338', nlsim: '\u2274', nLt: '\u226A\u20D2', nlt: '\u226E', nltri: '\u22EA', nltrie: '\u22EC', nLtv: '\u226A\u0338', nmid: '\u2224', NoBreak: '\u2060', NonBreakingSpace: '\u00A0', Nopf: '\u2115', nopf: '\uD835\uDD5F', Not: '\u2AEC', not: '\u00AC', NotCongruent: '\u2262', NotCupCap: '\u226D', NotDoubleVerticalBar: '\u2226', NotElement: '\u2209', NotEqual: '\u2260', NotEqualTilde: '\u2242\u0338', NotExists: '\u2204', NotGreater: '\u226F', NotGreaterEqual: '\u2271', NotGreaterFullEqual: '\u2267\u0338', NotGreaterGreater: '\u226B\u0338', NotGreaterLess: '\u2279', NotGreaterSlantEqual: '\u2A7E\u0338', NotGreaterTilde: '\u2275', NotHumpDownHump: '\u224E\u0338', NotHumpEqual: '\u224F\u0338', notin: '\u2209', notindot: '\u22F5\u0338', notinE: '\u22F9\u0338', notinva: '\u2209', notinvb: '\u22F7', notinvc: '\u22F6', NotLeftTriangle: '\u22EA', NotLeftTriangleBar: '\u29CF\u0338', NotLeftTriangleEqual: '\u22EC', NotLess: '\u226E', NotLessEqual: '\u2270', NotLessGreater: '\u2278', NotLessLess: '\u226A\u0338', NotLessSlantEqual: '\u2A7D\u0338', NotLessTilde: '\u2274', NotNestedGreaterGreater: '\u2AA2\u0338', NotNestedLessLess: '\u2AA1\u0338', notni: '\u220C', notniva: '\u220C', notnivb: '\u22FE', notnivc: '\u22FD', NotPrecedes: '\u2280', NotPrecedesEqual: '\u2AAF\u0338', NotPrecedesSlantEqual: '\u22E0', NotReverseElement: '\u220C', NotRightTriangle: '\u22EB', NotRightTriangleBar: '\u29D0\u0338', NotRightTriangleEqual: '\u22ED', NotSquareSubset: '\u228F\u0338', NotSquareSubsetEqual: '\u22E2', NotSquareSuperset: '\u2290\u0338', NotSquareSupersetEqual: '\u22E3', NotSubset: '\u2282\u20D2', NotSubsetEqual: '\u2288', NotSucceeds: '\u2281', NotSucceedsEqual: '\u2AB0\u0338', NotSucceedsSlantEqual: '\u22E1', NotSucceedsTilde: '\u227F\u0338', NotSuperset: '\u2283\u20D2', NotSupersetEqual: '\u2289', NotTilde: '\u2241', NotTildeEqual: '\u2244', NotTildeFullEqual: '\u2247', NotTildeTilde: '\u2249', NotVerticalBar: '\u2224', npar: '\u2226', nparallel: '\u2226', nparsl: '\u2AFD\u20E5', npart: '\u2202\u0338', npolint: '\u2A14', npr: '\u2280', nprcue: '\u22E0', npre: '\u2AAF\u0338', nprec: '\u2280', npreceq: '\u2AAF\u0338', nrArr: '\u21CF', nrarr: '\u219B', nrarrc: '\u2933\u0338', nrarrw: '\u219D\u0338', nRightarrow: '\u21CF', nrightarrow: '\u219B', nrtri: '\u22EB', nrtrie: '\u22ED', nsc: '\u2281', nsccue: '\u22E1', nsce: '\u2AB0\u0338', Nscr: '\uD835\uDCA9', nscr: '\uD835\uDCC3', nshortmid: '\u2224', nshortparallel: '\u2226', nsim: '\u2241', nsime: '\u2244', nsimeq: '\u2244', nsmid: '\u2224', nspar: '\u2226', nsqsube: '\u22E2', nsqsupe: '\u22E3', nsub: '\u2284', nsubE: '\u2AC5\u0338', nsube: '\u2288', nsubset: '\u2282\u20D2', nsubseteq: '\u2288', nsubseteqq: '\u2AC5\u0338', nsucc: '\u2281', nsucceq: '\u2AB0\u0338', nsup: '\u2285', nsupE: '\u2AC6\u0338', nsupe: '\u2289', nsupset: '\u2283\u20D2', nsupseteq: '\u2289', nsupseteqq: '\u2AC6\u0338', ntgl: '\u2279', Ntilde: '\u00D1', ntilde: '\u00F1', ntlg: '\u2278', ntriangleleft: '\u22EA', ntrianglelefteq: '\u22EC', ntriangleright: '\u22EB', ntrianglerighteq: '\u22ED', Nu: '\u039D', nu: '\u03BD', num: '\u0023', numero: '\u2116', numsp: '\u2007', nvap: '\u224D\u20D2', nVDash: '\u22AF', nVdash: '\u22AE', nvDash: '\u22AD', nvdash: '\u22AC', nvge: '\u2265\u20D2', nvgt: '\u003E\u20D2', nvHarr: '\u2904', nvinfin: '\u29DE', nvlArr: '\u2902', nvle: '\u2264\u20D2', nvlt: '\u003C\u20D2', nvltrie: '\u22B4\u20D2', nvrArr: '\u2903', nvrtrie: '\u22B5\u20D2', nvsim: '\u223C\u20D2', nwarhk: '\u2923', nwArr: '\u21D6', nwarr: '\u2196', nwarrow: '\u2196', nwnear: '\u2927', Oacute: '\u00D3', oacute: '\u00F3', oast: '\u229B', ocir: '\u229A', Ocirc: '\u00D4', ocirc: '\u00F4', Ocy: '\u041E', ocy: '\u043E', odash: '\u229D', Odblac: '\u0150', odblac: '\u0151', odiv: '\u2A38', odot: '\u2299', odsold: '\u29BC', OElig: '\u0152', oelig: '\u0153', ofcir: '\u29BF', Ofr: '\uD835\uDD12', ofr: '\uD835\uDD2C', ogon: '\u02DB', Ograve: '\u00D2', ograve: '\u00F2', ogt: '\u29C1', ohbar: '\u29B5', ohm: '\u03A9', oint: '\u222E', olarr: '\u21BA', olcir: '\u29BE', olcross: '\u29BB', oline: '\u203E', olt: '\u29C0', Omacr: '\u014C', omacr: '\u014D', Omega: '\u03A9', omega: '\u03C9', Omicron: '\u039F', omicron: '\u03BF', omid: '\u29B6', ominus: '\u2296', Oopf: '\uD835\uDD46', oopf: '\uD835\uDD60', opar: '\u29B7', OpenCurlyDoubleQuote: '\u201C', OpenCurlyQuote: '\u2018', operp: '\u29B9', oplus: '\u2295', Or: '\u2A54', or: '\u2228', orarr: '\u21BB', ord: '\u2A5D', order: '\u2134', orderof: '\u2134', ordf: '\u00AA', ordm: '\u00BA', origof: '\u22B6', oror: '\u2A56', orslope: '\u2A57', orv: '\u2A5B', oS: '\u24C8', Oscr: '\uD835\uDCAA', oscr: '\u2134', Oslash: '\u00D8', oslash: '\u00F8', osol: '\u2298', Otilde: '\u00D5', otilde: '\u00F5', Otimes: '\u2A37', otimes: '\u2297', otimesas: '\u2A36', Ouml: '\u00D6', ouml: '\u00F6', ovbar: '\u233D', OverBar: '\u203E', OverBrace: '\u23DE', OverBracket: '\u23B4', OverParenthesis: '\u23DC', par: '\u2225', para: '\u00B6', parallel: '\u2225', parsim: '\u2AF3', parsl: '\u2AFD', part: '\u2202', PartialD: '\u2202', Pcy: '\u041F', pcy: '\u043F', percnt: '\u0025', period: '\u002E', permil: '\u2030', perp: '\u22A5', pertenk: '\u2031', Pfr: '\uD835\uDD13', pfr: '\uD835\uDD2D', Phi: '\u03A6', phi: '\u03C6', phiv: '\u03D5', phmmat: '\u2133', phone: '\u260E', Pi: '\u03A0', pi: '\u03C0', pitchfork: '\u22D4', piv: '\u03D6', planck: '\u210F', planckh: '\u210E', plankv: '\u210F', plus: '\u002B', plusacir: '\u2A23', plusb: '\u229E', pluscir: '\u2A22', plusdo: '\u2214', plusdu: '\u2A25', pluse: '\u2A72', PlusMinus: '\u00B1', plusmn: '\u00B1', plussim: '\u2A26', plustwo: '\u2A27', pm: '\u00B1', Poincareplane: '\u210C', pointint: '\u2A15', Popf: '\u2119', popf: '\uD835\uDD61', pound: '\u00A3', Pr: '\u2ABB', pr: '\u227A', prap: '\u2AB7', prcue: '\u227C', prE: '\u2AB3', pre: '\u2AAF', prec: '\u227A', precapprox: '\u2AB7', preccurlyeq: '\u227C', Precedes: '\u227A', PrecedesEqual: '\u2AAF', PrecedesSlantEqual: '\u227C', PrecedesTilde: '\u227E', preceq: '\u2AAF', precnapprox: '\u2AB9', precneqq: '\u2AB5', precnsim: '\u22E8', precsim: '\u227E', Prime: '\u2033', prime: '\u2032', primes: '\u2119', prnap: '\u2AB9', prnE: '\u2AB5', prnsim: '\u22E8', prod: '\u220F', Product: '\u220F', profalar: '\u232E', profline: '\u2312', profsurf: '\u2313', prop: '\u221D', Proportion: '\u2237', Proportional: '\u221D', propto: '\u221D', prsim: '\u227E', prurel: '\u22B0', Pscr: '\uD835\uDCAB', pscr: '\uD835\uDCC5', Psi: '\u03A8', psi: '\u03C8', puncsp: '\u2008', Qfr: '\uD835\uDD14', qfr: '\uD835\uDD2E', qint: '\u2A0C', Qopf: '\u211A', qopf: '\uD835\uDD62', qprime: '\u2057', Qscr: '\uD835\uDCAC', qscr: '\uD835\uDCC6', quaternions: '\u210D', quatint: '\u2A16', quest: '\u003F', questeq: '\u225F', QUOT: '\u0022', quot: '\u0022', rAarr: '\u21DB', race: '\u223D\u0331', Racute: '\u0154', racute: '\u0155', radic: '\u221A', raemptyv: '\u29B3', Rang: '\u27EB', rang: '\u27E9', rangd: '\u2992', range: '\u29A5', rangle: '\u27E9', raquo: '\u00BB', Rarr: '\u21A0', rArr: '\u21D2', rarr: '\u2192', rarrap: '\u2975', rarrb: '\u21E5', rarrbfs: '\u2920', rarrc: '\u2933', rarrfs: '\u291E', rarrhk: '\u21AA', rarrlp: '\u21AC', rarrpl: '\u2945', rarrsim: '\u2974', Rarrtl: '\u2916', rarrtl: '\u21A3', rarrw: '\u219D', rAtail: '\u291C', ratail: '\u291A', ratio: '\u2236', rationals: '\u211A', RBarr: '\u2910', rBarr: '\u290F', rbarr: '\u290D', rbbrk: '\u2773', rbrace: '\u007D', rbrack: '\u005D', rbrke: '\u298C', rbrksld: '\u298E', rbrkslu: '\u2990', Rcaron: '\u0158', rcaron: '\u0159', Rcedil: '\u0156', rcedil: '\u0157', rceil: '\u2309', rcub: '\u007D', Rcy: '\u0420', rcy: '\u0440', rdca: '\u2937', rdldhar: '\u2969', rdquo: '\u201D', rdquor: '\u201D', rdsh: '\u21B3', Re: '\u211C', real: '\u211C', realine: '\u211B', realpart: '\u211C', reals: '\u211D', rect: '\u25AD', REG: '\u00AE', reg: '\u00AE', ReverseElement: '\u220B', ReverseEquilibrium: '\u21CB', ReverseUpEquilibrium: '\u296F', rfisht: '\u297D', rfloor: '\u230B', Rfr: '\u211C', rfr: '\uD835\uDD2F', rHar: '\u2964', rhard: '\u21C1', rharu: '\u21C0', rharul: '\u296C', Rho: '\u03A1', rho: '\u03C1', rhov: '\u03F1', RightAngleBracket: '\u27E9', RightArrow: '\u2192', Rightarrow: '\u21D2', rightarrow: '\u2192', RightArrowBar: '\u21E5', RightArrowLeftArrow: '\u21C4', rightarrowtail: '\u21A3', RightCeiling: '\u2309', RightDoubleBracket: '\u27E7', RightDownTeeVector: '\u295D', RightDownVector: '\u21C2', RightDownVectorBar: '\u2955', RightFloor: '\u230B', rightharpoondown: '\u21C1', rightharpoonup: '\u21C0', rightleftarrows: '\u21C4', rightleftharpoons: '\u21CC', rightrightarrows: '\u21C9', rightsquigarrow: '\u219D', RightTee: '\u22A2', RightTeeArrow: '\u21A6', RightTeeVector: '\u295B', rightthreetimes: '\u22CC', RightTriangle: '\u22B3', RightTriangleBar: '\u29D0', RightTriangleEqual: '\u22B5', RightUpDownVector: '\u294F', RightUpTeeVector: '\u295C', RightUpVector: '\u21BE', RightUpVectorBar: '\u2954', RightVector: '\u21C0', RightVectorBar: '\u2953', ring: '\u02DA', risingdotseq: '\u2253', rlarr: '\u21C4', rlhar: '\u21CC', rlm: '\u200F', rmoust: '\u23B1', rmoustache: '\u23B1', rnmid: '\u2AEE', roang: '\u27ED', roarr: '\u21FE', robrk: '\u27E7', ropar: '\u2986', Ropf: '\u211D', ropf: '\uD835\uDD63', roplus: '\u2A2E', rotimes: '\u2A35', RoundImplies: '\u2970', rpar: '\u0029', rpargt: '\u2994', rppolint: '\u2A12', rrarr: '\u21C9', Rrightarrow: '\u21DB', rsaquo: '\u203A', Rscr: '\u211B', rscr: '\uD835\uDCC7', Rsh: '\u21B1', rsh: '\u21B1', rsqb: '\u005D', rsquo: '\u2019', rsquor: '\u2019', rthree: '\u22CC', rtimes: '\u22CA', rtri: '\u25B9', rtrie: '\u22B5', rtrif: '\u25B8', rtriltri: '\u29CE', RuleDelayed: '\u29F4', ruluhar: '\u2968', rx: '\u211E', Sacute: '\u015A', sacute: '\u015B', sbquo: '\u201A', Sc: '\u2ABC', sc: '\u227B', scap: '\u2AB8', Scaron: '\u0160', scaron: '\u0161', sccue: '\u227D', scE: '\u2AB4', sce: '\u2AB0', Scedil: '\u015E', scedil: '\u015F', Scirc: '\u015C', scirc: '\u015D', scnap: '\u2ABA', scnE: '\u2AB6', scnsim: '\u22E9', scpolint: '\u2A13', scsim: '\u227F', Scy: '\u0421', scy: '\u0441', sdot: '\u22C5', sdotb: '\u22A1', sdote: '\u2A66', searhk: '\u2925', seArr: '\u21D8', searr: '\u2198', searrow: '\u2198', sect: '\u00A7', semi: '\u003B', seswar: '\u2929', setminus: '\u2216', setmn: '\u2216', sext: '\u2736', Sfr: '\uD835\uDD16', sfr: '\uD835\uDD30', sfrown: '\u2322', sharp: '\u266F', SHCHcy: '\u0429', shchcy: '\u0449', SHcy: '\u0428', shcy: '\u0448', ShortDownArrow: '\u2193', ShortLeftArrow: '\u2190', shortmid: '\u2223', shortparallel: '\u2225', ShortRightArrow: '\u2192', ShortUpArrow: '\u2191', shy: '\u00AD', Sigma: '\u03A3', sigma: '\u03C3', sigmaf: '\u03C2', sigmav: '\u03C2', sim: '\u223C', simdot: '\u2A6A', sime: '\u2243', simeq: '\u2243', simg: '\u2A9E', simgE: '\u2AA0', siml: '\u2A9D', simlE: '\u2A9F', simne: '\u2246', simplus: '\u2A24', simrarr: '\u2972', slarr: '\u2190', SmallCircle: '\u2218', smallsetminus: '\u2216', smashp: '\u2A33', smeparsl: '\u29E4', smid: '\u2223', smile: '\u2323', smt: '\u2AAA', smte: '\u2AAC', smtes: '\u2AAC\uFE00', SOFTcy: '\u042C', softcy: '\u044C', sol: '\u002F', solb: '\u29C4', solbar: '\u233F', Sopf: '\uD835\uDD4A', sopf: '\uD835\uDD64', spades: '\u2660', spadesuit: '\u2660', spar: '\u2225', sqcap: '\u2293', sqcaps: '\u2293\uFE00', sqcup: '\u2294', sqcups: '\u2294\uFE00', Sqrt: '\u221A', sqsub: '\u228F', sqsube: '\u2291', sqsubset: '\u228F', sqsubseteq: '\u2291', sqsup: '\u2290', sqsupe: '\u2292', sqsupset: '\u2290', sqsupseteq: '\u2292', squ: '\u25A1', Square: '\u25A1', square: '\u25A1', SquareIntersection: '\u2293', SquareSubset: '\u228F', SquareSubsetEqual: '\u2291', SquareSuperset: '\u2290', SquareSupersetEqual: '\u2292', SquareUnion: '\u2294', squarf: '\u25AA', squf: '\u25AA', srarr: '\u2192', Sscr: '\uD835\uDCAE', sscr: '\uD835\uDCC8', ssetmn: '\u2216', ssmile: '\u2323', sstarf: '\u22C6', Star: '\u22C6', star: '\u2606', starf: '\u2605', straightepsilon: '\u03F5', straightphi: '\u03D5', strns: '\u00AF', Sub: '\u22D0', sub: '\u2282', subdot: '\u2ABD', subE: '\u2AC5', sube: '\u2286', subedot: '\u2AC3', submult: '\u2AC1', subnE: '\u2ACB', subne: '\u228A', subplus: '\u2ABF', subrarr: '\u2979', Subset: '\u22D0', subset: '\u2282', subseteq: '\u2286', subseteqq: '\u2AC5', SubsetEqual: '\u2286', subsetneq: '\u228A', subsetneqq: '\u2ACB', subsim: '\u2AC7', subsub: '\u2AD5', subsup: '\u2AD3', succ: '\u227B', succapprox: '\u2AB8', succcurlyeq: '\u227D', Succeeds: '\u227B', SucceedsEqual: '\u2AB0', SucceedsSlantEqual: '\u227D', SucceedsTilde: '\u227F', succeq: '\u2AB0', succnapprox: '\u2ABA', succneqq: '\u2AB6', succnsim: '\u22E9', succsim: '\u227F', SuchThat: '\u220B', Sum: '\u2211', sum: '\u2211', sung: '\u266A', Sup: '\u22D1', sup: '\u2283', sup1: '\u00B9', sup2: '\u00B2', sup3: '\u00B3', supdot: '\u2ABE', supdsub: '\u2AD8', supE: '\u2AC6', supe: '\u2287', supedot: '\u2AC4', Superset: '\u2283', SupersetEqual: '\u2287', suphsol: '\u27C9', suphsub: '\u2AD7', suplarr: '\u297B', supmult: '\u2AC2', supnE: '\u2ACC', supne: '\u228B', supplus: '\u2AC0', Supset: '\u22D1', supset: '\u2283', supseteq: '\u2287', supseteqq: '\u2AC6', supsetneq: '\u228B', supsetneqq: '\u2ACC', supsim: '\u2AC8', supsub: '\u2AD4', supsup: '\u2AD6', swarhk: '\u2926', swArr: '\u21D9', swarr: '\u2199', swarrow: '\u2199', swnwar: '\u292A', szlig: '\u00DF', Tab: '\u0009', target: '\u2316', Tau: '\u03A4', tau: '\u03C4', tbrk: '\u23B4', Tcaron: '\u0164', tcaron: '\u0165', Tcedil: '\u0162', tcedil: '\u0163', Tcy: '\u0422', tcy: '\u0442', tdot: '\u20DB', telrec: '\u2315', Tfr: '\uD835\uDD17', tfr: '\uD835\uDD31', there4: '\u2234', Therefore: '\u2234', therefore: '\u2234', Theta: '\u0398', theta: '\u03B8', thetasym: '\u03D1', thetav: '\u03D1', thickapprox: '\u2248', thicksim: '\u223C', ThickSpace: '\u205F\u200A', thinsp: '\u2009', ThinSpace: '\u2009', thkap: '\u2248', thksim: '\u223C', THORN: '\u00DE', thorn: '\u00FE', Tilde: '\u223C', tilde: '\u02DC', TildeEqual: '\u2243', TildeFullEqual: '\u2245', TildeTilde: '\u2248', times: '\u00D7', timesb: '\u22A0', timesbar: '\u2A31', timesd: '\u2A30', tint: '\u222D', toea: '\u2928', top: '\u22A4', topbot: '\u2336', topcir: '\u2AF1', Topf: '\uD835\uDD4B', topf: '\uD835\uDD65', topfork: '\u2ADA', tosa: '\u2929', tprime: '\u2034', TRADE: '\u2122', trade: '\u2122', triangle: '\u25B5', triangledown: '\u25BF', triangleleft: '\u25C3', trianglelefteq: '\u22B4', triangleq: '\u225C', triangleright: '\u25B9', trianglerighteq: '\u22B5', tridot: '\u25EC', trie: '\u225C', triminus: '\u2A3A', TripleDot: '\u20DB', triplus: '\u2A39', trisb: '\u29CD', tritime: '\u2A3B', trpezium: '\u23E2', Tscr: '\uD835\uDCAF', tscr: '\uD835\uDCC9', TScy: '\u0426', tscy: '\u0446', TSHcy: '\u040B', tshcy: '\u045B', Tstrok: '\u0166', tstrok: '\u0167', twixt: '\u226C', twoheadleftarrow: '\u219E', twoheadrightarrow: '\u21A0', Uacute: '\u00DA', uacute: '\u00FA', Uarr: '\u219F', uArr: '\u21D1', uarr: '\u2191', Uarrocir: '\u2949', Ubrcy: '\u040E', ubrcy: '\u045E', Ubreve: '\u016C', ubreve: '\u016D', Ucirc: '\u00DB', ucirc: '\u00FB', Ucy: '\u0423', ucy: '\u0443', udarr: '\u21C5', Udblac: '\u0170', udblac: '\u0171', udhar: '\u296E', ufisht: '\u297E', Ufr: '\uD835\uDD18', ufr: '\uD835\uDD32', Ugrave: '\u00D9', ugrave: '\u00F9', uHar: '\u2963', uharl: '\u21BF', uharr: '\u21BE', uhblk: '\u2580', ulcorn: '\u231C', ulcorner: '\u231C', ulcrop: '\u230F', ultri: '\u25F8', Umacr: '\u016A', umacr: '\u016B', uml: '\u00A8', UnderBar: '\u005F', UnderBrace: '\u23DF', UnderBracket: '\u23B5', UnderParenthesis: '\u23DD', Union: '\u22C3', UnionPlus: '\u228E', Uogon: '\u0172', uogon: '\u0173', Uopf: '\uD835\uDD4C', uopf: '\uD835\uDD66', UpArrow: '\u2191', Uparrow: '\u21D1', uparrow: '\u2191', UpArrowBar: '\u2912', UpArrowDownArrow: '\u21C5', UpDownArrow: '\u2195', Updownarrow: '\u21D5', updownarrow: '\u2195', UpEquilibrium: '\u296E', upharpoonleft: '\u21BF', upharpoonright: '\u21BE', uplus: '\u228E', UpperLeftArrow: '\u2196', UpperRightArrow: '\u2197', Upsi: '\u03D2', upsi: '\u03C5', upsih: '\u03D2', Upsilon: '\u03A5', upsilon: '\u03C5', UpTee: '\u22A5', UpTeeArrow: '\u21A5', upuparrows: '\u21C8', urcorn: '\u231D', urcorner: '\u231D', urcrop: '\u230E', Uring: '\u016E', uring: '\u016F', urtri: '\u25F9', Uscr: '\uD835\uDCB0', uscr: '\uD835\uDCCA', utdot: '\u22F0', Utilde: '\u0168', utilde: '\u0169', utri: '\u25B5', utrif: '\u25B4', uuarr: '\u21C8', Uuml: '\u00DC', uuml: '\u00FC', uwangle: '\u29A7', vangrt: '\u299C', varepsilon: '\u03F5', varkappa: '\u03F0', varnothing: '\u2205', varphi: '\u03D5', varpi: '\u03D6', varpropto: '\u221D', vArr: '\u21D5', varr: '\u2195', varrho: '\u03F1', varsigma: '\u03C2', varsubsetneq: '\u228A\uFE00', varsubsetneqq: '\u2ACB\uFE00', varsupsetneq: '\u228B\uFE00', varsupsetneqq: '\u2ACC\uFE00', vartheta: '\u03D1', vartriangleleft: '\u22B2', vartriangleright: '\u22B3', Vbar: '\u2AEB', vBar: '\u2AE8', vBarv: '\u2AE9', Vcy: '\u0412', vcy: '\u0432', VDash: '\u22AB', Vdash: '\u22A9', vDash: '\u22A8', vdash: '\u22A2', Vdashl: '\u2AE6', Vee: '\u22C1', vee: '\u2228', veebar: '\u22BB', veeeq: '\u225A', vellip: '\u22EE', Verbar: '\u2016', verbar: '\u007C', Vert: '\u2016', vert: '\u007C', VerticalBar: '\u2223', VerticalLine: '\u007C', VerticalSeparator: '\u2758', VerticalTilde: '\u2240', VeryThinSpace: '\u200A', Vfr: '\uD835\uDD19', vfr: '\uD835\uDD33', vltri: '\u22B2', vnsub: '\u2282\u20D2', vnsup: '\u2283\u20D2', Vopf: '\uD835\uDD4D', vopf: '\uD835\uDD67', vprop: '\u221D', vrtri: '\u22B3', Vscr: '\uD835\uDCB1', vscr: '\uD835\uDCCB', vsubnE: '\u2ACB\uFE00', vsubne: '\u228A\uFE00', vsupnE: '\u2ACC\uFE00', vsupne: '\u228B\uFE00', Vvdash: '\u22AA', vzigzag: '\u299A', Wcirc: '\u0174', wcirc: '\u0175', wedbar: '\u2A5F', Wedge: '\u22C0', wedge: '\u2227', wedgeq: '\u2259', weierp: '\u2118', Wfr: '\uD835\uDD1A', wfr: '\uD835\uDD34', Wopf: '\uD835\uDD4E', wopf: '\uD835\uDD68', wp: '\u2118', wr: '\u2240', wreath: '\u2240', Wscr: '\uD835\uDCB2', wscr: '\uD835\uDCCC', xcap: '\u22C2', xcirc: '\u25EF', xcup: '\u22C3', xdtri: '\u25BD', Xfr: '\uD835\uDD1B', xfr: '\uD835\uDD35', xhArr: '\u27FA', xharr: '\u27F7', Xi: '\u039E', xi: '\u03BE', xlArr: '\u27F8', xlarr: '\u27F5', xmap: '\u27FC', xnis: '\u22FB', xodot: '\u2A00', Xopf: '\uD835\uDD4F', xopf: '\uD835\uDD69', xoplus: '\u2A01', xotime: '\u2A02', xrArr: '\u27F9', xrarr: '\u27F6', Xscr: '\uD835\uDCB3', xscr: '\uD835\uDCCD', xsqcup: '\u2A06', xuplus: '\u2A04', xutri: '\u25B3', xvee: '\u22C1', xwedge: '\u22C0', Yacute: '\u00DD', yacute: '\u00FD', YAcy: '\u042F', yacy: '\u044F', Ycirc: '\u0176', ycirc: '\u0177', Ycy: '\u042B', ycy: '\u044B', yen: '\u00A5', Yfr: '\uD835\uDD1C', yfr: '\uD835\uDD36', YIcy: '\u0407', yicy: '\u0457', Yopf: '\uD835\uDD50', yopf: '\uD835\uDD6A', Yscr: '\uD835\uDCB4', yscr: '\uD835\uDCCE', YUcy: '\u042E', yucy: '\u044E', Yuml: '\u0178', yuml: '\u00FF', Zacute: '\u0179', zacute: '\u017A', Zcaron: '\u017D', zcaron: '\u017E', Zcy: '\u0417', zcy: '\u0437', Zdot: '\u017B', zdot: '\u017C', zeetrf: '\u2128', ZeroWidthSpace: '\u200B', Zeta: '\u0396', zeta: '\u03B6', Zfr: '\u2128', zfr: '\uD835\uDD37', ZHcy: '\u0416', zhcy: '\u0436', zigrarr: '\u21DD', Zopf: '\u2124', zopf: '\uD835\uDD6B', Zscr: '\uD835\uDCB5', zscr: '\uD835\uDCCF', zwj: '\u200D', zwnj: '\u200C', }); /** * @deprecated * Use `HTML_ENTITIES` instead. * @see {@link HTML_ENTITIES} */ exports.entityMap = exports.HTML_ENTITIES; /***/ }), /***/ 7368: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var conventions = __nccwpck_require__(7855); function extendError(constructor, writableName) { constructor.prototype = Object.create(Error.prototype, { constructor: { value: constructor }, name: { value: constructor.name, enumerable: true, writable: writableName }, }); } var DOMExceptionName = conventions.freeze({ /** * the default value as defined by the spec */ Error: 'Error', /** * @deprecated * Use RangeError instead. */ IndexSizeError: 'IndexSizeError', /** * @deprecated * Just to match the related static code, not part of the spec. */ DomstringSizeError: 'DomstringSizeError', HierarchyRequestError: 'HierarchyRequestError', WrongDocumentError: 'WrongDocumentError', InvalidCharacterError: 'InvalidCharacterError', /** * @deprecated * Just to match the related static code, not part of the spec. */ NoDataAllowedError: 'NoDataAllowedError', NoModificationAllowedError: 'NoModificationAllowedError', NotFoundError: 'NotFoundError', NotSupportedError: 'NotSupportedError', InUseAttributeError: 'InUseAttributeError', InvalidStateError: 'InvalidStateError', SyntaxError: 'SyntaxError', InvalidModificationError: 'InvalidModificationError', NamespaceError: 'NamespaceError', /** * @deprecated * Use TypeError for invalid arguments, * "NotSupportedError" DOMException for unsupported operations, * and "NotAllowedError" DOMException for denied requests instead. */ InvalidAccessError: 'InvalidAccessError', /** * @deprecated * Just to match the related static code, not part of the spec. */ ValidationError: 'ValidationError', /** * @deprecated * Use TypeError instead. */ TypeMismatchError: 'TypeMismatchError', SecurityError: 'SecurityError', NetworkError: 'NetworkError', AbortError: 'AbortError', /** * @deprecated * Just to match the related static code, not part of the spec. */ URLMismatchError: 'URLMismatchError', QuotaExceededError: 'QuotaExceededError', TimeoutError: 'TimeoutError', InvalidNodeTypeError: 'InvalidNodeTypeError', DataCloneError: 'DataCloneError', EncodingError: 'EncodingError', NotReadableError: 'NotReadableError', UnknownError: 'UnknownError', ConstraintError: 'ConstraintError', DataError: 'DataError', TransactionInactiveError: 'TransactionInactiveError', ReadOnlyError: 'ReadOnlyError', VersionError: 'VersionError', OperationError: 'OperationError', NotAllowedError: 'NotAllowedError', OptOutError: 'OptOutError', }); var DOMExceptionNames = Object.keys(DOMExceptionName); function isValidDomExceptionCode(value) { return typeof value === 'number' && value >= 1 && value <= 25; } function endsWithError(value) { return typeof value === 'string' && value.substring(value.length - DOMExceptionName.Error.length) === DOMExceptionName.Error; } /** * DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation * is impossible to perform (either for logical reasons, because data is lost, or because the * implementation has become unstable). In general, DOM methods return specific error values in * ordinary processing situations, such as out-of-bound errors when using NodeList. * * Implementations should raise other exceptions under other circumstances. For example, * implementations should raise an implementation-dependent exception if a null argument is * passed when null was not expected. * * This implementation supports the following usages: * 1. according to the living standard (both arguments are optional): * ``` * new DOMException("message (can be empty)", DOMExceptionNames.HierarchyRequestError) * ``` * 2. according to previous xmldom implementation (only the first argument is required): * ``` * new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "optional message") * ``` * both result in the proper name being set. * * @class DOMException * @param {number | string} messageOrCode * The reason why an operation is not acceptable. * If it is a number, it is used to determine the `name`, see * {@link https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-258A00AF ExceptionCode} * @param {string | keyof typeof DOMExceptionName | Error} [nameOrMessage] * The `name` to use for the error. * If `messageOrCode` is a number, this arguments is used as the `message` instead. * @augments Error * @see https://webidl.spec.whatwg.org/#idl-DOMException * @see https://webidl.spec.whatwg.org/#dfn-error-names-table * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-17189187 * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html */ function DOMException(messageOrCode, nameOrMessage) { // support old way of passing arguments: first argument is a valid number if (isValidDomExceptionCode(messageOrCode)) { this.name = DOMExceptionNames[messageOrCode]; this.message = nameOrMessage || ''; } else { this.message = messageOrCode; this.name = endsWithError(nameOrMessage) ? nameOrMessage : DOMExceptionName.Error; } if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException); } extendError(DOMException, true); Object.defineProperties(DOMException.prototype, { code: { enumerable: true, get: function () { var code = DOMExceptionNames.indexOf(this.name); if (isValidDomExceptionCode(code)) return code; return 0; }, }, }); var ExceptionCode = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25, }; var entries = Object.entries(ExceptionCode); for (var i = 0; i < entries.length; i++) { var key = entries[i][0]; DOMException[key] = entries[i][1]; } /** * Creates an error that will not be caught by XMLReader aka the SAX parser. * * @class * @param {string} message * @param {any} [locator] */ function ParseError(message, locator) { this.message = message; this.locator = locator; if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError); } extendError(ParseError); exports.DOMException = DOMException; exports.DOMExceptionName = DOMExceptionName; exports.ExceptionCode = ExceptionCode; exports.ParseError = ParseError; /***/ }), /***/ 2062: /***/ ((__unused_webpack_module, exports) => { /** * Detects relevant unicode support for regular expressions in the runtime. * Should the runtime not accepts the flag `u` or unicode ranges, * character classes without unicode handling will be used. * * @param {typeof RegExp} [RegExpImpl=RegExp] * For testing: the RegExp class. * @returns {boolean} * @see https://node.green/#ES2015-syntax-RegExp--y--and--u--flags */ function detectUnicodeSupport(RegExpImpl) { try { if (typeof RegExpImpl !== 'function') { RegExpImpl = RegExp; } // eslint-disable-next-line es5/no-unicode-regex,es5/no-unicode-code-point-escape var match = new RegExpImpl('\u{1d306}', 'u').exec('𝌆'); return !!match && match[0].length === 2; } catch (error) {} return false; } var UNICODE_SUPPORT = detectUnicodeSupport(); /** * Removes `[`, `]` and any trailing quantifiers from the source of a RegExp. * * @param {RegExp} regexp */ function chars(regexp) { if (regexp.source[0] !== '[') { throw new Error(regexp + ' can not be used with chars'); } return regexp.source.slice(1, regexp.source.lastIndexOf(']')); } /** * Creates a new character list regular expression, * by removing `search` from the source of `regexp`. * * @param {RegExp} regexp * @param {string} search * The character(s) to remove. * @returns {RegExp} */ function chars_without(regexp, search) { if (regexp.source[0] !== '[') { throw new Error('/' + regexp.source + '/ can not be used with chars_without'); } if (!search || typeof search !== 'string') { throw new Error(JSON.stringify(search) + ' is not a valid search'); } if (regexp.source.indexOf(search) === -1) { throw new Error('"' + search + '" is not is /' + regexp.source + '/'); } if (search === '-' && regexp.source.indexOf(search) !== 1) { throw new Error('"' + search + '" is not at the first postion of /' + regexp.source + '/'); } return new RegExp(regexp.source.replace(search, ''), UNICODE_SUPPORT ? 'u' : ''); } /** * Combines and Regular expressions correctly by using `RegExp.source`. * * @param {...(RegExp | string)[]} args * @returns {RegExp} */ function reg(args) { var self = this; return new RegExp( Array.prototype.slice .call(arguments) .map(function (part) { var isStr = typeof part === 'string'; if (isStr && self === undefined && part === '|') { throw new Error('use regg instead of reg to wrap expressions with `|`!'); } return isStr ? part : part.source; }) .join(''), UNICODE_SUPPORT ? 'mu' : 'm' ); } /** * Like `reg` but wraps the expression in `(?:`,`)` to create a non tracking group. * * @param {...(RegExp | string)[]} args * @returns {RegExp} */ function regg(args) { if (arguments.length === 0) { throw new Error('no parameters provided'); } return reg.apply(regg, ['(?:'].concat(Array.prototype.slice.call(arguments), [')'])); } // /** // * Append ^ to the beginning of the expression. // * @param {...(RegExp | string)[]} args // * @returns {RegExp} // */ // function reg_start(args) { // if (arguments.length === 0) { // throw new Error('no parameters provided'); // } // return reg.apply(reg_start, ['^'].concat(Array.prototype.slice.call(arguments))); // } // https://www.w3.org/TR/xml/#document // `[1] document ::= prolog element Misc*` // https://www.w3.org/TR/xml11/#NT-document // `[1] document ::= ( prolog element Misc* ) - ( Char* RestrictedChar Char* )` /** * A character usually appearing in wrongly converted strings. * * @type {string} * @see https://en.wikipedia.org/wiki/Specials_(Unicode_block)#Replacement_character * @see https://nodejs.dev/en/api/v18/buffer/#buffers-and-character-encodings * @see https://www.unicode.org/faq/utf_bom.html#BOM * @readonly */ var UNICODE_REPLACEMENT_CHARACTER = '\uFFFD'; // https://www.w3.org/TR/xml/#NT-Char // any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. // `[2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]` // https://www.w3.org/TR/xml11/#NT-Char // `[2] Char ::= [#x1-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]` // https://www.w3.org/TR/xml11/#NT-RestrictedChar // `[2a] RestrictedChar ::= [#x1-#x8] | [#xB-#xC] | [#xE-#x1F] | [#x7F-#x84] | [#x86-#x9F]` // https://www.w3.org/TR/xml11/#charsets var Char = /[-\x09\x0A\x0D\x20-\x2C\x2E-\uD7FF\uE000-\uFFFD]/; // without \u10000-\uEFFFF if (UNICODE_SUPPORT) { // eslint-disable-next-line es5/no-unicode-code-point-escape Char = reg('[', chars(Char), '\\u{10000}-\\u{10FFFF}', ']'); } // Negation of Char: matches any character that is NOT a valid XML 1.0 Char. // Derived directly from the Char character class above (after the unicode-support extension). // XML 1.0 Char production [2]: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] // @see https://www.w3.org/TR/xml/#NT-Char var InvalidChar = new RegExp('[^' + chars(Char) + ']', UNICODE_SUPPORT ? 'u' : ''); var _SChar = /[\x20\x09\x0D\x0A]/; var SChar_s = chars(_SChar); // https://www.w3.org/TR/xml11/#NT-S // `[3] S ::= (#x20 | #x9 | #xD | #xA)+` var S = reg(_SChar, '+'); // optional whitespace described as `S?` in the grammar, // simplified to 0-n occurrences of the character class // instead of 0-1 occurrences of a non-capturing group around S var S_OPT = reg(_SChar, '*'); // https://www.w3.org/TR/xml11/#NT-NameStartChar // `[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]` var NameStartChar = /[:_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; // without \u10000-\uEFFFF if (UNICODE_SUPPORT) { // eslint-disable-next-line es5/no-unicode-code-point-escape NameStartChar = reg('[', chars(NameStartChar), '\\u{10000}-\\u{10FFFF}', ']'); } var NameStartChar_s = chars(NameStartChar); // https://www.w3.org/TR/xml11/#NT-NameChar // `[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]` var NameChar = reg('[', NameStartChar_s, chars(/[-.0-9\xB7]/), chars(/[\u0300-\u036F\u203F-\u2040]/), ']'); // https://www.w3.org/TR/xml11/#NT-Name // `[5] Name ::= NameStartChar (NameChar)*` var Name = reg(NameStartChar, NameChar, '*'); /* https://www.w3.org/TR/xml11/#NT-Names `[6] Names ::= Name (#x20 Name)*` */ // https://www.w3.org/TR/xml11/#NT-Nmtoken // `[7] Nmtoken ::= (NameChar)+` var Nmtoken = reg(NameChar, '+'); /* https://www.w3.org/TR/xml11/#NT-Nmtokens `[8] Nmtokens ::= Nmtoken (#x20 Nmtoken)*` var Nmtokens = reg(Nmtoken, regg(/\x20/, Nmtoken), '*'); */ // https://www.w3.org/TR/xml11/#NT-EntityRef // `[68] EntityRef ::= '&' Name ';'` [WFC: Entity Declared] [VC: Entity Declared] [WFC: Parsed Entity] [WFC: No Recursion] var EntityRef = reg('&', Name, ';'); // https://www.w3.org/TR/xml11/#NT-CharRef // `[66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'` [WFC: Legal Character] var CharRef = regg(/&#[0-9]+;|&#x[0-9a-fA-F]+;/); /* https://www.w3.org/TR/xml11/#NT-Reference - `[67] Reference ::= EntityRef | CharRef` - `[66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'` [WFC: Legal Character] - `[68] EntityRef ::= '&' Name ';'` [WFC: Entity Declared] [VC: Entity Declared] [WFC: Parsed Entity] [WFC: No Recursion] */ var Reference = regg(EntityRef, '|', CharRef); // https://www.w3.org/TR/xml11/#NT-PEReference // `[69] PEReference ::= '%' Name ';'` // [VC: Entity Declared] [WFC: No Recursion] [WFC: In DTD] var PEReference = reg('%', Name, ';'); // https://www.w3.org/TR/xml11/#NT-EntityValue // `[9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' | "'" ([^%&'] | PEReference | Reference)* "'"` var EntityValue = regg( reg('"', regg(/[^%&"]/, '|', PEReference, '|', Reference), '*', '"'), '|', reg("'", regg(/[^%&']/, '|', PEReference, '|', Reference), '*', "'") ); // https://www.w3.org/TR/xml11/#NT-AttValue // `[10] AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'"` var AttValue = regg('"', regg(/[^<&"]/, '|', Reference), '*', '"', '|', "'", regg(/[^<&']/, '|', Reference), '*', "'"); // https://www.w3.org/TR/xml-names/#ns-decl // https://www.w3.org/TR/xml-names/#ns-qualnames // NameStartChar without ":" var NCNameStartChar = chars_without(NameStartChar, ':'); // https://www.w3.org/TR/xml-names/#orphans // `[5] NCNameChar ::= NameChar - ':'` // An XML NameChar, minus the ":" var NCNameChar = chars_without(NameChar, ':'); // https://www.w3.org/TR/xml-names/#NT-NCName // `[4] NCName ::= Name - (Char* ':' Char*)` // An XML Name, minus the ":" var NCName = reg(NCNameStartChar, NCNameChar, '*'); /** https://www.w3.org/TR/xml-names/#ns-qualnames ``` [7] QName ::= PrefixedName | UnprefixedName === (NCName ':' NCName) | NCName === NCName (':' NCName)? [8] PrefixedName ::= Prefix ':' LocalPart === NCName ':' NCName [9] UnprefixedName ::= LocalPart === NCName [10] Prefix ::= NCName [11] LocalPart ::= NCName ``` */ var QName = reg(NCName, regg(':', NCName), '?'); var QName_exact = reg('^', QName, '$'); var QName_group = reg('(', QName, ')'); // https://www.w3.org/TR/xml11/#NT-SystemLiteral // `[11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")` var SystemLiteral = regg(/"[^"]*"|'[^']*'/); /* https://www.w3.org/TR/xml11/#NT-PI ``` [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) [16] PI ::= '' Char*)))? '?>' ``` target /xml/i is not excluded! */ var PI = reg(/^<\?/, '(', Name, ')', regg(S, '(', Char, '*?)'), '?', /\?>/); // https://www.w3.org/TR/xml11/#NT-PubidChar // `[13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]` var PubidChar = /[\x20\x0D\x0Aa-zA-Z0-9-'()+,./:=?;!*#@$_%]/; // https://www.w3.org/TR/xml11/#NT-PubidLiteral // `[12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"` var PubidLiteral = regg('"', PubidChar, '*"', '|', "'", chars_without(PubidChar, "'"), "*'"); // https://www.w3.org/TR/xml11/#NT-CharData // `[14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)` var COMMENT_START = ''; // https://www.w3.org/TR/xml11/#NT-Comment // `[15] Comment ::= ''` var Comment = reg(COMMENT_START, regg(chars_without(Char, '-'), '|', reg('-', chars_without(Char, '-'))), '*', COMMENT_END); var PCDATA = '#PCDATA'; // https://www.w3.org/TR/xml11/#NT-Mixed // `[51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')'` // https://www.w3.org/TR/xml-names/#NT-Mixed // `[51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? QName)* S? ')*' | '(' S? '#PCDATA' S? ')'` // [VC: Proper Group/PE Nesting] [VC: No Duplicate Types] var Mixed = regg( reg(/\(/, S_OPT, PCDATA, regg(S_OPT, /\|/, S_OPT, QName), '*', S_OPT, /\)\*/), '|', reg(/\(/, S_OPT, PCDATA, S_OPT, /\)/) ); var _children_quantity = /[?*+]?/; /* `[49] choice ::= '(' S? cp ( S? '|' S? cp )+ S? ')'` [VC: Proper Group/PE Nesting] `[50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'` [VC: Proper Group/PE Nesting] simplification to solve circular referencing, but doesn't check validity constraint "Proper Group/PE Nesting" var _choice_or_seq = reg('[', NameChar_s, SChar_s, chars(_children_quantity), '()|,]*'); ``` [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')? === (Name | '(' S? cp ( S? '|' S? cp )+ S? ')' | '(' S? cp ( S? ',' S? cp )* S? ')') ('?' | '*' | '+')? !== (Name | [_choice_or_seq]*) ('?' | '*' | '+')? ``` simplification to solve circular referencing, but doesn't check validity constraint "Proper Group/PE Nesting" var cp = reg(regg(Name, '|', _choice_or_seq), _children_quantity); */ /* Inefficient regular expression (High) This part of the regular expression may cause exponential backtracking on strings starting with '(|' and containing many repetitions of '|'. https://github.com/xmldom/xmldom/security/code-scanning/91 var choice = regg(/\(/, S_OPT, cp, regg(S_OPT, /\|/, S_OPT, cp), '+', S_OPT, /\)/); */ /* Inefficient regular expression (High) This part of the regular expression may cause exponential backtracking on strings starting with '(,' and containing many repetitions of ','. https://github.com/xmldom/xmldom/security/code-scanning/92 var seq = regg(/\(/, S_OPT, cp, regg(S_OPT, /,/, S_OPT, cp), '*', S_OPT, /\)/); */ // `[47] children ::= (choice | seq) ('?' | '*' | '+')?` // simplification to solve circular referencing, but doesn't check validity constraint "Proper Group/PE Nesting" var children = reg(/\([^>]+\)/, _children_quantity /*regg(choice, '|', seq), _children_quantity*/); // https://www.w3.org/TR/xml11/#NT-contentspec // `[46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children` var contentspec = regg('EMPTY', '|', 'ANY', '|', Mixed, '|', children); var ELEMENTDECL_START = ''` // https://www.w3.org/TR/xml-names/#NT-elementdecl // `[17] elementdecl ::= ''` // because of https://www.w3.org/TR/xml11/#NT-PEReference // since xmldom is not supporting replacements of PEReferences in the DTD // this also supports PEReference in the possible places var elementdecl = reg(ELEMENTDECL_START, S, regg(QName, '|', PEReference), S, regg(contentspec, '|', PEReference), S_OPT, '>'); // https://www.w3.org/TR/xml11/#NT-NotationType // `[58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'` // [VC: Notation Attributes] [VC: One Notation Per Element Type] [VC: No Notation on Empty Element] [VC: No Duplicate Tokens] var NotationType = reg('NOTATION', S, /\(/, S_OPT, Name, regg(S_OPT, /\|/, S_OPT, Name), '*', S_OPT, /\)/); // https://www.w3.org/TR/xml11/#NT-Enumeration // `[59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'` // [VC: Enumeration] [VC: No Duplicate Tokens] var Enumeration = reg(/\(/, S_OPT, Nmtoken, regg(S_OPT, /\|/, S_OPT, Nmtoken), '*', S_OPT, /\)/); // https://www.w3.org/TR/xml11/#NT-EnumeratedType // `[57] EnumeratedType ::= NotationType | Enumeration` var EnumeratedType = regg(NotationType, '|', Enumeration); /* ``` [55] StringType ::= 'CDATA' [56] TokenizedType ::= 'ID' [VC: ID] [VC: One ID per Element Type] [VC: ID Attribute Default] | 'IDREF' [VC: IDREF] | 'IDREFS' [VC: IDREF] | 'ENTITY' [VC: Entity Name] | 'ENTITIES' [VC: Entity Name] | 'NMTOKEN' [VC: Name Token] | 'NMTOKENS' [VC: Name Token] [54] AttType ::= StringType | TokenizedType | EnumeratedType ```*/ var AttType = regg(/CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS/, '|', EnumeratedType); // `[60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)` // [WFC: No < in Attribute Values] [WFC: No External Entity References] // [VC: Fixed Attribute Default] [VC: Required Attribute] [VC: Attribute Default Value Syntactically Correct] var DefaultDecl = regg(/#REQUIRED|#IMPLIED/, '|', regg(regg('#FIXED', S), '?', AttValue)); // https://www.w3.org/TR/xml11/#NT-AttDef // [53] AttDef ::= S Name S AttType S DefaultDecl // https://www.w3.org/TR/xml-names/#NT-AttDef // [1] NSAttName ::= PrefixedAttName | DefaultAttName // [2] PrefixedAttName ::= 'xmlns:' NCName [NSC: Reserved Prefixes and Namespace Names] // [3] DefaultAttName ::= 'xmlns' // [21] AttDef ::= S (QName | NSAttName) S AttType S DefaultDecl // === S Name S AttType S DefaultDecl // xmldom is not distinguishing between QName and NSAttName on this level // to support XML without namespaces in DTD we can not restrict it to QName var AttDef = regg(S, Name, S, AttType, S, DefaultDecl); var ATTLIST_DECL_START = ''` // https://www.w3.org/TR/xml-names/#NT-AttlistDecl // `[20] AttlistDecl ::= ''` // to support XML without namespaces in DTD we can not restrict it to QName var AttlistDecl = reg(ATTLIST_DECL_START, S, Name, AttDef, '*', S_OPT, '>'); // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#about:legacy-compat var ABOUT_LEGACY_COMPAT = 'about:legacy-compat'; var ABOUT_LEGACY_COMPAT_SystemLiteral = regg('"' + ABOUT_LEGACY_COMPAT + '"', '|', "'" + ABOUT_LEGACY_COMPAT + "'"); var SYSTEM = 'SYSTEM'; var PUBLIC = 'PUBLIC'; // https://www.w3.org/TR/xml11/#NT-ExternalID // `[75] ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral` var ExternalID = regg(regg(SYSTEM, S, SystemLiteral), '|', regg(PUBLIC, S, PubidLiteral, S, SystemLiteral)); var ExternalID_match = reg( '^', regg( regg(SYSTEM, S, '(?', SystemLiteral, ')'), '|', regg(PUBLIC, S, '(?', PubidLiteral, ')', S, '(?', SystemLiteral, ')') ) ); // Full-string anchored matcher for requireWellFormed serializer checks // https://w3c.github.io/DOM-Parsing/#xml-serializing-a-document-node var PubidLiteral_match = reg('^', PubidLiteral, '$'); // Full-string anchored matcher for requireWellFormed serializer checks // https://w3c.github.io/DOM-Parsing/#xml-serializing-a-document-node var SystemLiteral_match = reg('^', SystemLiteral, '$'); // https://www.w3.org/TR/xml11/#NT-NDataDecl // `[76] NDataDecl ::= S 'NDATA' S Name` [VC: Notation Declared] var NDataDecl = regg(S, 'NDATA', S, Name); // https://www.w3.org/TR/xml11/#NT-EntityDef // `[73] EntityDef ::= EntityValue | (ExternalID NDataDecl?)` var EntityDef = regg(EntityValue, '|', regg(ExternalID, NDataDecl, '?')); var ENTITY_DECL_START = ''` var GEDecl = reg(ENTITY_DECL_START, S, Name, S, EntityDef, S_OPT, '>'); // https://www.w3.org/TR/xml11/#NT-PEDef // `[74] PEDef ::= EntityValue | ExternalID` var PEDef = regg(EntityValue, '|', ExternalID); // https://www.w3.org/TR/xml11/#NT-PEDecl // `[72] PEDecl ::= ''` var PEDecl = reg(ENTITY_DECL_START, S, '%', S, Name, S, PEDef, S_OPT, '>'); // https://www.w3.org/TR/xml11/#NT-EntityDecl // `[70] EntityDecl ::= GEDecl | PEDecl` var EntityDecl = regg(GEDecl, '|', PEDecl); // https://www.w3.org/TR/xml11/#NT-PublicID // `[83] PublicID ::= 'PUBLIC' S PubidLiteral` var PublicID = reg(PUBLIC, S, PubidLiteral); // https://www.w3.org/TR/xml11/#NT-NotationDecl // `[82] NotationDecl ::= ''` [VC: Unique Notation Name] var NotationDecl = reg(''); // https://www.w3.org/TR/xml11/#NT-Eq // `[25] Eq ::= S? '=' S?` var Eq = reg(S_OPT, '=', S_OPT); // https://www.w3.org/TR/xml/#NT-VersionNum // `[26] VersionNum ::= '1.' [0-9]+` // https://www.w3.org/TR/xml11/#NT-VersionNum // `[26] VersionNum ::= '1.1'` var VersionNum = /1[.]\d+/; // https://www.w3.org/TR/xml11/#NT-VersionInfo // `[24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')` var VersionInfo = reg(S, 'version', Eq, regg("'", VersionNum, "'", '|', '"', VersionNum, '"')); // https://www.w3.org/TR/xml11/#NT-EncName // `[81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*` var EncName = /[A-Za-z][-A-Za-z0-9._]*/; // https://www.w3.org/TR/xml11/#NT-EncDecl // `[80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )` var EncodingDecl = regg(S, 'encoding', Eq, regg('"', EncName, '"', '|', "'", EncName, "'")); // https://www.w3.org/TR/xml11/#NT-SDDecl // `[32] SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))` var SDDecl = regg(S, 'standalone', Eq, regg("'", regg('yes', '|', 'no'), "'", '|', '"', regg('yes', '|', 'no'), '"')); // https://www.w3.org/TR/xml11/#NT-XMLDecl // [23] XMLDecl ::= '' var XMLDecl = reg(/^<\?xml/, VersionInfo, EncodingDecl, '?', SDDecl, '?', S_OPT, /\?>/); /* https://www.w3.org/TR/xml/#NT-markupdecl https://www.w3.org/TR/xml11/#NT-markupdecl `[29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment` var markupdecl = regg(elementdecl, '|', AttlistDecl, '|', EntityDecl, '|', NotationDecl, '|', PI_unsafe, '|', Comment); */ /* https://www.w3.org/TR/xml-names/#NT-doctypedecl `[28a] DeclSep ::= PEReference | S` https://www.w3.org/TR/xml11/#NT-intSubset ``` [28b] intSubset ::= (markupdecl | DeclSep)* === (markupdecl | PEReference | S)* ``` [WFC: PE Between Declarations] var intSubset = reg(regg(markupdecl, '|', PEReference, '|', S), '*'); */ var DOCTYPE_DECL_START = ''` https://www.afterwardsw3.org/TR/xml-names/#NT-doctypedecl `[16] doctypedecl ::= ''` var doctypedecl = reg(''); */ var CDATA_START = ''; var CDStart = //; var CData = reg(Char, '*?', CDEnd); /* https://www.w3.org/TR/xml/#dt-cdsection `[18] CDSect ::= CDStart CData CDEnd` `[19] CDStart ::= '' Char*))` `[21] CDEnd ::= ']]>'` */ var CDSect = reg(CDStart, CData); // unit tested exports.chars = chars; exports.chars_without = chars_without; exports.detectUnicodeSupport = detectUnicodeSupport; exports.reg = reg; exports.regg = regg; exports.ABOUT_LEGACY_COMPAT = ABOUT_LEGACY_COMPAT; exports.ABOUT_LEGACY_COMPAT_SystemLiteral = ABOUT_LEGACY_COMPAT_SystemLiteral; exports.AttlistDecl = AttlistDecl; exports.CDATA_START = CDATA_START; exports.CDATA_END = CDATA_END; exports.CDSect = CDSect; exports.Char = Char; exports.Comment = Comment; exports.COMMENT_START = COMMENT_START; exports.COMMENT_END = COMMENT_END; exports.DOCTYPE_DECL_START = DOCTYPE_DECL_START; exports.elementdecl = elementdecl; exports.EntityDecl = EntityDecl; exports.EntityValue = EntityValue; exports.ExternalID = ExternalID; exports.ExternalID_match = ExternalID_match; exports.Name = Name; exports.NotationDecl = NotationDecl; exports.Reference = Reference; exports.PEReference = PEReference; exports.PI = PI; exports.PUBLIC = PUBLIC; exports.PubidLiteral = PubidLiteral; exports.PubidLiteral_match = PubidLiteral_match; exports.QName = QName; exports.QName_exact = QName_exact; exports.QName_group = QName_group; exports.S = S; exports.SChar_s = SChar_s; exports.S_OPT = S_OPT; exports.SYSTEM = SYSTEM; exports.SystemLiteral = SystemLiteral; exports.SystemLiteral_match = SystemLiteral_match; exports.InvalidChar = InvalidChar; exports.UNICODE_REPLACEMENT_CHARACTER = UNICODE_REPLACEMENT_CHARACTER; exports.UNICODE_SUPPORT = UNICODE_SUPPORT; exports.XMLDecl = XMLDecl; /***/ }), /***/ 8351: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var __webpack_unused_export__; var conventions = __nccwpck_require__(7855); __webpack_unused_export__ = conventions.assign; __webpack_unused_export__ = conventions.hasDefaultHTMLNamespace; __webpack_unused_export__ = conventions.isHTMLMimeType; __webpack_unused_export__ = conventions.isValidMimeType; __webpack_unused_export__ = conventions.MIME_TYPE; __webpack_unused_export__ = conventions.NAMESPACE; var errors = __nccwpck_require__(7368); __webpack_unused_export__ = errors.DOMException; __webpack_unused_export__ = errors.DOMExceptionName; __webpack_unused_export__ = errors.ExceptionCode; __webpack_unused_export__ = errors.ParseError; var dom = __nccwpck_require__(7311); __webpack_unused_export__ = dom.Attr; __webpack_unused_export__ = dom.CDATASection; __webpack_unused_export__ = dom.CharacterData; __webpack_unused_export__ = dom.Comment; __webpack_unused_export__ = dom.Document; __webpack_unused_export__ = dom.DocumentFragment; __webpack_unused_export__ = dom.DocumentType; __webpack_unused_export__ = dom.DOMImplementation; __webpack_unused_export__ = dom.Element; __webpack_unused_export__ = dom.Entity; __webpack_unused_export__ = dom.EntityReference; __webpack_unused_export__ = dom.LiveNodeList; __webpack_unused_export__ = dom.NamedNodeMap; __webpack_unused_export__ = dom.Node; __webpack_unused_export__ = dom.NodeList; __webpack_unused_export__ = dom.Notation; __webpack_unused_export__ = dom.ProcessingInstruction; __webpack_unused_export__ = dom.Text; __webpack_unused_export__ = dom.XMLSerializer; var domParser = __nccwpck_require__(4847); exports.S4 = domParser.DOMParser; __webpack_unused_export__ = domParser.normalizeLineEndings; __webpack_unused_export__ = domParser.onErrorStopParsing; __webpack_unused_export__ = domParser.onWarningStopParsing; /***/ }), /***/ 1995: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var conventions = __nccwpck_require__(7855); var g = __nccwpck_require__(2062); var errors = __nccwpck_require__(7368); var isHTMLEscapableRawTextElement = conventions.isHTMLEscapableRawTextElement; var isHTMLMimeType = conventions.isHTMLMimeType; var isHTMLRawTextElement = conventions.isHTMLRawTextElement; var hasOwn = conventions.hasOwn; var NAMESPACE = conventions.NAMESPACE; var ParseError = errors.ParseError; var DOMException = errors.DOMException; //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE var S_TAG = 0; //tag name offerring var S_ATTR = 1; //attr name offerring var S_ATTR_SPACE = 2; //attr name end and space offer var S_EQ = 3; //=space? var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only) var S_ATTR_END = 5; //attr value end and no space(quot end) var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer) var S_TAG_CLOSE = 7; //closed el function XMLReader() {} XMLReader.prototype = { parse: function (source, defaultNSMap, entityMap) { var domBuilder = this.domBuilder; domBuilder.startDocument(); _copy(defaultNSMap, (defaultNSMap = Object.create(null))); parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler); domBuilder.endDocument(); }, }; /** * Detecting everything that might be a reference, * including those without ending `;`, since those are allowed in HTML. * The entityReplacer takes care of verifying and transforming each occurrence, * and reports to the errorHandler on those that are not OK, * depending on the context. */ var ENTITY_REG = /&#?\w+;?/g; function parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) { var isHTML = isHTMLMimeType(domBuilder.mimeType); if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) { errorHandler.warning('Unicode replacement character detected, source encoding issues?'); } function fixedFromCharCode(code) { // String.prototype.fromCharCode does not supports // > 2 bytes unicode chars directly if (code > 0xffff) { code -= 0x10000; var surrogate1 = 0xd800 + (code >> 10), surrogate2 = 0xdc00 + (code & 0x3ff); return String.fromCharCode(surrogate1, surrogate2); } else { return String.fromCharCode(code); } } function entityReplacer(a) { var complete = a[a.length - 1] === ';' ? a : a + ';'; if (!isHTML && complete !== a) { errorHandler.error('EntityRef: expecting ;'); return a; } var match = g.Reference.exec(complete); if (!match || match[0].length !== complete.length) { errorHandler.error('entity not matching Reference production: ' + a); return a; } var k = complete.slice(1, -1); if (hasOwn(entityMap, k)) { return entityMap[k]; } else if (k.charAt(0) === '#') { return fixedFromCharCode(parseInt(k.substring(1).replace('x', '0x'))); } else { errorHandler.error('entity not found:' + a); return a; } } function appendText(end) { //has some bugs if (end > start) { var xt = source.substring(start, end).replace(ENTITY_REG, entityReplacer); locator && position(start); domBuilder.characters(xt, 0, end - start); start = end; } } var lineStart = 0; var lineEnd = 0; var linePattern = /\r\n?|\n|$/g; var locator = domBuilder.locator; function position(p, m) { while (p >= lineEnd && (m = linePattern.exec(source))) { lineStart = lineEnd; lineEnd = m.index + m[0].length; locator.lineNumber++; } locator.columnNumber = p - lineStart + 1; } var parseStack = [{ currentNSMap: defaultNSMapCopy }]; var unclosedTags = []; var start = 0; while (true) { try { var tagStart = source.indexOf('<', start); if (tagStart < 0) { if (!isHTML && unclosedTags.length > 0) { return errorHandler.fatalError('unclosed xml tag(s): ' + unclosedTags.join(', ')); } if (!source.substring(start).match(/^\s*$/)) { var doc = domBuilder.doc; var text = doc.createTextNode(source.substring(start)); if (doc.documentElement) { return errorHandler.error('Extra content at the end of the document'); } doc.appendChild(text); domBuilder.currentElement = text; } return; } if (tagStart > start) { var fromSource = source.substring(start, tagStart); if (!isHTML && unclosedTags.length === 0) { fromSource = fromSource.replace(new RegExp(g.S_OPT.source, 'g'), ''); fromSource && errorHandler.error("Unexpected content outside root element: '" + fromSource + "'"); } appendText(tagStart); } switch (source.charAt(tagStart + 1)) { case '/': var end = source.indexOf('>', tagStart + 2); var tagNameRaw = source.substring(tagStart + 2, end > 0 ? end : undefined); if (!tagNameRaw) { return errorHandler.fatalError('end tag name missing'); } var tagNameMatch = end > 0 && g.reg('^', g.QName_group, g.S_OPT, '$').exec(tagNameRaw); if (!tagNameMatch) { return errorHandler.fatalError('end tag name contains invalid characters: "' + tagNameRaw + '"'); } if (!domBuilder.currentElement && !domBuilder.doc.documentElement) { // not enough information to provide a helpful error message, // but parsing will throw since there is no root element return; } var currentTagName = unclosedTags[unclosedTags.length - 1] || domBuilder.currentElement.tagName || domBuilder.doc.documentElement.tagName || ''; if (currentTagName !== tagNameMatch[1]) { var tagNameLower = tagNameMatch[1].toLowerCase(); if (!isHTML || currentTagName.toLowerCase() !== tagNameLower) { return errorHandler.fatalError('Opening and ending tag mismatch: "' + currentTagName + '" != "' + tagNameRaw + '"'); } } var config = parseStack.pop(); unclosedTags.pop(); var localNSMap = config.localNSMap; domBuilder.endElement(config.uri, config.localName, currentTagName); if (localNSMap) { for (var prefix in localNSMap) { if (hasOwn(localNSMap, prefix)) { domBuilder.endPrefixMapping(prefix); } } } end++; break; // end element case '?': // locator && position(tagStart); end = parseProcessingInstruction(source, tagStart, domBuilder, errorHandler); break; case '!': // start) { start = end; } else { //Possible sax fallback here, risk of positional error appendText(Math.max(tagStart, start) + 1); } } } function copyLocator(f, t) { t.lineNumber = f.lineNumber; t.columnNumber = f.columnNumber; return t; } /** * @returns * end of the elementStartPart(end of elementEndPart for selfClosed el) * @see {@link #appendElement} */ function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) { /** * @param {string} qname * @param {string} value * @param {number} startIndex */ function addAttribute(qname, value, startIndex) { if (hasOwn(el.attributeNames, qname)) { return errorHandler.fatalError('Attribute ' + qname + ' redefined'); } if (!isHTML && value.indexOf('<') >= 0) { return errorHandler.fatalError("Unescaped '<' not allowed in attributes values"); } el.addValue( qname, // @see https://www.w3.org/TR/xml/#AVNormalize // since the xmldom sax parser does not "interpret" DTD the following is not implemented: // - recursive replacement of (DTD) entity references // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA value.replace(/[\t\n\r]/g, ' ').replace(ENTITY_REG, entityReplacer), startIndex ); } var attrName; var value; var p = ++start; var s = S_TAG; //status while (true) { var c = source.charAt(p); switch (c) { case '=': if (s === S_ATTR) { //attrName attrName = source.slice(start, p); s = S_EQ; } else if (s === S_ATTR_SPACE) { s = S_EQ; } else { //fatalError: equal must after attrName or space after attrName throw new Error('attribute equal must after attrName'); // No known test case } break; case "'": case '"': if ( s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE ) { //equal if (s === S_ATTR) { errorHandler.warning('attribute value must after "="'); attrName = source.slice(start, p); } start = p + 1; p = source.indexOf(c, start); if (p > 0) { value = source.slice(start, p); addAttribute(attrName, value, start - 1); s = S_ATTR_END; } else { //fatalError: no end quot match throw new Error("attribute value no end '" + c + "' match"); } } else if (s == S_ATTR_NOQUOT_VALUE) { value = source.slice(start, p); addAttribute(attrName, value, start); errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!'); start = p + 1; s = S_ATTR_END; } else { //fatalError: no equal before throw new Error('attribute value must after "="'); // No known test case } break; case '/': switch (s) { case S_TAG: el.setTagName(source.slice(start, p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: s = S_TAG_CLOSE; el.closed = true; case S_ATTR_NOQUOT_VALUE: case S_ATTR: break; case S_ATTR_SPACE: el.closed = true; break; //case S_EQ: default: throw new Error("attribute invalid close char('/')"); // No known test case } break; case '': //end document errorHandler.error('unexpected end of input'); if (s == S_TAG) { el.setTagName(source.slice(start, p)); } return p; case '>': switch (s) { case S_TAG: el.setTagName(source.slice(start, p)); case S_ATTR_END: case S_TAG_SPACE: case S_TAG_CLOSE: break; //normal case S_ATTR_NOQUOT_VALUE: //Compatible state case S_ATTR: value = source.slice(start, p); if (value.slice(-1) === '/') { el.closed = true; value = value.slice(0, -1); } case S_ATTR_SPACE: if (s === S_ATTR_SPACE) { value = attrName; } if (s == S_ATTR_NOQUOT_VALUE) { errorHandler.warning('attribute "' + value + '" missed quot(")!'); addAttribute(attrName, value, start); } else { if (!isHTML) { errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!'); } addAttribute(value, value, start); } break; case S_EQ: if (!isHTML) { return errorHandler.fatalError('AttValue: \' or " expected'); } } return p; /*xml space '\x20' | #x9 | #xD | #xA; */ case '\u0080': c = ' '; default: if (c <= ' ') { //space switch (s) { case S_TAG: el.setTagName(source.slice(start, p)); //tagName s = S_TAG_SPACE; break; case S_ATTR: attrName = source.slice(start, p); s = S_ATTR_SPACE; break; case S_ATTR_NOQUOT_VALUE: var value = source.slice(start, p); errorHandler.warning('attribute "' + value + '" missed quot(")!!'); addAttribute(attrName, value, start); case S_ATTR_END: s = S_TAG_SPACE; break; //case S_TAG_SPACE: //case S_EQ: //case S_ATTR_SPACE: // void();break; //case S_TAG_CLOSE: //ignore warning } } else { //not space //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE switch (s) { //case S_TAG:void();break; //case S_ATTR:void();break; //case S_ATTR_NOQUOT_VALUE:void();break; case S_ATTR_SPACE: if (!isHTML) { errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!'); } addAttribute(attrName, attrName, start); start = p; s = S_ATTR; break; case S_ATTR_END: errorHandler.warning('attribute space is required"' + attrName + '"!!'); case S_TAG_SPACE: s = S_ATTR; start = p; break; case S_EQ: s = S_ATTR_NOQUOT_VALUE; start = p; break; case S_TAG_CLOSE: throw new Error("elements closed character '/' and '>' must be connected to"); } } } //end outer switch p++; } } /** * @returns * `true` if a new namespace has been defined. */ function appendElement(el, domBuilder, currentNSMap) { var tagName = el.tagName; var localNSMap = null; var i = el.length; while (i--) { var a = el[i]; var qName = a.qName; var value = a.value; var nsp = qName.indexOf(':'); if (nsp > 0) { var prefix = (a.prefix = qName.slice(0, nsp)); var localName = qName.slice(nsp + 1); var nsPrefix = prefix === 'xmlns' && localName; } else { localName = qName; prefix = null; nsPrefix = qName === 'xmlns' && ''; } //can not set prefix,because prefix !== '' a.localName = localName; //prefix == null for no ns prefix attribute if (nsPrefix !== false) { //hack!! if (localNSMap == null) { localNSMap = Object.create(null); _copy(currentNSMap, (currentNSMap = Object.create(null))); } currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; a.uri = NAMESPACE.XMLNS; domBuilder.startPrefixMapping(nsPrefix, value); } } var i = el.length; while (i--) { a = el[i]; if (a.prefix) { //no prefix attribute has no namespace if (a.prefix === 'xml') { a.uri = NAMESPACE.XML; } if (a.prefix !== 'xmlns') { a.uri = currentNSMap[a.prefix]; } } } var nsp = tagName.indexOf(':'); if (nsp > 0) { prefix = el.prefix = tagName.slice(0, nsp); localName = el.localName = tagName.slice(nsp + 1); } else { prefix = null; //important!! localName = el.localName = tagName; } //no prefix element has default namespace var ns = (el.uri = currentNSMap[prefix || '']); domBuilder.startElement(ns, localName, tagName, el); //endPrefixMapping and startPrefixMapping have not any help for dom builder //localNSMap = null if (el.closed) { domBuilder.endElement(ns, localName, tagName); if (localNSMap) { for (prefix in localNSMap) { if (hasOwn(localNSMap, prefix)) { domBuilder.endPrefixMapping(prefix); } } } } else { el.currentNSMap = currentNSMap; el.localNSMap = localNSMap; //parseStack.push(el); return true; } } function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) { // https://html.spec.whatwg.org/#raw-text-elements // https://html.spec.whatwg.org/#escapable-raw-text-elements // https://html.spec.whatwg.org/#cdata-rcdata-restrictions:raw-text-elements // TODO: https://html.spec.whatwg.org/#cdata-rcdata-restrictions var isEscapableRaw = isHTMLEscapableRawTextElement(tagName); if (isEscapableRaw || isHTMLRawTextElement(tagName)) { var elEndStart = source.indexOf('', elStartEnd); var text = source.substring(elStartEnd + 1, elEndStart); if (isEscapableRaw) { text = text.replace(ENTITY_REG, entityReplacer); } domBuilder.characters(text, 0, text.length); return elEndStart; } return elStartEnd + 1; } function _copy(source, target) { for (var n in source) { if (hasOwn(source, n)) { target[n] = source[n]; } } } /** * @typedef ParseUtils * @property {function(relativeIndex: number?): string | undefined} char * Provides look ahead access to a singe character relative to the current index. * @property {function(): number} getIndex * Provides read-only access to the current index. * @property {function(reg: RegExp): string | null} getMatch * Applies the provided regular expression enforcing that it starts at the current index and * returns the complete matching string, * and moves the current index by the length of the matching string. * @property {function(): string} getSource * Provides read-only access to the complete source. * @property {function(places: number?): void} skip * moves the current index by places (defaults to 1) * @property {function(): number} skipBlanks * Moves the current index by the amount of white space that directly follows the current index * and returns the amount of whitespace chars skipped (0..n), * or -1 if the end of the source was reached. * @property {function(): string} substringFromIndex * creates a substring from the current index to the end of `source` * @property {function(compareWith: string): boolean} substringStartsWith * Checks if `source` contains `compareWith`, starting from the current index. * @property {function(compareWith: string): boolean} substringStartsWithCaseInsensitive * Checks if `source` contains `compareWith`, starting from the current index, * comparing the upper case of both sides. * @see {@link parseUtils} */ /** * A temporary scope for parsing and look ahead operations in `source`, * starting from index `start`. * * Some operations move the current index by a number of positions, * after which `getIndex` returns the new index. * * @param {string} source * @param {number} start * @returns {ParseUtils} */ function parseUtils(source, start) { var index = start; function char(n) { n = n || 0; return source.charAt(index + n); } function skip(n) { n = n || 1; index += n; } function skipBlanks() { var blanks = 0; while (index < source.length) { var c = char(); if (c !== ' ' && c !== '\n' && c !== '\t' && c !== '\r') { return blanks; } blanks++; skip(); } return -1; } function substringFromIndex() { return source.substring(index); } function substringStartsWith(text) { return source.substring(index, index + text.length) === text; } function substringStartsWithCaseInsensitive(text) { return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase(); } function getMatch(args) { var expr = g.reg('^', args); var match = expr.exec(substringFromIndex()); if (match) { skip(match[0].length); return match[0]; } return null; } return { char: char, getIndex: function () { return index; }, getMatch: getMatch, getSource: function () { return source; }, skip: skip, skipBlanks: skipBlanks, substringFromIndex: substringFromIndex, substringStartsWith: substringStartsWith, substringStartsWithCaseInsensitive: substringStartsWithCaseInsensitive, }; } /** * @param {ParseUtils} p * @param {DOMHandler} errorHandler * @returns {string} */ function parseDoctypeInternalSubset(p, errorHandler) { /** * @param {ParseUtils} p * @param {DOMHandler} errorHandler * @returns {string} */ function parsePI(p, errorHandler) { var match = g.PI.exec(p.substringFromIndex()); if (!match) { return errorHandler.fatalError('processing instruction is not well-formed at position ' + p.getIndex()); } if (match[1].toLowerCase() === 'xml') { return errorHandler.fatalError( 'xml declaration is only allowed at the start of the document, but found at position ' + p.getIndex() ); } p.skip(match[0].length); return match[0]; } // Parse internal subset var source = p.getSource(); if (p.char() === '[') { p.skip(1); var intSubsetStart = p.getIndex(); while (p.getIndex() < source.length) { p.skipBlanks(); if (p.char() === ']') { var internalSubset = source.substring(intSubsetStart, p.getIndex()); p.skip(1); return internalSubset; } var current = null; // Only in external subset // if (char() === '<' && char(1) === '!' && char(2) === '[') { // parseConditionalSections(p, errorHandler); // } else if (p.char() === '<' && p.char(1) === '!') { switch (p.char(2)) { case 'E': // ELEMENT | ENTITY if (p.char(3) === 'L') { current = p.getMatch(g.elementdecl); } else if (p.char(3) === 'N') { current = p.getMatch(g.EntityDecl); } break; case 'A': // ATTRIBUTE current = p.getMatch(g.AttlistDecl); break; case 'N': // NOTATION current = p.getMatch(g.NotationDecl); break; case '-': // COMMENT current = p.getMatch(g.Comment); break; } } else if (p.char() === '<' && p.char(1) === '?') { current = parsePI(p, errorHandler); } else if (p.char() === '%') { current = p.getMatch(g.PEReference); } else { return errorHandler.fatalError('Error detected in Markup declaration'); } if (!current) { return errorHandler.fatalError('Error in internal subset at position ' + p.getIndex()); } } return errorHandler.fatalError('doctype internal subset is not well-formed, missing ]'); } } /** * Called when the parser encounters an element starting with '') { return errorHandler.fatalError('doctype not terminated with > at position ' + p.getIndex()); } p.skip(1); domBuilder.startDTD(doctype.name, doctype.publicId, doctype.systemId, doctype.internalSubset); domBuilder.endDTD(); return p.getIndex(); } default: return errorHandler.fatalError('Not well-formed XML starting with " 0) { return errorHandler.fatalError( 'processing instruction at position ' + start + ' is an xml declaration which is only at the start of the document' ); } if (!g.XMLDecl.test(source.substring(start))) { return errorHandler.fatalError('xml declaration is not well-formed'); } } domBuilder.processingInstruction(match[1], match[2]); return start + match[0].length; } function ElementAttributes() { this.attributeNames = Object.create(null); } ElementAttributes.prototype = { setTagName: function (tagName) { if (!g.QName_exact.test(tagName)) { throw new Error('invalid tagName:' + tagName); } this.tagName = tagName; }, addValue: function (qName, value, offset) { if (!g.QName_exact.test(qName)) { throw new Error('invalid attribute:' + qName); } this.attributeNames[qName] = this.length; this[this.length++] = { qName: qName, value: value, offset: offset }; }, length: 0, getLocalName: function (i) { return this[i].localName; }, getLocator: function (i) { return this[i].locator; }, getQName: function (i) { return this[i].qName; }, getURI: function (i) { return this[i].uri; }, getValue: function (i) { return this[i].value; }, // ,getIndex:function(uri, localName)){ // if(localName){ // // }else{ // var qName = uri // } // }, // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))}, // getType:function(uri,localName){} // getType:function(i){}, }; exports.XMLReader = XMLReader; exports.parseUtils = parseUtils; exports.parseDoctypeCommentOrCData = parseDoctypeCommentOrCData; /***/ }), /***/ 7413: /***/ ((module, exports, __nccwpck_require__) => { /** * @author Toru Nagashima * See LICENSE file in root directory for full license. */ Object.defineProperty(exports, "__esModule", ({ value: true })); var eventTargetShim = __nccwpck_require__(6577); /** * The signal class. * @see https://dom.spec.whatwg.org/#abortsignal */ class AbortSignal extends eventTargetShim.EventTarget { /** * AbortSignal cannot be constructed directly. */ constructor() { super(); throw new TypeError("AbortSignal cannot be constructed directly"); } /** * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. */ get aborted() { const aborted = abortedFlags.get(this); if (typeof aborted !== "boolean") { throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); } return aborted; } } eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); /** * Create an AbortSignal object. */ function createAbortSignal() { const signal = Object.create(AbortSignal.prototype); eventTargetShim.EventTarget.call(signal); abortedFlags.set(signal, false); return signal; } /** * Abort a given signal. */ function abortSignal(signal) { if (abortedFlags.get(signal) !== false) { return; } abortedFlags.set(signal, true); signal.dispatchEvent({ type: "abort" }); } /** * Aborted flag for each instances. */ const abortedFlags = new WeakMap(); // Properties should be enumerable. Object.defineProperties(AbortSignal.prototype, { aborted: { enumerable: true }, }); // `toString()` should return `"[object AbortSignal]"` if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { configurable: true, value: "AbortSignal", }); } /** * The AbortController. * @see https://dom.spec.whatwg.org/#abortcontroller */ class AbortController { /** * Initialize this controller. */ constructor() { signals.set(this, createAbortSignal()); } /** * Returns the `AbortSignal` object associated with this object. */ get signal() { return getSignal(this); } /** * Abort and signal to any observers that the associated activity is to be aborted. */ abort() { abortSignal(getSignal(this)); } } /** * Associated signals. */ const signals = new WeakMap(); /** * Get the associated signal of a given controller. */ function getSignal(controller) { const signal = signals.get(controller); if (signal == null) { throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); } return signal; } // Properties should be enumerable. Object.defineProperties(AbortController.prototype, { signal: { enumerable: true }, abort: { enumerable: true }, }); if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { configurable: true, value: "AbortController", }); } exports.AbortController = AbortController; exports.AbortSignal = AbortSignal; exports["default"] = AbortController; module.exports = AbortController module.exports.AbortController = module.exports["default"] = AbortController module.exports.AbortSignal = AbortSignal //# sourceMappingURL=abort-controller.js.map /***/ }), /***/ 9290: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var $byteLength = callBound('ArrayBuffer.prototype.byteLength', true); var isArrayBuffer = __nccwpck_require__(6429); /** @type {import('.')} */ module.exports = function byteLength(ab) { if (!isArrayBuffer(ab)) { return NaN; } return $byteLength ? $byteLength(ab) : ab.byteLength; }; // in node < 0.11, byteLength is an own nonconfigurable property /***/ }), /***/ 2639: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var bind = __nccwpck_require__(7564); var $apply = __nccwpck_require__(3945); var $call = __nccwpck_require__(8093); var $reflectApply = __nccwpck_require__(1330); /** @type {import('./actualApply')} */ module.exports = $reflectApply || bind.call($call, $apply); /***/ }), /***/ 6002: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var bind = __nccwpck_require__(7564); var $apply = __nccwpck_require__(3945); var actualApply = __nccwpck_require__(2639); /** @type {import('./applyBind')} */ module.exports = function applyBind() { return actualApply(bind, $apply, arguments); }; /***/ }), /***/ 3945: /***/ ((module) => { /** @type {import('./functionApply')} */ module.exports = Function.prototype.apply; /***/ }), /***/ 8093: /***/ ((module) => { /** @type {import('./functionCall')} */ module.exports = Function.prototype.call; /***/ }), /***/ 8705: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var bind = __nccwpck_require__(7564); var $TypeError = __nccwpck_require__(3314); var $call = __nccwpck_require__(8093); var $actualApply = __nccwpck_require__(2639); /** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ module.exports = function callBindBasic(args) { if (args.length < 1 || typeof args[0] !== 'function') { throw new $TypeError('a function is required'); } return $actualApply(bind, $call, args); }; /***/ }), /***/ 1330: /***/ ((module) => { /** @type {import('./reflectApply')} */ module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; /***/ }), /***/ 2856: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var GetIntrinsic = __nccwpck_require__(470); var callBind = __nccwpck_require__(3844); var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBind(intrinsic); } return intrinsic; }; /***/ }), /***/ 3844: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var setFunctionLength = __nccwpck_require__(9346); var $defineProperty = __nccwpck_require__(9094); var callBindBasic = __nccwpck_require__(8705); var applyBind = __nccwpck_require__(6002); module.exports = function callBind(originalFunction) { var func = callBindBasic(arguments); var adjustedLength = 1 + originalFunction.length - (arguments.length - 1); return setFunctionLength( func, adjustedLength > 0 ? adjustedLength : 0, true ); }; if ($defineProperty) { $defineProperty(module.exports, 'apply', { value: applyBind }); } else { module.exports.apply = applyBind; } /***/ }), /***/ 3105: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var GetIntrinsic = __nccwpck_require__(470); var callBindBasic = __nccwpck_require__(8705); /** @type {(thisArg: string, searchString: string, position?: number) => number} */ var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); /** @type {import('.')} */ module.exports = function callBoundIntrinsic(name, allowMissing) { /* eslint no-extra-parens: 0 */ var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBindBasic(/** @type {const} */ ([intrinsic])); } return intrinsic; }; /***/ }), /***/ 347: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var assign = __nccwpck_require__(3274); var callBound = __nccwpck_require__(2856); var flags = __nccwpck_require__(1972); var GetIntrinsic = __nccwpck_require__(470); var getIterator = __nccwpck_require__(8517); var getSideChannel = __nccwpck_require__(4753); var is = __nccwpck_require__(4682); var isArguments = __nccwpck_require__(1481); var isArray = __nccwpck_require__(2513); var isArrayBuffer = __nccwpck_require__(6429); var isDate = __nccwpck_require__(6253); var isRegex = __nccwpck_require__(6622); var isSharedArrayBuffer = __nccwpck_require__(2403); var objectKeys = __nccwpck_require__(2682); var whichBoxedPrimitive = __nccwpck_require__(516); var whichCollection = __nccwpck_require__(6260); var whichTypedArray = __nccwpck_require__(4768); var byteLength = __nccwpck_require__(9290); var sabByteLength = callBound('SharedArrayBuffer.prototype.byteLength', true); var $getTime = callBound('Date.prototype.getTime'); var gPO = Object.getPrototypeOf; var $objToString = callBound('Object.prototype.toString'); var $Set = GetIntrinsic('%Set%', true); var $mapHas = callBound('Map.prototype.has', true); var $mapGet = callBound('Map.prototype.get', true); var $mapSize = callBound('Map.prototype.size', true); var $setAdd = callBound('Set.prototype.add', true); var $setDelete = callBound('Set.prototype.delete', true); var $setHas = callBound('Set.prototype.has', true); var $setSize = callBound('Set.prototype.size', true); // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L401-L414 function setHasEqualElement(set, val1, opts, channel) { var i = getIterator(set); var result; while ((result = i.next()) && !result.done) { if (internalDeepEqual(val1, result.value, opts, channel)) { // eslint-disable-line no-use-before-define // Remove the matching element to make sure we do not check that again. $setDelete(set, result.value); return true; } } return false; } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L416-L439 function findLooseMatchingPrimitives(prim) { if (typeof prim === 'undefined') { return null; } if (typeof prim === 'object') { // Only pass in null as object! return void 0; } if (typeof prim === 'symbol') { return false; } if (typeof prim === 'string' || typeof prim === 'number') { // Loose equal entries exist only if the string is possible to convert to a regular number and not NaN. return +prim === +prim; // eslint-disable-line no-implicit-coercion } return true; } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L449-L460 function mapMightHaveLoosePrim(a, b, prim, item, opts, channel) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } var curB = $mapGet(b, altValue); var looseOpts = assign({}, opts, { strict: false }); if ( (typeof curB === 'undefined' && !$mapHas(b, altValue)) // eslint-disable-next-line no-use-before-define || !internalDeepEqual(item, curB, looseOpts, channel) ) { return false; } // eslint-disable-next-line no-use-before-define return !$mapHas(a, altValue) && internalDeepEqual(item, curB, looseOpts, channel); } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L441-L447 function setMightHaveLoosePrim(a, b, prim) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } return $setHas(b, altValue) && !$setHas(a, altValue); } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L518-L533 function mapHasEqualEntry(set, map, key1, item1, opts, channel) { var i = getIterator(set); var result; var key2; while ((result = i.next()) && !result.done) { key2 = result.value; if ( // eslint-disable-next-line no-use-before-define internalDeepEqual(key1, key2, opts, channel) // eslint-disable-next-line no-use-before-define && internalDeepEqual(item1, $mapGet(map, key2), opts, channel) ) { $setDelete(set, key2); return true; } } return false; } function internalDeepEqual(actual, expected, options, channel) { var opts = options || {}; // 7.1. All identical values are equivalent, as determined by ===. if (opts.strict ? is(actual, expected) : actual === expected) { return true; } var actualBoxed = whichBoxedPrimitive(actual); var expectedBoxed = whichBoxedPrimitive(expected); if (actualBoxed !== expectedBoxed) { return false; } // 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==. if (!actual || !expected || (typeof actual !== 'object' && typeof expected !== 'object')) { return opts.strict ? is(actual, expected) : actual == expected; // eslint-disable-line eqeqeq } /* * 7.4. For all other Object pairs, including Array objects, equivalence is * determined by having the same number of owned properties (as verified * with Object.prototype.hasOwnProperty.call), the same set of keys * (although not necessarily the same order), equivalent values for every * corresponding key, and an identical 'prototype' property. Note: this * accounts for both named and indexed properties on Arrays. */ // see https://github.com/nodejs/node/commit/d3aafd02efd3a403d646a3044adcf14e63a88d32 for memos/channel inspiration var hasActual = channel.has(actual); var hasExpected = channel.has(expected); var sentinel; if (hasActual && hasExpected) { if (channel.get(actual) === channel.get(expected)) { return true; } } else { sentinel = {}; } if (!hasActual) { channel.set(actual, sentinel); } if (!hasExpected) { channel.set(expected, sentinel); } // eslint-disable-next-line no-use-before-define return objEquiv(actual, expected, opts, channel); } function isBuffer(x) { if (!x || typeof x !== 'object' || typeof x.length !== 'number') { return false; } if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { return false; } if (x.length > 0 && typeof x[0] !== 'number') { return false; } return !!(x.constructor && x.constructor.isBuffer && x.constructor.isBuffer(x)); } function setEquiv(a, b, opts, channel) { if ($setSize(a) !== $setSize(b)) { return false; } var iA = getIterator(a); var iB = getIterator(b); var resultA; var resultB; var set; while ((resultA = iA.next()) && !resultA.done) { if (resultA.value && typeof resultA.value === 'object') { if (!set) { set = new $Set(); } $setAdd(set, resultA.value); } else if (!$setHas(b, resultA.value)) { if (opts.strict) { return false; } if (!setMightHaveLoosePrim(a, b, resultA.value)) { return false; } if (!set) { set = new $Set(); } $setAdd(set, resultA.value); } } if (set) { while ((resultB = iB.next()) && !resultB.done) { // We have to check if a primitive value is already matching and only if it's not, go hunting for it. if (resultB.value && typeof resultB.value === 'object') { if (!setHasEqualElement(set, resultB.value, opts.strict, channel)) { return false; } } else if ( !opts.strict && !$setHas(a, resultB.value) && !setHasEqualElement(set, resultB.value, opts.strict, channel) ) { return false; } } return $setSize(set) === 0; } return true; } function mapEquiv(a, b, opts, channel) { if ($mapSize(a) !== $mapSize(b)) { return false; } var iA = getIterator(a); var iB = getIterator(b); var resultA; var resultB; var set; var key; var item1; var item2; while ((resultA = iA.next()) && !resultA.done) { key = resultA.value[0]; item1 = resultA.value[1]; if (key && typeof key === 'object') { if (!set) { set = new $Set(); } $setAdd(set, key); } else { item2 = $mapGet(b, key); if ((typeof item2 === 'undefined' && !$mapHas(b, key)) || !internalDeepEqual(item1, item2, opts, channel)) { if (opts.strict) { return false; } if (!mapMightHaveLoosePrim(a, b, key, item1, opts, channel)) { return false; } if (!set) { set = new $Set(); } $setAdd(set, key); } } } if (set) { while ((resultB = iB.next()) && !resultB.done) { key = resultB.value[0]; item2 = resultB.value[1]; if (key && typeof key === 'object') { if (!mapHasEqualEntry(set, a, key, item2, opts, channel)) { return false; } } else if ( !opts.strict && (!a.has(key) || !internalDeepEqual($mapGet(a, key), item2, opts, channel)) && !mapHasEqualEntry(set, a, key, item2, assign({}, opts, { strict: false }), channel) ) { return false; } } return $setSize(set) === 0; } return true; } function objEquiv(a, b, opts, channel) { /* eslint max-statements: [2, 100], max-lines-per-function: [2, 120], max-depth: [2, 5], max-lines: [2, 400] */ var i, key; if (typeof a !== typeof b) { return false; } if (a == null || b == null) { return false; } if ($objToString(a) !== $objToString(b)) { return false; } if (isArguments(a) !== isArguments(b)) { return false; } var aIsArray = isArray(a); var bIsArray = isArray(b); if (aIsArray !== bIsArray) { return false; } // TODO: replace when a cross-realm brand check is available var aIsError = a instanceof Error; var bIsError = b instanceof Error; if (aIsError !== bIsError) { return false; } if (aIsError || bIsError) { if (a.name !== b.name || a.message !== b.message) { return false; } } var aIsRegex = isRegex(a); var bIsRegex = isRegex(b); if (aIsRegex !== bIsRegex) { return false; } if ((aIsRegex || bIsRegex) && (a.source !== b.source || flags(a) !== flags(b))) { return false; } var aIsDate = isDate(a); var bIsDate = isDate(b); if (aIsDate !== bIsDate) { return false; } if (aIsDate || bIsDate) { // && would work too, because both are true or both false here if ($getTime(a) !== $getTime(b)) { return false; } } if (opts.strict && gPO && gPO(a) !== gPO(b)) { return false; } var aWhich = whichTypedArray(a); var bWhich = whichTypedArray(b); if (aWhich !== bWhich) { return false; } if (aWhich || bWhich) { // && would work too, because both are true or both false here if (a.length !== b.length) { return false; } for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } var aIsBuffer = isBuffer(a); var bIsBuffer = isBuffer(b); if (aIsBuffer !== bIsBuffer) { return false; } if (aIsBuffer || bIsBuffer) { // && would work too, because both are true or both false here if (a.length !== b.length) { return false; } for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } var aIsArrayBuffer = isArrayBuffer(a); var bIsArrayBuffer = isArrayBuffer(b); if (aIsArrayBuffer !== bIsArrayBuffer) { return false; } if (aIsArrayBuffer || bIsArrayBuffer) { // && would work too, because both are true or both false here if (byteLength(a) !== byteLength(b)) { return false; } return typeof Uint8Array === 'function' && internalDeepEqual(new Uint8Array(a), new Uint8Array(b), opts, channel); } var aIsSAB = isSharedArrayBuffer(a); var bIsSAB = isSharedArrayBuffer(b); if (aIsSAB !== bIsSAB) { return false; } if (aIsSAB || bIsSAB) { // && would work too, because both are true or both false here if (sabByteLength(a) !== sabByteLength(b)) { return false; } return typeof Uint8Array === 'function' && internalDeepEqual(new Uint8Array(a), new Uint8Array(b), opts, channel); } if (typeof a !== typeof b) { return false; } var ka = objectKeys(a); var kb = objectKeys(b); // having the same number of owned properties (keys incorporates hasOwnProperty) if (ka.length !== kb.length) { return false; } // the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); // ~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) { return false; } // eslint-disable-line eqeqeq } // equivalent values for every corresponding key, and ~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!internalDeepEqual(a[key], b[key], opts, channel)) { return false; } } var aCollection = whichCollection(a); var bCollection = whichCollection(b); if (aCollection !== bCollection) { return false; } if (aCollection === 'Set' || bCollection === 'Set') { // aCollection === bCollection return setEquiv(a, b, opts, channel); } if (aCollection === 'Map') { // aCollection === bCollection return mapEquiv(a, b, opts, channel); } return true; } module.exports = function deepEqual(a, b, opts) { return internalDeepEqual(a, b, opts, getSideChannel()); }; /***/ }), /***/ 1316: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var $defineProperty = __nccwpck_require__(9094); var $SyntaxError = __nccwpck_require__(105); var $TypeError = __nccwpck_require__(3314); var gopd = __nccwpck_require__(3170); /** @type {import('.')} */ module.exports = function defineDataProperty( obj, property, value ) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new $TypeError('`obj` must be an object or a function`'); } if (typeof property !== 'string' && typeof property !== 'symbol') { throw new $TypeError('`property` must be a string or a symbol`'); } if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); } if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); } if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); } if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { throw new $TypeError('`loose`, if provided, must be a boolean'); } var nonEnumerable = arguments.length > 3 ? arguments[3] : null; var nonWritable = arguments.length > 4 ? arguments[4] : null; var nonConfigurable = arguments.length > 5 ? arguments[5] : null; var loose = arguments.length > 6 ? arguments[6] : false; /* @type {false | TypedPropertyDescriptor} */ var desc = !!gopd && gopd(obj, property); if ($defineProperty) { $defineProperty(obj, property, { configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, value: value, writable: nonWritable === null && desc ? desc.writable : !nonWritable }); } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable obj[property] = value; // eslint-disable-line no-param-reassign } else { throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); } }; /***/ }), /***/ 191: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var keys = __nccwpck_require__(2682); var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; var toStr = Object.prototype.toString; var concat = Array.prototype.concat; var defineDataProperty = __nccwpck_require__(1316); var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var supportsDescriptors = __nccwpck_require__(497)(); var defineProperty = function (object, name, value, predicate) { if (name in object) { if (predicate === true) { if (object[name] === value) { return; } } else if (!isFunction(predicate) || !predicate()) { return; } } if (supportsDescriptors) { defineDataProperty(object, name, value, true); } else { defineDataProperty(object, name, value); } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = concat.call(props, Object.getOwnPropertySymbols(map)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; /***/ }), /***/ 6669: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBind = __nccwpck_require__(8705); var gOPD = __nccwpck_require__(3170); var hasProtoAccessor; try { // eslint-disable-next-line no-extra-parens, no-proto hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; } catch (e) { if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { throw e; } } // eslint-disable-next-line no-extra-parens var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); var $Object = Object; var $getPrototypeOf = $Object.getPrototypeOf; /** @type {import('./get')} */ module.exports = desc && typeof desc.get === 'function' ? callBind([desc.get]) : typeof $getPrototypeOf === 'function' ? /** @type {import('./get')} */ function getDunder(value) { // eslint-disable-next-line eqeqeq return $getPrototypeOf(value == null ? value : $Object(value)); } : false; /***/ }), /***/ 9094: /***/ ((module) => { /** @type {import('.')} */ var $defineProperty = Object.defineProperty || false; if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = false; } } module.exports = $defineProperty; /***/ }), /***/ 3056: /***/ ((module) => { /** @type {import('./eval')} */ module.exports = EvalError; /***/ }), /***/ 1620: /***/ ((module) => { /** @type {import('.')} */ module.exports = Error; /***/ }), /***/ 4585: /***/ ((module) => { /** @type {import('./range')} */ module.exports = RangeError; /***/ }), /***/ 6905: /***/ ((module) => { /** @type {import('./ref')} */ module.exports = ReferenceError; /***/ }), /***/ 105: /***/ ((module) => { /** @type {import('./syntax')} */ module.exports = SyntaxError; /***/ }), /***/ 3314: /***/ ((module) => { /** @type {import('./type')} */ module.exports = TypeError; /***/ }), /***/ 2578: /***/ ((module) => { /** @type {import('./uri')} */ module.exports = URIError; /***/ }), /***/ 5399: /***/ ((module) => { /** @type {import('.')} */ module.exports = Object; /***/ }), /***/ 6577: /***/ ((module, exports) => { /** * @author Toru Nagashima * @copyright 2015 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ Object.defineProperty(exports, "__esModule", ({ value: true })); /** * @typedef {object} PrivateData * @property {EventTarget} eventTarget The event target. * @property {{type:string}} event The original event object. * @property {number} eventPhase The current event phase. * @property {EventTarget|null} currentTarget The current event target. * @property {boolean} canceled The flag to prevent default. * @property {boolean} stopped The flag to stop propagation. * @property {boolean} immediateStopped The flag to stop propagation immediately. * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. * @property {number} timeStamp The unix time. * @private */ /** * Private data for event wrappers. * @type {WeakMap} * @private */ const privateData = new WeakMap(); /** * Cache for wrapper classes. * @type {WeakMap} * @private */ const wrappers = new WeakMap(); /** * Get private data. * @param {Event} event The event object to get private data. * @returns {PrivateData} The private data of the event. * @private */ function pd(event) { const retv = privateData.get(event); console.assert( retv != null, "'this' is expected an Event object, but got", event ); return retv } /** * https://dom.spec.whatwg.org/#set-the-canceled-flag * @param data {PrivateData} private data. */ function setCancelFlag(data) { if (data.passiveListener != null) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error( "Unable to preventDefault inside passive event listener invocation.", data.passiveListener ); } return } if (!data.event.cancelable) { return } data.canceled = true; if (typeof data.event.preventDefault === "function") { data.event.preventDefault(); } } /** * @see https://dom.spec.whatwg.org/#interface-event * @private */ /** * The event wrapper. * @constructor * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Event|{type:string}} event The original event to wrap. */ function Event(eventTarget, event) { privateData.set(this, { eventTarget, event, eventPhase: 2, currentTarget: eventTarget, canceled: false, stopped: false, immediateStopped: false, passiveListener: null, timeStamp: event.timeStamp || Date.now(), }); // https://heycam.github.io/webidl/#Unforgeable Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); // Define accessors const keys = Object.keys(event); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in this)) { Object.defineProperty(this, key, defineRedirectDescriptor(key)); } } } // Should be enumerable, but class methods are not enumerable. Event.prototype = { /** * The type of this event. * @type {string} */ get type() { return pd(this).event.type }, /** * The target of this event. * @type {EventTarget} */ get target() { return pd(this).eventTarget }, /** * The target of this event. * @type {EventTarget} */ get currentTarget() { return pd(this).currentTarget }, /** * @returns {EventTarget[]} The composed path of this event. */ composedPath() { const currentTarget = pd(this).currentTarget; if (currentTarget == null) { return [] } return [currentTarget] }, /** * Constant of NONE. * @type {number} */ get NONE() { return 0 }, /** * Constant of CAPTURING_PHASE. * @type {number} */ get CAPTURING_PHASE() { return 1 }, /** * Constant of AT_TARGET. * @type {number} */ get AT_TARGET() { return 2 }, /** * Constant of BUBBLING_PHASE. * @type {number} */ get BUBBLING_PHASE() { return 3 }, /** * The target of this event. * @type {number} */ get eventPhase() { return pd(this).eventPhase }, /** * Stop event bubbling. * @returns {void} */ stopPropagation() { const data = pd(this); data.stopped = true; if (typeof data.event.stopPropagation === "function") { data.event.stopPropagation(); } }, /** * Stop event bubbling. * @returns {void} */ stopImmediatePropagation() { const data = pd(this); data.stopped = true; data.immediateStopped = true; if (typeof data.event.stopImmediatePropagation === "function") { data.event.stopImmediatePropagation(); } }, /** * The flag to be bubbling. * @type {boolean} */ get bubbles() { return Boolean(pd(this).event.bubbles) }, /** * The flag to be cancelable. * @type {boolean} */ get cancelable() { return Boolean(pd(this).event.cancelable) }, /** * Cancel this event. * @returns {void} */ preventDefault() { setCancelFlag(pd(this)); }, /** * The flag to indicate cancellation state. * @type {boolean} */ get defaultPrevented() { return pd(this).canceled }, /** * The flag to be composed. * @type {boolean} */ get composed() { return Boolean(pd(this).event.composed) }, /** * The unix time of this event. * @type {number} */ get timeStamp() { return pd(this).timeStamp }, /** * The target of this event. * @type {EventTarget} * @deprecated */ get srcElement() { return pd(this).eventTarget }, /** * The flag to stop event bubbling. * @type {boolean} * @deprecated */ get cancelBubble() { return pd(this).stopped }, set cancelBubble(value) { if (!value) { return } const data = pd(this); data.stopped = true; if (typeof data.event.cancelBubble === "boolean") { data.event.cancelBubble = true; } }, /** * The flag to indicate cancellation state. * @type {boolean} * @deprecated */ get returnValue() { return !pd(this).canceled }, set returnValue(value) { if (!value) { setCancelFlag(pd(this)); } }, /** * Initialize this event object. But do nothing under event dispatching. * @param {string} type The event type. * @param {boolean} [bubbles=false] The flag to be possible to bubble up. * @param {boolean} [cancelable=false] The flag to be possible to cancel. * @deprecated */ initEvent() { // Do nothing. }, }; // `constructor` is not enumerable. Object.defineProperty(Event.prototype, "constructor", { value: Event, configurable: true, writable: true, }); // Ensure `event instanceof window.Event` is `true`. if (typeof window !== "undefined" && typeof window.Event !== "undefined") { Object.setPrototypeOf(Event.prototype, window.Event.prototype); // Make association for wrappers. wrappers.set(window.Event.prototype, Event); } /** * Get the property descriptor to redirect a given property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to redirect the property. * @private */ function defineRedirectDescriptor(key) { return { get() { return pd(this).event[key] }, set(value) { pd(this).event[key] = value; }, configurable: true, enumerable: true, } } /** * Get the property descriptor to call a given method property. * @param {string} key Property name to define property descriptor. * @returns {PropertyDescriptor} The property descriptor to call the method property. * @private */ function defineCallDescriptor(key) { return { value() { const event = pd(this).event; return event[key].apply(event, arguments) }, configurable: true, enumerable: true, } } /** * Define new wrapper class. * @param {Function} BaseEvent The base wrapper class. * @param {Object} proto The prototype of the original event. * @returns {Function} The defined wrapper class. * @private */ function defineWrapper(BaseEvent, proto) { const keys = Object.keys(proto); if (keys.length === 0) { return BaseEvent } /** CustomEvent */ function CustomEvent(eventTarget, event) { BaseEvent.call(this, eventTarget, event); } CustomEvent.prototype = Object.create(BaseEvent.prototype, { constructor: { value: CustomEvent, configurable: true, writable: true }, }); // Define accessors. for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (!(key in BaseEvent.prototype)) { const descriptor = Object.getOwnPropertyDescriptor(proto, key); const isFunc = typeof descriptor.value === "function"; Object.defineProperty( CustomEvent.prototype, key, isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key) ); } } return CustomEvent } /** * Get the wrapper class of a given prototype. * @param {Object} proto The prototype of the original event to get its wrapper. * @returns {Function} The wrapper class. * @private */ function getWrapper(proto) { if (proto == null || proto === Object.prototype) { return Event } let wrapper = wrappers.get(proto); if (wrapper == null) { wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); wrappers.set(proto, wrapper); } return wrapper } /** * Wrap a given event to management a dispatching. * @param {EventTarget} eventTarget The event target of this dispatching. * @param {Object} event The event to wrap. * @returns {Event} The wrapper instance. * @private */ function wrapEvent(eventTarget, event) { const Wrapper = getWrapper(Object.getPrototypeOf(event)); return new Wrapper(eventTarget, event) } /** * Get the immediateStopped flag of a given event. * @param {Event} event The event to get. * @returns {boolean} The flag to stop propagation immediately. * @private */ function isStopped(event) { return pd(event).immediateStopped } /** * Set the current event phase of a given event. * @param {Event} event The event to set current target. * @param {number} eventPhase New event phase. * @returns {void} * @private */ function setEventPhase(event, eventPhase) { pd(event).eventPhase = eventPhase; } /** * Set the current target of a given event. * @param {Event} event The event to set current target. * @param {EventTarget|null} currentTarget New current target. * @returns {void} * @private */ function setCurrentTarget(event, currentTarget) { pd(event).currentTarget = currentTarget; } /** * Set a passive listener of a given event. * @param {Event} event The event to set current target. * @param {Function|null} passiveListener New passive listener. * @returns {void} * @private */ function setPassiveListener(event, passiveListener) { pd(event).passiveListener = passiveListener; } /** * @typedef {object} ListenerNode * @property {Function} listener * @property {1|2|3} listenerType * @property {boolean} passive * @property {boolean} once * @property {ListenerNode|null} next * @private */ /** * @type {WeakMap>} * @private */ const listenersMap = new WeakMap(); // Listener types const CAPTURE = 1; const BUBBLE = 2; const ATTRIBUTE = 3; /** * Check whether a given value is an object or not. * @param {any} x The value to check. * @returns {boolean} `true` if the value is an object. */ function isObject(x) { return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax } /** * Get listeners. * @param {EventTarget} eventTarget The event target to get. * @returns {Map} The listeners. * @private */ function getListeners(eventTarget) { const listeners = listenersMap.get(eventTarget); if (listeners == null) { throw new TypeError( "'this' is expected an EventTarget object, but got another value." ) } return listeners } /** * Get the property descriptor for the event attribute of a given event. * @param {string} eventName The event name to get property descriptor. * @returns {PropertyDescriptor} The property descriptor. * @private */ function defineEventAttributeDescriptor(eventName) { return { get() { const listeners = getListeners(this); let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { return node.listener } node = node.next; } return null }, set(listener) { if (typeof listener !== "function" && !isObject(listener)) { listener = null; // eslint-disable-line no-param-reassign } const listeners = getListeners(this); // Traverse to the tail while removing old value. let prev = null; let node = listeners.get(eventName); while (node != null) { if (node.listenerType === ATTRIBUTE) { // Remove old value. if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } node = node.next; } // Add new value. if (listener !== null) { const newNode = { listener, listenerType: ATTRIBUTE, passive: false, once: false, next: null, }; if (prev === null) { listeners.set(eventName, newNode); } else { prev.next = newNode; } } }, configurable: true, enumerable: true, } } /** * Define an event attribute (e.g. `eventTarget.onclick`). * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. * @param {string} eventName The event name to define. * @returns {void} */ function defineEventAttribute(eventTargetPrototype, eventName) { Object.defineProperty( eventTargetPrototype, `on${eventName}`, defineEventAttributeDescriptor(eventName) ); } /** * Define a custom EventTarget with event attributes. * @param {string[]} eventNames Event names for event attributes. * @returns {EventTarget} The custom EventTarget. * @private */ function defineCustomEventTarget(eventNames) { /** CustomEventTarget */ function CustomEventTarget() { EventTarget.call(this); } CustomEventTarget.prototype = Object.create(EventTarget.prototype, { constructor: { value: CustomEventTarget, configurable: true, writable: true, }, }); for (let i = 0; i < eventNames.length; ++i) { defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); } return CustomEventTarget } /** * EventTarget. * * - This is constructor if no arguments. * - This is a function which returns a CustomEventTarget constructor if there are arguments. * * For example: * * class A extends EventTarget {} * class B extends EventTarget("message") {} * class C extends EventTarget("message", "error") {} * class D extends EventTarget(["message", "error"]) {} */ function EventTarget() { /*eslint-disable consistent-return */ if (this instanceof EventTarget) { listenersMap.set(this, new Map()); return } if (arguments.length === 1 && Array.isArray(arguments[0])) { return defineCustomEventTarget(arguments[0]) } if (arguments.length > 0) { const types = new Array(arguments.length); for (let i = 0; i < arguments.length; ++i) { types[i] = arguments[i]; } return defineCustomEventTarget(types) } throw new TypeError("Cannot call a class as a function") /*eslint-enable consistent-return */ } // Should be enumerable, but class methods are not enumerable. EventTarget.prototype = { /** * Add a given listener to this event target. * @param {string} eventName The event name to add. * @param {Function} listener The listener to add. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ addEventListener(eventName, listener, options) { if (listener == null) { return } if (typeof listener !== "function" && !isObject(listener)) { throw new TypeError("'listener' should be a function or an object.") } const listeners = getListeners(this); const optionsIsObj = isObject(options); const capture = optionsIsObj ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; const newNode = { listener, listenerType, passive: optionsIsObj && Boolean(options.passive), once: optionsIsObj && Boolean(options.once), next: null, }; // Set it as the first node if the first node is null. let node = listeners.get(eventName); if (node === undefined) { listeners.set(eventName, newNode); return } // Traverse to the tail while checking duplication.. let prev = null; while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { // Should ignore duplication. return } prev = node; node = node.next; } // Add it. prev.next = newNode; }, /** * Remove a given listener from this event target. * @param {string} eventName The event name to remove. * @param {Function} listener The listener to remove. * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. * @returns {void} */ removeEventListener(eventName, listener, options) { if (listener == null) { return } const listeners = getListeners(this); const capture = isObject(options) ? Boolean(options.capture) : Boolean(options); const listenerType = capture ? CAPTURE : BUBBLE; let prev = null; let node = listeners.get(eventName); while (node != null) { if ( node.listener === listener && node.listenerType === listenerType ) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } return } prev = node; node = node.next; } }, /** * Dispatch a given event. * @param {Event|{type:string}} event The event to dispatch. * @returns {boolean} `false` if canceled. */ dispatchEvent(event) { if (event == null || typeof event.type !== "string") { throw new TypeError('"event.type" should be a string.') } // If listeners aren't registered, terminate. const listeners = getListeners(this); const eventName = event.type; let node = listeners.get(eventName); if (node == null) { return true } // Since we cannot rewrite several properties, so wrap object. const wrappedEvent = wrapEvent(this, event); // This doesn't process capturing phase and bubbling phase. // This isn't participating in a tree. let prev = null; while (node != null) { // Remove this listener if it's once if (node.once) { if (prev !== null) { prev.next = node.next; } else if (node.next !== null) { listeners.set(eventName, node.next); } else { listeners.delete(eventName); } } else { prev = node; } // Call this listener setPassiveListener( wrappedEvent, node.passive ? node.listener : null ); if (typeof node.listener === "function") { try { node.listener.call(this, wrappedEvent); } catch (err) { if ( typeof console !== "undefined" && typeof console.error === "function" ) { console.error(err); } } } else if ( node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function" ) { node.listener.handleEvent(wrappedEvent); } // Break if `event.stopImmediatePropagation` was called. if (isStopped(wrappedEvent)) { break } node = node.next; } setPassiveListener(wrappedEvent, null); setEventPhase(wrappedEvent, 0); setCurrentTarget(wrappedEvent, null); return !wrappedEvent.defaultPrevented }, }; // `constructor` is not enumerable. Object.defineProperty(EventTarget.prototype, "constructor", { value: EventTarget, configurable: true, writable: true, }); // Ensure `eventTarget instanceof window.EventTarget` is `true`. if ( typeof window !== "undefined" && typeof window.EventTarget !== "undefined" ) { Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); } exports.defineEventAttribute = defineEventAttribute; exports.EventTarget = EventTarget; exports["default"] = EventTarget; module.exports = EventTarget module.exports.EventTarget = module.exports["default"] = EventTarget module.exports.defineEventAttribute = defineEventAttribute //# sourceMappingURL=event-target-shim.js.map /***/ }), /***/ 4963: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var isCallable = __nccwpck_require__(9203); var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; /** @type {(arr: A, iterator: (this: This | void, value: A[number], index: number, arr: A) => void, receiver: This | undefined) => void} */ var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { if (receiver == null) { iterator(array[i], i, array); } else { iterator.call(receiver, array[i], i, array); } } } }; /** @type {(string: S, iterator: (this: This | void, value: S[number], index: number, string: S) => void, receiver: This | undefined) => void} */ var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. if (receiver == null) { iterator(string.charAt(i), i, string); } else { iterator.call(receiver, string.charAt(i), i, string); } } }; /** @type {(obj: O, iterator: (this: This | void, value: O[keyof O], index: keyof O, obj: O) => void, receiver: This | undefined) => void} */ var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { if (receiver == null) { iterator(object[k], k, object); } else { iterator.call(receiver, object[k], k, object); } } } }; /** @type {(x: unknown) => x is readonly unknown[]} */ function isArray(x) { return toStr.call(x) === '[object Array]'; } /** @type {import('.')._internal} */ module.exports = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } var receiver; if (arguments.length >= 3) { receiver = thisArg; } if (isArray(list)) { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { forEachString(list, iterator, receiver); } else { forEachObject(list, iterator, receiver); } }; /***/ }), /***/ 9808: /***/ ((module) => { /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var toStr = Object.prototype.toString; var max = Math.max; var funcType = '[object Function]'; var concatty = function concatty(a, b) { var arr = []; for (var i = 0; i < a.length; i += 1) { arr[i] = a[i]; } for (var j = 0; j < b.length; j += 1) { arr[j + a.length] = b[j]; } return arr; }; var slicy = function slicy(arrLike, offset) { var arr = []; for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { arr[j] = arrLike[i]; } return arr; }; var joiny = function (arr, joiner) { var str = ''; for (var i = 0; i < arr.length; i += 1) { str += arr[i]; if (i + 1 < arr.length) { str += joiner; } } return str; }; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.apply(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slicy(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, concatty(args, arguments) ); if (Object(result) === result) { return result; } return this; } return target.apply( that, concatty(args, arguments) ); }; var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs[i] = '$' + i; } bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /***/ 7564: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var implementation = __nccwpck_require__(9808); module.exports = Function.prototype.bind || implementation; /***/ }), /***/ 1327: /***/ ((module) => { var functionsHaveNames = function functionsHaveNames() { return typeof function f() {}.name === 'string'; }; var gOPD = Object.getOwnPropertyDescriptor; if (gOPD) { try { gOPD([], 'length'); } catch (e) { // IE 8 has a broken gOPD gOPD = null; } } functionsHaveNames.functionsHaveConfigurableNames = function functionsHaveConfigurableNames() { if (!functionsHaveNames() || !gOPD) { return false; } var desc = gOPD(function () {}, 'name'); return !!desc && !!desc.configurable; }; var $bind = Function.prototype.bind; functionsHaveNames.boundFunctionsHaveNames = function boundFunctionsHaveNames() { return functionsHaveNames() && typeof $bind === 'function' && function f() {}.bind().name !== ''; }; module.exports = functionsHaveNames; /***/ }), /***/ 470: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var undefined; var $Object = __nccwpck_require__(5399); var $Error = __nccwpck_require__(1620); var $EvalError = __nccwpck_require__(3056); var $RangeError = __nccwpck_require__(4585); var $ReferenceError = __nccwpck_require__(6905); var $SyntaxError = __nccwpck_require__(105); var $TypeError = __nccwpck_require__(3314); var $URIError = __nccwpck_require__(2578); var abs = __nccwpck_require__(5641); var floor = __nccwpck_require__(6171); var max = __nccwpck_require__(7147); var min = __nccwpck_require__(1017); var pow = __nccwpck_require__(6947); var round = __nccwpck_require__(2621); var sign = __nccwpck_require__(156); var $Function = Function; // eslint-disable-next-line consistent-return var getEvalledConstructor = function (expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); } catch (e) {} }; var $gOPD = __nccwpck_require__(3170); var $defineProperty = __nccwpck_require__(9094); var throwTypeError = function () { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? (function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }()) : throwTypeError; var hasSymbols = __nccwpck_require__(3336)(); var getProto = __nccwpck_require__(1967); var $ObjectGPO = __nccwpck_require__(1311); var $ReflectGPO = __nccwpck_require__(8681); var $apply = __nccwpck_require__(3945); var $call = __nccwpck_require__(8093); var needsEval = {}; var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); var INTRINSICS = { __proto__: null, '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': needsEval, '%AsyncGenerator%': needsEval, '%AsyncGeneratorFunction%': needsEval, '%AsyncIteratorPrototype%': needsEval, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, '%Boolean%': Boolean, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%Date%': Date, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': $Error, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': $EvalError, '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, '%Function%': $Function, '%GeneratorFunction%': needsEval, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': typeof JSON === 'object' ? JSON : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), '%Math%': Math, '%Number%': Number, '%Object%': $Object, '%Object.getOwnPropertyDescriptor%': $gOPD, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': $RangeError, '%ReferenceError%': $ReferenceError, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%String%': String, '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, '%Symbol%': hasSymbols ? Symbol : undefined, '%SyntaxError%': $SyntaxError, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypeError%': $TypeError, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%URIError%': $URIError, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, '%Function.prototype.call%': $call, '%Function.prototype.apply%': $apply, '%Object.defineProperty%': $defineProperty, '%Object.getPrototypeOf%': $ObjectGPO, '%Math.abs%': abs, '%Math.floor%': floor, '%Math.max%': max, '%Math.min%': min, '%Math.pow%': pow, '%Math.round%': round, '%Math.sign%': sign, '%Reflect.getPrototypeOf%': $ReflectGPO }; if (getProto) { try { null.error; // eslint-disable-line no-unused-expressions } catch (e) { // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 var errorProto = getProto(getProto(e)); INTRINSICS['%Error.prototype%'] = errorProto; } } var doEval = function doEval(name) { var value; if (name === '%AsyncFunction%') { value = getEvalledConstructor('async function () {}'); } else if (name === '%GeneratorFunction%') { value = getEvalledConstructor('function* () {}'); } else if (name === '%AsyncGeneratorFunction%') { value = getEvalledConstructor('async function* () {}'); } else if (name === '%AsyncGenerator%') { var fn = doEval('%AsyncGeneratorFunction%'); if (fn) { value = fn.prototype; } } else if (name === '%AsyncIteratorPrototype%') { var gen = doEval('%AsyncGenerator%'); if (gen && getProto) { value = getProto(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { __proto__: null, '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], '%ArrayPrototype%': ['Array', 'prototype'], '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], '%ArrayProto_values%': ['Array', 'prototype', 'values'], '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], '%BooleanPrototype%': ['Boolean', 'prototype'], '%DataViewPrototype%': ['DataView', 'prototype'], '%DatePrototype%': ['Date', 'prototype'], '%ErrorPrototype%': ['Error', 'prototype'], '%EvalErrorPrototype%': ['EvalError', 'prototype'], '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], '%FunctionPrototype%': ['Function', 'prototype'], '%Generator%': ['GeneratorFunction', 'prototype'], '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], '%JSONParse%': ['JSON', 'parse'], '%JSONStringify%': ['JSON', 'stringify'], '%MapPrototype%': ['Map', 'prototype'], '%NumberPrototype%': ['Number', 'prototype'], '%ObjectPrototype%': ['Object', 'prototype'], '%ObjProto_toString%': ['Object', 'prototype', 'toString'], '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], '%PromisePrototype%': ['Promise', 'prototype'], '%PromiseProto_then%': ['Promise', 'prototype', 'then'], '%Promise_all%': ['Promise', 'all'], '%Promise_reject%': ['Promise', 'reject'], '%Promise_resolve%': ['Promise', 'resolve'], '%RangeErrorPrototype%': ['RangeError', 'prototype'], '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], '%RegExpPrototype%': ['RegExp', 'prototype'], '%SetPrototype%': ['Set', 'prototype'], '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], '%StringPrototype%': ['String', 'prototype'], '%SymbolPrototype%': ['Symbol', 'prototype'], '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], '%TypedArrayPrototype%': ['TypedArray', 'prototype'], '%TypeErrorPrototype%': ['TypeError', 'prototype'], '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], '%URIErrorPrototype%': ['URIError', 'prototype'], '%WeakMapPrototype%': ['WeakMap', 'prototype'], '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; var bind = __nccwpck_require__(7564); var hasOwn = __nccwpck_require__(4076); var $concat = bind.call($call, Array.prototype.concat); var $spliceApply = bind.call($apply, Array.prototype.splice); var $replace = bind.call($call, String.prototype.replace); var $strSlice = bind.call($call, String.prototype.slice); var $exec = bind.call($call, RegExp.prototype.exec); /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === '%' && last !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); } else if (last === '%' && first !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); } var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = '%' + alias[0] + '%'; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return { alias: alias, name: intrinsicName, value: value }; } throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new $TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new $TypeError('"allowMissing" argument must be a boolean'); } if ($exec(/^%?[^%]*%?$/, name) === null) { throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ( ( (first === '"' || first === "'" || first === '`') || (last === '"' || last === "'" || last === '`') ) && first !== last ) { throw new $SyntaxError('property names with quotes must have matching quotes'); } if (part === 'constructor' || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += '.' + part; intrinsicRealName = '%' + intrinsicBaseName + '%'; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } return void undefined; } if ($gOPD && (i + 1) >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; // By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; /***/ }), /***/ 1311: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var $Object = __nccwpck_require__(5399); /** @type {import('./Object.getPrototypeOf')} */ module.exports = $Object.getPrototypeOf || null; /***/ }), /***/ 8681: /***/ ((module) => { /** @type {import('./Reflect.getPrototypeOf')} */ module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; /***/ }), /***/ 1967: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var reflectGetProto = __nccwpck_require__(8681); var originalGetProto = __nccwpck_require__(1311); var getDunderProto = __nccwpck_require__(6669); /** @type {import('.')} */ module.exports = reflectGetProto ? function getProto(O) { // @ts-expect-error TS can't narrow inside a closure, for some reason return reflectGetProto(O); } : originalGetProto ? function getProto(O) { if (!O || (typeof O !== 'object' && typeof O !== 'function')) { throw new TypeError('getProto: not an object'); } // @ts-expect-error TS can't narrow inside a closure, for some reason return originalGetProto(O); } : getDunderProto ? function getProto(O) { // @ts-expect-error TS can't narrow inside a closure, for some reason return getDunderProto(O); } : null; /***/ }), /***/ 1174: /***/ ((module) => { /** @type {import('./gOPD')} */ module.exports = Object.getOwnPropertyDescriptor; /***/ }), /***/ 3170: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** @type {import('.')} */ var $gOPD = __nccwpck_require__(1174); if ($gOPD) { try { $gOPD([], 'length'); } catch (e) { // IE 8 has a broken gOPD $gOPD = null; } } module.exports = $gOPD; /***/ }), /***/ 6629: /***/ ((module) => { var $BigInt = typeof BigInt !== 'undefined' && BigInt; /** @type {import('.')} */ module.exports = function hasNativeBigInts() { return typeof $BigInt === 'function' && typeof BigInt === 'function' && typeof $BigInt(42) === 'bigint' // eslint-disable-line no-magic-numbers && typeof BigInt(42) === 'bigint'; // eslint-disable-line no-magic-numbers }; /***/ }), /***/ 497: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var $defineProperty = __nccwpck_require__(9094); var hasPropertyDescriptors = function hasPropertyDescriptors() { return !!$defineProperty; }; hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { // node v0.6 has a bug where array lengths can be Set but not Defined if (!$defineProperty) { return null; } try { return $defineProperty([], 'length', { value: 1 }).length !== 1; } catch (e) { // In Firefox 4-22, defining length on an array throws an exception. return true; } }; module.exports = hasPropertyDescriptors; /***/ }), /***/ 3336: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var origSymbol = typeof Symbol !== 'undefined' && Symbol; var hasSymbolSham = __nccwpck_require__(1114); /** @type {import('.')} */ module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (typeof origSymbol('foo') !== 'symbol') { return false; } if (typeof Symbol('bar') !== 'symbol') { return false; } return hasSymbolSham(); }; /***/ }), /***/ 1114: /***/ ((module) => { /** @type {import('./shams')} */ /* eslint complexity: [2, 18], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } /** @type {{ [k in symbol]?: unknown }} */ var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { // eslint-disable-next-line no-extra-parens var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /***/ 5479: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var hasSymbols = __nccwpck_require__(1114); /** @type {import('.')} */ module.exports = function hasToStringTagShams() { return hasSymbols() && !!Symbol.toStringTag; }; /***/ }), /***/ 4076: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var call = Function.prototype.call; var $hasOwn = Object.prototype.hasOwnProperty; var bind = __nccwpck_require__(7564); /** @type {import('.')} */ module.exports = bind.call(call, $hasOwn); /***/ }), /***/ 1481: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var hasToStringTag = __nccwpck_require__(5479)(); var callBound = __nccwpck_require__(3105); var $toString = callBound('Object.prototype.toString'); /** @type {import('.')} */ var isStandardArguments = function isArguments(value) { if ( hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value ) { return false; } return $toString(value) === '[object Arguments]'; }; /** @type {import('.')} */ var isLegacyArguments = function isArguments(value) { if (isStandardArguments(value)) { return true; } return value !== null && typeof value === 'object' && 'length' in value && typeof value.length === 'number' && value.length >= 0 && $toString(value) !== '[object Array]' && 'callee' in value && $toString(value.callee) === '[object Function]'; }; var supportsStandardArguments = (function () { return isStandardArguments(arguments); }()); // @ts-expect-error TODO make this not error isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests /** @type {import('.')} */ module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; /***/ }), /***/ 6429: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBind = __nccwpck_require__(3844); var callBound = __nccwpck_require__(3105); var GetIntrinsic = __nccwpck_require__(470); var $ArrayBuffer = GetIntrinsic('%ArrayBuffer%', true); /** @type {undefined | ((receiver: ArrayBuffer) => number) | ((receiver: unknown) => never)} */ var $byteLength = callBound('ArrayBuffer.prototype.byteLength', true); var $toString = callBound('Object.prototype.toString'); // in node 0.10, ArrayBuffers have no prototype methods, but have an own slot-checking `slice` method var abSlice = !!$ArrayBuffer && !$byteLength && new $ArrayBuffer(0).slice; var $abSlice = !!abSlice && callBind(abSlice); /** @type {import('.')} */ module.exports = $byteLength || $abSlice ? function isArrayBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } try { if ($byteLength) { // @ts-expect-error no idea why TS can't handle the overload $byteLength(obj); } else { // @ts-expect-error TS chooses not to type-narrow inside a closure $abSlice(obj, 0); } return true; } catch (e) { return false; } } : $ArrayBuffer // in node 0.8, ArrayBuffers have no prototype or own methods, but also no Symbol.toStringTag ? function isArrayBuffer(obj) { return $toString(obj) === '[object ArrayBuffer]'; } // @ts-expect-error : function isArrayBuffer(obj) { // eslint-disable-line no-unused-vars return false; }; /***/ }), /***/ 7788: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var hasBigInts = __nccwpck_require__(6629)(); if (hasBigInts) { var bigIntValueOf = BigInt.prototype.valueOf; /** @type {(value: object) => value is BigInt} */ var tryBigInt = function tryBigIntObject(value) { try { bigIntValueOf.call(value); return true; } catch (e) { } return false; }; /** @type {import('.')} */ module.exports = function isBigInt(value) { if ( value === null || typeof value === 'undefined' || typeof value === 'boolean' || typeof value === 'string' || typeof value === 'number' || typeof value === 'symbol' || typeof value === 'function' ) { return false; } if (typeof value === 'bigint') { return true; } return tryBigInt(value); }; } else { /** @type {import('.')} */ module.exports = function isBigInt(value) { return false && 0; }; } /***/ }), /***/ 823: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var $boolToStr = callBound('Boolean.prototype.toString'); var $toString = callBound('Object.prototype.toString'); /** @type {import('.')} */ var tryBooleanObject = function booleanBrandCheck(value) { try { $boolToStr(value); return true; } catch (e) { return false; } }; var boolClass = '[object Boolean]'; var hasToStringTag = __nccwpck_require__(5479)(); /** @type {import('.')} */ module.exports = function isBoolean(value) { if (typeof value === 'boolean') { return true; } if (value === null || typeof value !== 'object') { return false; } return hasToStringTag ? tryBooleanObject(value) : $toString(value) === boolClass; }; /***/ }), /***/ 9203: /***/ ((module) => { var fnToStr = Function.prototype.toString; var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; var badArrayLike; var isCallableMarker; if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { try { badArrayLike = Object.defineProperty({}, 'length', { get: function () { throw isCallableMarker; } }); isCallableMarker = {}; // eslint-disable-next-line no-throw-literal reflectApply(function () { throw 42; }, null, badArrayLike); } catch (_) { if (_ !== isCallableMarker) { reflectApply = null; } } } else { reflectApply = null; } var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { var fnStr = fnToStr.call(value); return constructorRegex.test(fnStr); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var objectClass = '[object Object]'; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var ddaClass = '[object HTMLAllCollection]'; // IE 11 var ddaClass2 = '[object HTML document.all class]'; var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing var isDDA = function isDocumentDotAll() { return false; }; if (typeof document === 'object') { // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly var all = document.all; if (toStr.call(all) === toStr.call(document.all)) { isDDA = function isDocumentDotAll(value) { /* globals document: false */ // in IE 6-8, typeof document.all is "object" and it's truthy if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { try { var str = toStr.call(value); return ( str === ddaClass || str === ddaClass2 || str === ddaClass3 // opera 12.16 || str === objectClass // IE 6-8 ) && value('') == null; // eslint-disable-line eqeqeq } catch (e) { /**/ } } return false; }; } } module.exports = reflectApply ? function isCallable(value) { if (isDDA(value)) { return true; } if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } try { reflectApply(value, null, badArrayLike); } catch (e) { if (e !== isCallableMarker) { return false; } } return !isES6ClassFn(value) && tryFunctionObject(value); } : function isCallable(value) { if (isDDA(value)) { return true; } if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } return tryFunctionObject(value); }; /***/ }), /***/ 6253: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var getDay = callBound('Date.prototype.getDay'); /** @type {import('.')} */ var tryDateObject = function tryDateGetDayCall(value) { try { getDay(value); return true; } catch (e) { return false; } }; /** @type {(value: unknown) => string} */ var toStr = callBound('Object.prototype.toString'); var dateClass = '[object Date]'; var hasToStringTag = __nccwpck_require__(5479)(); /** @type {import('.')} */ module.exports = function isDateObject(value) { if (typeof value !== 'object' || value === null) { return false; } return hasToStringTag ? tryDateObject(value) : toStr(value) === dateClass; }; /***/ }), /***/ 9311: /***/ ((module) => { /** @const */ var $Map = typeof Map === 'function' && Map.prototype ? Map : null; var $Set = typeof Set === 'function' && Set.prototype ? Set : null; var exported; if (!$Map) { /** @type {import('.')} */ // eslint-disable-next-line no-unused-vars exported = function isMap(x) { // `Map` is not present in this environment. return false; }; } var $mapHas = $Map ? Map.prototype.has : null; var $setHas = $Set ? Set.prototype.has : null; if (!exported && !$mapHas) { /** @type {import('.')} */ // eslint-disable-next-line no-unused-vars exported = function isMap(x) { // `Map` does not have a `has` method return false; }; } /** @type {import('.')} */ module.exports = exported || function isMap(x) { if (!x || typeof x !== 'object') { return false; } try { $mapHas.call(x); if ($setHas) { try { $setHas.call(x); } catch (e) { return true; } } // @ts-expect-error TS can't figure out that $Map is always truthy here return x instanceof $Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; }; /***/ }), /***/ 3670: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var $numToStr = callBound('Number.prototype.toString'); /** @type {import('.')} */ var tryNumberObject = function tryNumberObject(value) { try { $numToStr(value); return true; } catch (e) { return false; } }; var $toString = callBound('Object.prototype.toString'); var numClass = '[object Number]'; var hasToStringTag = __nccwpck_require__(5479)(); /** @type {import('.')} */ module.exports = function isNumberObject(value) { if (typeof value === 'number') { return true; } if (!value || typeof value !== 'object') { return false; } return hasToStringTag ? tryNumberObject(value) : $toString(value) === numClass; }; /***/ }), /***/ 6622: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var hasToStringTag = __nccwpck_require__(5479)(); var hasOwn = __nccwpck_require__(4076); var gOPD = __nccwpck_require__(3170); /** @type {import('.')} */ var fn; if (hasToStringTag) { /** @type {(receiver: ThisParameterType, ...args: Parameters) => ReturnType} */ var $exec = callBound('RegExp.prototype.exec'); /** @type {object} */ var isRegexMarker = {}; var throwRegexMarker = function () { throw isRegexMarker; }; /** @type {{ toString(): never, valueOf(): never, [Symbol.toPrimitive]?(): never }} */ var badStringifier = { toString: throwRegexMarker, valueOf: throwRegexMarker }; if (typeof Symbol.toPrimitive === 'symbol') { badStringifier[Symbol.toPrimitive] = throwRegexMarker; } /** @type {import('.')} */ // @ts-expect-error TS can't figure out that the $exec call always throws // eslint-disable-next-line consistent-return fn = function isRegex(value) { if (!value || typeof value !== 'object') { return false; } // eslint-disable-next-line no-extra-parens var descriptor = /** @type {NonNullable} */ (gOPD)(/** @type {{ lastIndex?: unknown }} */ (value), 'lastIndex'); var hasLastIndexDataProperty = descriptor && hasOwn(descriptor, 'value'); if (!hasLastIndexDataProperty) { return false; } try { // eslint-disable-next-line no-extra-parens $exec(value, /** @type {string} */ (/** @type {unknown} */ (badStringifier))); } catch (e) { return e === isRegexMarker; } }; } else { /** @type {(receiver: ThisParameterType, ...args: Parameters) => ReturnType} */ var $toString = callBound('Object.prototype.toString'); /** @const @type {'[object RegExp]'} */ var regexClass = '[object RegExp]'; /** @type {import('.')} */ fn = function isRegex(value) { // In older browsers, typeof regex incorrectly returns 'function' if (!value || (typeof value !== 'object' && typeof value !== 'function')) { return false; } return $toString(value) === regexClass; }; } module.exports = fn; /***/ }), /***/ 6513: /***/ ((module) => { var $Map = typeof Map === 'function' && Map.prototype ? Map : null; var $Set = typeof Set === 'function' && Set.prototype ? Set : null; var exported; if (!$Set) { /** @type {import('.')} */ // eslint-disable-next-line no-unused-vars exported = function isSet(x) { // `Set` is not present in this environment. return false; }; } var $mapHas = $Map ? Map.prototype.has : null; var $setHas = $Set ? Set.prototype.has : null; if (!exported && !$setHas) { /** @type {import('.')} */ // eslint-disable-next-line no-unused-vars exported = function isSet(x) { // `Set` does not have a `has` method return false; }; } /** @type {import('.')} */ module.exports = exported || function isSet(x) { if (!x || typeof x !== 'object') { return false; } try { $setHas.call(x); if ($mapHas) { try { $mapHas.call(x); } catch (e) { return true; } } // @ts-expect-error TS can't figure out that $Set is always truthy here return x instanceof $Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; }; /***/ }), /***/ 2403: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); /** @type {undefined | ((thisArg: SharedArrayBuffer) => number)} */ var $byteLength = callBound('SharedArrayBuffer.prototype.byteLength', true); /** @type {import('.')} */ module.exports = $byteLength ? function isSharedArrayBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } try { // @ts-expect-error TS can't figure out this closed-over variable is non-nullable, and it's fine that `obj` might not be a SAB $byteLength(obj); return true; } catch (e) { return false; } } : function isSharedArrayBuffer(_obj) { // eslint-disable-line no-unused-vars return false; }; /***/ }), /***/ 7970: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); /** @type {(receiver: ThisParameterType, ...args: Parameters) => ReturnType} */ var $strValueOf = callBound('String.prototype.valueOf'); /** @type {import('.')} */ var tryStringObject = function tryStringObject(value) { try { $strValueOf(value); return true; } catch (e) { return false; } }; /** @type {(receiver: ThisParameterType, ...args: Parameters) => ReturnType} */ var $toString = callBound('Object.prototype.toString'); var strClass = '[object String]'; var hasToStringTag = __nccwpck_require__(5479)(); /** @type {import('.')} */ module.exports = function isString(value) { if (typeof value === 'string') { return true; } if (!value || typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : $toString(value) === strClass; }; /***/ }), /***/ 3927: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var $toString = callBound('Object.prototype.toString'); var hasSymbols = __nccwpck_require__(3336)(); var safeRegexTest = __nccwpck_require__(3470); if (hasSymbols) { var $symToStr = callBound('Symbol.prototype.toString'); var isSymString = safeRegexTest(/^Symbol\(.*\)$/); /** @type {(value: object) => value is Symbol} */ var isSymbolObject = function isRealSymbolObject(value) { if (typeof value.valueOf() !== 'symbol') { return false; } return isSymString($symToStr(value)); }; /** @type {import('.')} */ module.exports = function isSymbol(value) { if (typeof value === 'symbol') { return true; } if (!value || typeof value !== 'object' || $toString(value) !== '[object Symbol]') { return false; } try { return isSymbolObject(value); } catch (e) { return false; } }; } else { /** @type {import('.')} */ module.exports = function isSymbol(value) { // this environment does not support Symbols. return false && 0; }; } /***/ }), /***/ 3955: /***/ ((module) => { var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null; var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null; var exported; if (!$WeakMap) { /** @type {import('.')} */ // eslint-disable-next-line no-unused-vars exported = function isWeakMap(x) { // `WeakMap` is not present in this environment. return false; }; } var $mapHas = $WeakMap ? $WeakMap.prototype.has : null; var $setHas = $WeakSet ? $WeakSet.prototype.has : null; if (!exported && !$mapHas) { /** @type {import('.')} */ // eslint-disable-next-line no-unused-vars exported = function isWeakMap(x) { // `WeakMap` does not have a `has` method return false; }; } /** @type {import('.')} */ module.exports = exported || function isWeakMap(x) { if (!x || typeof x !== 'object') { return false; } try { $mapHas.call(x, $mapHas); if ($setHas) { try { $setHas.call(x, $setHas); } catch (e) { return true; } } // @ts-expect-error TS can't figure out that $WeakMap is always truthy here return x instanceof $WeakMap; // core-js workaround, pre-v3 } catch (e) {} return false; }; /***/ }), /***/ 2237: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var GetIntrinsic = __nccwpck_require__(470); var callBound = __nccwpck_require__(3105); var $WeakSet = GetIntrinsic('%WeakSet%', true); /** @type {undefined | ((thisArg: Set, value: V) => boolean)} */ var $setHas = callBound('WeakSet.prototype.has', true); if ($setHas) { /** @type {undefined | ((thisArg: WeakMap, key: K) => boolean)} */ var $mapHas = callBound('WeakMap.prototype.has', true); /** @type {import('.')} */ module.exports = function isWeakSet(x) { if (!x || typeof x !== 'object') { return false; } try { // @ts-expect-error TS can't figure out that $setHas is always truthy here $setHas(x, $setHas); if ($mapHas) { try { // @ts-expect-error this indeed might not be a weak collection $mapHas(x, $mapHas); } catch (e) { return true; } } // @ts-expect-error TS can't figure out that $WeakSet is always truthy here return x instanceof $WeakSet; // core-js workaround, pre-v3 } catch (e) {} return false; }; } else { /** @type {import('.')} */ // @ts-expect-error module.exports = function isWeakSet(x) { // eslint-disable-line no-unused-vars // `WeakSet` does not exist, or does not have a `has` method return false; }; } /***/ }), /***/ 2513: /***/ ((module) => { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /***/ 5641: /***/ ((module) => { /** @type {import('./abs')} */ module.exports = Math.abs; /***/ }), /***/ 6171: /***/ ((module) => { /** @type {import('./floor')} */ module.exports = Math.floor; /***/ }), /***/ 7044: /***/ ((module) => { /** @type {import('./isNaN')} */ module.exports = Number.isNaN || function isNaN(a) { return a !== a; }; /***/ }), /***/ 7147: /***/ ((module) => { /** @type {import('./max')} */ module.exports = Math.max; /***/ }), /***/ 1017: /***/ ((module) => { /** @type {import('./min')} */ module.exports = Math.min; /***/ }), /***/ 6947: /***/ ((module) => { /** @type {import('./pow')} */ module.exports = Math.pow; /***/ }), /***/ 2621: /***/ ((module) => { /** @type {import('./round')} */ module.exports = Math.round; /***/ }), /***/ 156: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var $isNaN = __nccwpck_require__(7044); /** @type {import('./sign')} */ module.exports = function sign(number) { if ($isNaN(number) || number === 0) { return number; } return number < 0 ? -1 : +1; }; /***/ }), /***/ 7666: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! node-domexception. MIT License. Jimmy Wärting */ if (!globalThis.DOMException) { try { const { MessageChannel } = __nccwpck_require__(8167), port = new MessageChannel().port1, ab = new ArrayBuffer() port.postMessage(ab, [ab, ab]) } catch (err) { err.constructor.name === 'DOMException' && ( globalThis.DOMException = err.constructor ) } } module.exports = globalThis.DOMException /***/ }), /***/ 506: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === 'function' && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; var booleanValueOf = Boolean.prototype.valueOf; var objectToString = Object.prototype.toString; var functionToString = Function.prototype.toString; var $match = String.prototype.match; var $slice = String.prototype.slice; var $replace = String.prototype.replace; var $toUpperCase = String.prototype.toUpperCase; var $toLowerCase = String.prototype.toLowerCase; var $test = RegExp.prototype.test; var $concat = Array.prototype.concat; var $join = Array.prototype.join; var $arrSlice = Array.prototype.slice; var $floor = Math.floor; var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; var gOPS = Object.getOwnPropertySymbols; var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; // ie, `has-tostringtag/shams var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') ? Symbol.toStringTag : null; var isEnumerable = Object.prototype.propertyIsEnumerable; var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( [].__proto__ === Array.prototype // eslint-disable-line no-proto ? function (O) { return O.__proto__; // eslint-disable-line no-proto } : null ); function addNumericSeparator(num, str) { if ( num === Infinity || num === -Infinity || num !== num || (num && num > -1000 && num < 1000) || $test.call(/e/, str) ) { return str; } var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; if (typeof num === 'number') { var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) if (int !== num) { var intStr = String(int); var dec = $slice.call(str, intStr.length + 1); return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); } } return $replace.call(str, sepRegex, '$&_'); } var utilInspect = __nccwpck_require__(8502); var inspectCustom = utilInspect.custom; var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; var quotes = { __proto__: null, 'double': '"', single: "'" }; var quoteREs = { __proto__: null, 'double': /(["\\])/g, single: /(['\\])/g }; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { throw new TypeError('option "quoteStyle" must be "single" or "double"'); } if ( has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null ) ) { throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); } var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); } if ( has(opts, 'indent') && opts.indent !== null && opts.indent !== '\t' && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) ) { throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); } if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); } var numericSeparator = opts.numericSeparator; if (typeof obj === 'undefined') { return 'undefined'; } if (obj === null) { return 'null'; } if (typeof obj === 'boolean') { return obj ? 'true' : 'false'; } if (typeof obj === 'string') { return inspectString(obj, opts); } if (typeof obj === 'number') { if (obj === 0) { return Infinity / obj > 0 ? '0' : '-0'; } var str = String(obj); return numericSeparator ? addNumericSeparator(obj, str) : str; } if (typeof obj === 'bigint') { var bigIntStr = String(obj) + 'n'; return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; } var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; if (typeof depth === 'undefined') { depth = 0; } if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { return isArray(obj) ? '[Array]' : '[Object]'; } var indent = getIndent(opts, depth); if (typeof seen === 'undefined') { seen = []; } else if (indexOf(seen, obj) >= 0) { return '[Circular]'; } function inspect(value, from, noIndent) { if (from) { seen = $arrSlice.call(seen); seen.push(from); } if (noIndent) { var newOpts = { depth: opts.depth }; if (has(opts, 'quoteStyle')) { newOpts.quoteStyle = opts.quoteStyle; } return inspect_(value, newOpts, depth + 1, seen); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable var name = nameOf(obj); var keys = arrObjKeys(obj, inspect); return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); } if (isSymbol(obj)) { var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; } if (isElement(obj)) { var s = '<' + $toLowerCase.call(String(obj.nodeName)); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) { s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); } s += '>'; if (obj.childNodes && obj.childNodes.length) { s += '...'; } s += ''; return s; } if (isArray(obj)) { if (obj.length === 0) { return '[]'; } var xs = arrObjKeys(obj, inspect); if (indent && !singleLineValues(xs)) { return '[' + indentedJoin(xs, indent) + ']'; } return '[ ' + $join.call(xs, ', ') + ' ]'; } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; } if (parts.length === 0) { return '[' + String(obj) + ']'; } return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; } if (typeof obj === 'object' && customInspect) { if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { return utilInspect(obj, { depth: maxDepth - depth }); } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { return obj.inspect(); } } if (isMap(obj)) { var mapParts = []; if (mapForEach) { mapForEach.call(obj, function (value, key) { mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); }); } return collectionOf('Map', mapSize.call(obj), mapParts, indent); } if (isSet(obj)) { var setParts = []; if (setForEach) { setForEach.call(obj, function (value) { setParts.push(inspect(value, obj)); }); } return collectionOf('Set', setSize.call(obj), setParts, indent); } if (isWeakMap(obj)) { return weakCollectionOf('WeakMap'); } if (isWeakSet(obj)) { return weakCollectionOf('WeakSet'); } if (isWeakRef(obj)) { return weakCollectionOf('WeakRef'); } if (isNumber(obj)) { return markBoxed(inspect(Number(obj))); } if (isBigInt(obj)) { return markBoxed(inspect(bigIntValueOf.call(obj))); } if (isBoolean(obj)) { return markBoxed(booleanValueOf.call(obj)); } if (isString(obj)) { return markBoxed(inspect(String(obj))); } // note: in IE 8, sometimes `global !== window` but both are the prototypes of each other /* eslint-env browser */ if (typeof window !== 'undefined' && obj === window) { return '{ [object Window] }'; } if ( (typeof globalThis !== 'undefined' && obj === globalThis) || (typeof global !== 'undefined' && obj === global) ) { return '{ [object globalThis] }'; } if (!isDate(obj) && !isRegExp(obj)) { var ys = arrObjKeys(obj, inspect); var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; var protoTag = obj instanceof Object ? '' : 'null prototype'; var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); if (ys.length === 0) { return tag + '{}'; } if (indent) { return tag + '{' + indentedJoin(ys, indent) + '}'; } return tag + '{ ' + $join.call(ys, ', ') + ' }'; } return String(obj); }; function wrapQuotes(s, defaultStyle, opts) { var style = opts.quoteStyle || defaultStyle; var quoteChar = quotes[style]; return quoteChar + s + quoteChar; } function quote(s) { return $replace.call(String(s), /"/g, '"'); } function canTrustToString(obj) { return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); } function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives function isSymbol(obj) { if (hasShammedSymbols) { return obj && typeof obj === 'object' && obj instanceof Symbol; } if (typeof obj === 'symbol') { return true; } if (!obj || typeof obj !== 'object' || !symToString) { return false; } try { symToString.call(obj); return true; } catch (e) {} return false; } function isBigInt(obj) { if (!obj || typeof obj !== 'object' || !bigIntValueOf) { return false; } try { bigIntValueOf.call(obj); return true; } catch (e) {} return false; } var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; function has(obj, key) { return hasOwn.call(obj, key); } function toStr(obj) { return objectToString.call(obj); } function nameOf(f) { if (f.name) { return f.name; } var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); if (m) { return m[1]; } return null; } function indexOf(xs, x) { if (xs.indexOf) { return xs.indexOf(x); } for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) { return i; } } return -1; } function isMap(x) { if (!mapSize || !x || typeof x !== 'object') { return false; } try { mapSize.call(x); try { setSize.call(x); } catch (s) { return true; } return x instanceof Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakMap(x) { if (!weakMapHas || !x || typeof x !== 'object') { return false; } try { weakMapHas.call(x, weakMapHas); try { weakSetHas.call(x, weakSetHas); } catch (s) { return true; } return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakRef(x) { if (!weakRefDeref || !x || typeof x !== 'object') { return false; } try { weakRefDeref.call(x); return true; } catch (e) {} return false; } function isSet(x) { if (!setSize || !x || typeof x !== 'object') { return false; } try { setSize.call(x); try { mapSize.call(x); } catch (m) { return true; } return x instanceof Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakSet(x) { if (!weakSetHas || !x || typeof x !== 'object') { return false; } try { weakSetHas.call(x, weakSetHas); try { weakMapHas.call(x, weakMapHas); } catch (s) { return true; } return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isElement(x) { if (!x || typeof x !== 'object') { return false; } if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { return true; } return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; } function inspectString(str, opts) { if (str.length > opts.maxStringLength) { var remaining = str.length - opts.maxStringLength; var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; } var quoteRE = quoteREs[opts.quoteStyle || 'single']; quoteRE.lastIndex = 0; // eslint-disable-next-line no-control-regex var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); return wrapQuotes(s, 'single', opts); } function lowbyte(c) { var n = c.charCodeAt(0); var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; if (x) { return '\\' + x; } return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); } function markBoxed(str) { return 'Object(' + str + ')'; } function weakCollectionOf(type) { return type + ' { ? }'; } function collectionOf(type, size, entries, indent) { var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); return type + ' (' + size + ') {' + joinedEntries + '}'; } function singleLineValues(xs) { for (var i = 0; i < xs.length; i++) { if (indexOf(xs[i], '\n') >= 0) { return false; } } return true; } function getIndent(opts, depth) { var baseIndent; if (opts.indent === '\t') { baseIndent = '\t'; } else if (typeof opts.indent === 'number' && opts.indent > 0) { baseIndent = $join.call(Array(opts.indent + 1), ' '); } else { return null; } return { base: baseIndent, prev: $join.call(Array(depth + 1), baseIndent) }; } function indentedJoin(xs, indent) { if (xs.length === 0) { return ''; } var lineJoiner = '\n' + indent.prev + indent.base; return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; } function arrObjKeys(obj, inspect) { var isArr = isArray(obj); var xs = []; if (isArr) { xs.length = obj.length; for (var i = 0; i < obj.length; i++) { xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; } } var syms = typeof gOPS === 'function' ? gOPS(obj) : []; var symMap; if (hasShammedSymbols) { symMap = {}; for (var k = 0; k < syms.length; k++) { symMap['$' + syms[k]] = syms[k]; } } for (var key in obj) { // eslint-disable-line no-restricted-syntax if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section continue; // eslint-disable-line no-restricted-syntax, no-continue } else if ($test.call(/[^\w$]/, key)) { xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); } else { xs.push(key + ': ' + inspect(obj[key], obj)); } } if (typeof gOPS === 'function') { for (var j = 0; j < syms.length; j++) { if (isEnumerable.call(obj, syms[j])) { xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); } } } return xs; } /***/ }), /***/ 8502: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(9023).inspect; /***/ }), /***/ 2530: /***/ ((module) => { var numberIsNaN = function (value) { return value !== value; }; module.exports = function is(a, b) { if (a === 0 && b === 0) { return 1 / a === 1 / b; } if (a === b) { return true; } if (numberIsNaN(a) && numberIsNaN(b)) { return true; } return false; }; /***/ }), /***/ 4682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var define = __nccwpck_require__(191); var callBind = __nccwpck_require__(3844); var implementation = __nccwpck_require__(2530); var getPolyfill = __nccwpck_require__(9419); var shim = __nccwpck_require__(9069); var polyfill = callBind(getPolyfill(), Object); define(polyfill, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = polyfill; /***/ }), /***/ 9419: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var implementation = __nccwpck_require__(2530); module.exports = function getPolyfill() { return typeof Object.is === 'function' ? Object.is : implementation; }; /***/ }), /***/ 9069: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var getPolyfill = __nccwpck_require__(9419); var define = __nccwpck_require__(191); module.exports = function shimObjectIs() { var polyfill = getPolyfill(); define(Object, { is: polyfill }, { is: function testObjectIs() { return Object.is !== polyfill; } }); return polyfill; }; /***/ }), /***/ 226: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArgs = __nccwpck_require__(8598); // eslint-disable-line global-require var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } module.exports = keysShim; /***/ }), /***/ 2682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var slice = Array.prototype.slice; var isArgs = __nccwpck_require__(8598); var origKeys = Object.keys; var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __nccwpck_require__(226); var originalKeys = Object.keys; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2)); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArgs(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /***/ 8598: /***/ ((module) => { var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /***/ 4082: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // modified from https://github.com/es-shims/es6-shim var objectKeys = __nccwpck_require__(2682); var hasSymbols = __nccwpck_require__(1114)(); var callBound = __nccwpck_require__(3105); var $Object = __nccwpck_require__(5399); var $push = callBound('Array.prototype.push'); var $propIsEnumerable = callBound('Object.prototype.propertyIsEnumerable'); var originalGetSymbols = hasSymbols ? $Object.getOwnPropertySymbols : null; // eslint-disable-next-line no-unused-vars module.exports = function assign(target, source1) { if (target == null) { throw new TypeError('target must be an object'); } var to = $Object(target); // step 1 if (arguments.length === 1) { return to; // step 2 } for (var s = 1; s < arguments.length; ++s) { var from = $Object(arguments[s]); // step 3.a.i // step 3.a.ii: var keys = objectKeys(from); var getSymbols = hasSymbols && ($Object.getOwnPropertySymbols || originalGetSymbols); if (getSymbols) { var syms = getSymbols(from); for (var j = 0; j < syms.length; ++j) { var key = syms[j]; if ($propIsEnumerable(from, key)) { $push(keys, key); } } } // step 3.a.iii: for (var i = 0; i < keys.length; ++i) { var nextKey = keys[i]; if ($propIsEnumerable(from, nextKey)) { // step 3.a.iii.2 var propValue = from[nextKey]; // step 3.a.iii.2.a to[nextKey] = propValue; // step 3.a.iii.2.b } } } return to; // step 4 }; /***/ }), /***/ 3274: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var defineProperties = __nccwpck_require__(191); var callBind = __nccwpck_require__(3844); var implementation = __nccwpck_require__(4082); var getPolyfill = __nccwpck_require__(4987); var shim = __nccwpck_require__(2941); var polyfill = callBind.apply(getPolyfill()); // eslint-disable-next-line no-unused-vars var bound = function assign(target, source1) { return polyfill(Object, arguments); }; defineProperties(bound, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = bound; /***/ }), /***/ 4987: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var implementation = __nccwpck_require__(4082); var lacksProperEnumerationOrder = function () { if (!Object.assign) { return false; } /* * v8, specifically in node 4.x, has a bug with incorrect property enumeration order * note: this does not detect the bug unless there's 20 characters */ var str = 'abcdefghijklmnopqrst'; var letters = str.split(''); var map = {}; for (var i = 0; i < letters.length; ++i) { map[letters[i]] = letters[i]; } var obj = Object.assign({}, map); var actual = ''; for (var k in obj) { actual += k; } return str !== actual; }; var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } /* * Firefox 37 still has "pending exception" logic in its Object.assign implementation, * which is 72% slower than our shim, and Firefox 40's native implementation. */ var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } return false; }; module.exports = function getPolyfill() { if (!Object.assign) { return implementation; } if (lacksProperEnumerationOrder()) { return implementation; } if (assignHasPendingExceptions()) { return implementation; } return Object.assign; }; /***/ }), /***/ 2941: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var define = __nccwpck_require__(191); var getPolyfill = __nccwpck_require__(4987); module.exports = function shimAssign() { var polyfill = getPolyfill(); define( Object, { assign: polyfill }, { assign: function () { return Object.assign !== polyfill; } } ); return polyfill; }; /***/ }), /***/ 8879: /***/ ((module) => { /** @type {import('.')} */ module.exports = [ 'Float16Array', 'Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'BigInt64Array', 'BigUint64Array' ]; /***/ }), /***/ 6968: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var setFunctionName = __nccwpck_require__(297); var $TypeError = __nccwpck_require__(3314); var $Object = Object; module.exports = setFunctionName(function flags() { if (this == null || this !== $Object(this)) { throw new $TypeError('RegExp.prototype.flags getter called on non-object'); } var result = ''; if (this.hasIndices) { result += 'd'; } if (this.global) { result += 'g'; } if (this.ignoreCase) { result += 'i'; } if (this.multiline) { result += 'm'; } if (this.dotAll) { result += 's'; } if (this.unicode) { result += 'u'; } if (this.unicodeSets) { result += 'v'; } if (this.sticky) { result += 'y'; } return result; }, 'get flags', true); /***/ }), /***/ 1972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var define = __nccwpck_require__(191); var callBind = __nccwpck_require__(3844); var implementation = __nccwpck_require__(6968); var getPolyfill = __nccwpck_require__(5261); var shim = __nccwpck_require__(6123); var flagsBound = callBind(getPolyfill()); define(flagsBound, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = flagsBound; /***/ }), /***/ 5261: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var implementation = __nccwpck_require__(6968); var supportsDescriptors = (__nccwpck_require__(191).supportsDescriptors); var $gOPD = Object.getOwnPropertyDescriptor; module.exports = function getPolyfill() { if (supportsDescriptors && (/a/mig).flags === 'gim') { var descriptor = $gOPD(RegExp.prototype, 'flags'); if ( descriptor && typeof descriptor.get === 'function' && 'dotAll' in RegExp.prototype && 'hasIndices' in RegExp.prototype ) { /* eslint getter-return: 0 */ var calls = ''; var o = {}; Object.defineProperty(o, 'hasIndices', { get: function () { calls += 'd'; } }); Object.defineProperty(o, 'sticky', { get: function () { calls += 'y'; } }); descriptor.get.call(o); if (calls === 'dy') { return descriptor.get; } } } return implementation; }; /***/ }), /***/ 6123: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var supportsDescriptors = (__nccwpck_require__(191).supportsDescriptors); var getPolyfill = __nccwpck_require__(5261); var gOPD = __nccwpck_require__(3170); var defineProperty = Object.defineProperty; var $TypeError = __nccwpck_require__(1620); var getProto = __nccwpck_require__(1967); var regex = /a/; module.exports = function shimFlags() { if (!supportsDescriptors || !getProto) { throw new $TypeError('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors'); } var polyfill = getPolyfill(); var proto = getProto(regex); var descriptor = gOPD(proto, 'flags'); if (!descriptor || descriptor.get !== polyfill) { defineProperty(proto, 'flags', { configurable: true, enumerable: false, get: polyfill }); } return polyfill; }; /***/ }), /***/ 3470: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var callBound = __nccwpck_require__(3105); var isRegex = __nccwpck_require__(6622); var $exec = callBound('RegExp.prototype.exec'); var $TypeError = __nccwpck_require__(3314); /** @type {import('.')} */ module.exports = function regexTester(regex) { if (!isRegex(regex)) { throw new $TypeError('`regex` must be a RegExp'); } return function test(s) { return $exec(regex, s) !== null; }; }; /***/ }), /***/ 9346: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var GetIntrinsic = __nccwpck_require__(470); var define = __nccwpck_require__(1316); var hasDescriptors = __nccwpck_require__(497)(); var gOPD = __nccwpck_require__(3170); var $TypeError = __nccwpck_require__(3314); var $floor = GetIntrinsic('%Math.floor%'); /** @type {import('.')} */ module.exports = function setFunctionLength(fn, length) { if (typeof fn !== 'function') { throw new $TypeError('`fn` is not a function'); } if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { throw new $TypeError('`length` must be a positive 32-bit integer'); } var loose = arguments.length > 2 && !!arguments[2]; var functionLengthIsConfigurable = true; var functionLengthIsWritable = true; if ('length' in fn && gOPD) { var desc = gOPD(fn, 'length'); if (desc && !desc.configurable) { functionLengthIsConfigurable = false; } if (desc && !desc.writable) { functionLengthIsWritable = false; } } if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { if (hasDescriptors) { define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); } else { define(/** @type {Parameters[0]} */ (fn), 'length', length); } } return fn; }; /***/ }), /***/ 297: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var define = __nccwpck_require__(1316); var hasDescriptors = __nccwpck_require__(497)(); var functionsHaveConfigurableNames = (__nccwpck_require__(1327).functionsHaveConfigurableNames)(); var $TypeError = __nccwpck_require__(3314); /** @type {import('.')} */ module.exports = function setFunctionName(fn, name) { if (typeof fn !== 'function') { throw new $TypeError('`fn` is not a function'); } var loose = arguments.length > 2 && !!arguments[2]; if (!loose || functionsHaveConfigurableNames) { if (hasDescriptors) { define(/** @type {Parameters[0]} */ (fn), 'name', name, true, true); } else { define(/** @type {Parameters[0]} */ (fn), 'name', name); } } return fn; }; /***/ }), /***/ 8948: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var inspect = __nccwpck_require__(506); var $TypeError = __nccwpck_require__(3314); /* * This function traverses the list returning the node corresponding to the given key. * * That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. * By doing so, all the recently used nodes can be accessed relatively quickly. */ /** @type {import('./list.d.ts').listGetNode} */ // eslint-disable-next-line consistent-return var listGetNode = function (list, key, isDelete) { /** @type {typeof list | NonNullable<(typeof list)['next']>} */ var prev = list; /** @type {(typeof list)['next']} */ var curr; // eslint-disable-next-line eqeqeq for (; (curr = prev.next) != null; prev = curr) { if (curr.key === key) { prev.next = curr.next; if (!isDelete) { // eslint-disable-next-line no-extra-parens curr.next = /** @type {NonNullable} */ (list.next); list.next = curr; // eslint-disable-line no-param-reassign } return curr; } } }; /** @type {import('./list.d.ts').listGet} */ var listGet = function (objects, key) { if (!objects) { return void undefined; } var node = listGetNode(objects, key); return node && node.value; }; /** @type {import('./list.d.ts').listSet} */ var listSet = function (objects, key, value) { var node = listGetNode(objects, key); if (node) { node.value = value; } else { // Prepend the new node to the beginning of the list objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens key: key, next: objects.next, value: value }); } }; /** @type {import('./list.d.ts').listHas} */ var listHas = function (objects, key) { if (!objects) { return false; } return !!listGetNode(objects, key); }; /** @type {import('./list.d.ts').listDelete} */ // eslint-disable-next-line consistent-return var listDelete = function (objects, key) { if (objects) { return listGetNode(objects, key, true); } }; /** @type {import('.')} */ module.exports = function getSideChannelList() { /** @typedef {ReturnType} Channel */ /** @typedef {Parameters[0]} K */ /** @typedef {Parameters[1]} V */ /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { var deletedNode = listDelete($o, key); if (deletedNode && $o && !$o.next) { $o = void undefined; } return !!deletedNode; }, get: function (key) { return listGet($o, key); }, has: function (key) { return listHas($o, key); }, set: function (key, value) { if (!$o) { // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head $o = { next: void undefined }; } // eslint-disable-next-line no-extra-parens listSet(/** @type {NonNullable} */ ($o), key, value); } }; return channel; }; /***/ }), /***/ 2622: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var GetIntrinsic = __nccwpck_require__(470); var callBound = __nccwpck_require__(3105); var inspect = __nccwpck_require__(506); var $TypeError = __nccwpck_require__(3314); var $Map = GetIntrinsic('%Map%', true); /** @type {(thisArg: Map, key: K) => V} */ var $mapGet = callBound('Map.prototype.get', true); /** @type {(thisArg: Map, key: K, value: V) => void} */ var $mapSet = callBound('Map.prototype.set', true); /** @type {(thisArg: Map, key: K) => boolean} */ var $mapHas = callBound('Map.prototype.has', true); /** @type {(thisArg: Map, key: K) => boolean} */ var $mapDelete = callBound('Map.prototype.delete', true); /** @type {(thisArg: Map) => number} */ var $mapSize = callBound('Map.prototype.size', true); /** @type {import('.')} */ module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { /** @typedef {ReturnType} Channel */ /** @typedef {Parameters[0]} K */ /** @typedef {Parameters[1]} V */ /** @type {Map | undefined} */ var $m; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { if ($m) { var result = $mapDelete($m, key); if ($mapSize($m) === 0) { $m = void undefined; } return result; } return false; }, get: function (key) { // eslint-disable-line consistent-return if ($m) { return $mapGet($m, key); } }, has: function (key) { if ($m) { return $mapHas($m, key); } return false; }, set: function (key, value) { if (!$m) { // @ts-expect-error TS can't handle narrowing a variable inside a closure $m = new $Map(); } $mapSet($m, key, value); } }; // @ts-expect-error TODO: figure out why TS is erroring here return channel; }; /***/ }), /***/ 2870: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var GetIntrinsic = __nccwpck_require__(470); var callBound = __nccwpck_require__(3105); var inspect = __nccwpck_require__(506); var getSideChannelMap = __nccwpck_require__(2622); var $TypeError = __nccwpck_require__(3314); var $WeakMap = GetIntrinsic('%WeakMap%', true); /** @type {(thisArg: WeakMap, key: K) => V} */ var $weakMapGet = callBound('WeakMap.prototype.get', true); /** @type {(thisArg: WeakMap, key: K, value: V) => void} */ var $weakMapSet = callBound('WeakMap.prototype.set', true); /** @type {(thisArg: WeakMap, key: K) => boolean} */ var $weakMapHas = callBound('WeakMap.prototype.has', true); /** @type {(thisArg: WeakMap, key: K) => boolean} */ var $weakMapDelete = callBound('WeakMap.prototype.delete', true); /** @type {import('.')} */ module.exports = $WeakMap ? /** @type {Exclude} */ function getSideChannelWeakMap() { /** @typedef {ReturnType} Channel */ /** @typedef {Parameters[0]} K */ /** @typedef {Parameters[1]} V */ /** @type {WeakMap | undefined} */ var $wm; /** @type {Channel | undefined} */ var $m; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, 'delete': function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapDelete($wm, key); } } else if (getSideChannelMap) { if ($m) { return $m['delete'](key); } } return false; }, get: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapGet($wm, key); } } return $m && $m.get(key); }, has: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapHas($wm, key); } } return !!$m && $m.has(key); }, set: function (key, value) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if (!$wm) { $wm = new $WeakMap(); } $weakMapSet($wm, key, value); } else if (getSideChannelMap) { if (!$m) { $m = getSideChannelMap(); } // eslint-disable-next-line no-extra-parens /** @type {NonNullable} */ ($m).set(key, value); } } }; // @ts-expect-error TODO: figure out why this is erroring return channel; } : getSideChannelMap; /***/ }), /***/ 4753: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var $TypeError = __nccwpck_require__(3314); var inspect = __nccwpck_require__(506); var getSideChannelList = __nccwpck_require__(8948); var getSideChannelMap = __nccwpck_require__(2622); var getSideChannelWeakMap = __nccwpck_require__(2870); var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; /** @type {import('.')} */ module.exports = function getSideChannel() { /** @typedef {ReturnType} Channel */ /** @type {Channel | undefined} */ var $channelData; /** @type {Channel} */ var channel = { assert: function (key) { if (!channel.has(key)) { var keyDesc = key && Object(key) === key ? 'the given object key' : inspect(key); throw new $TypeError('Side channel does not contain ' + keyDesc); } }, 'delete': function (key) { return !!$channelData && $channelData['delete'](key); }, get: function (key) { return $channelData && $channelData.get(key); }, has: function (key) { return !!$channelData && $channelData.has(key); }, set: function (key, value) { if (!$channelData) { $channelData = makeChannel(); } $channelData.set(key, value); } }; return channel; }; /***/ }), /***/ 770: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(218); /***/ }), /***/ 218: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { var __webpack_unused_export__; var net = __nccwpck_require__(9278); var tls = __nccwpck_require__(4756); var http = __nccwpck_require__(8611); var https = __nccwpck_require__(5692); var events = __nccwpck_require__(4434); var assert = __nccwpck_require__(2613); var util = __nccwpck_require__(9023); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } __webpack_unused_export__ = debug; // for test /***/ }), /***/ 6752: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var __webpack_unused_export__; const Client = __nccwpck_require__(3701) const Dispatcher = __nccwpck_require__(883) const Pool = __nccwpck_require__(628) const BalancedPool = __nccwpck_require__(837) const Agent = __nccwpck_require__(7405) const ProxyAgent = __nccwpck_require__(6672) const EnvHttpProxyAgent = __nccwpck_require__(3137) const RetryAgent = __nccwpck_require__(50) const errors = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { InvalidArgumentError } = errors const api = __nccwpck_require__(6615) const buildConnector = __nccwpck_require__(9136) const MockClient = __nccwpck_require__(7365) const MockAgent = __nccwpck_require__(7501) const MockPool = __nccwpck_require__(4004) const mockErrors = __nccwpck_require__(2429) const RetryHandler = __nccwpck_require__(7816) const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) const DecoratorHandler = __nccwpck_require__(8155) const RedirectHandler = __nccwpck_require__(8754) const createRedirectInterceptor = __nccwpck_require__(5092) Object.assign(Dispatcher.prototype, api) __webpack_unused_export__ = Dispatcher __webpack_unused_export__ = Client __webpack_unused_export__ = Pool __webpack_unused_export__ = BalancedPool __webpack_unused_export__ = Agent module.exports.kT = ProxyAgent __webpack_unused_export__ = EnvHttpProxyAgent __webpack_unused_export__ = RetryAgent __webpack_unused_export__ = RetryHandler __webpack_unused_export__ = DecoratorHandler __webpack_unused_export__ = RedirectHandler __webpack_unused_export__ = createRedirectInterceptor __webpack_unused_export__ = { redirect: __nccwpck_require__(1514), retry: __nccwpck_require__(2026), dump: __nccwpck_require__(8060), dns: __nccwpck_require__(379) } __webpack_unused_export__ = buildConnector __webpack_unused_export__ = errors __webpack_unused_export__ = { parseHeaders: util.parseHeaders, headerNameToString: util.headerNameToString } function makeDispatcher (fn) { return (url, opts, handler) => { if (typeof opts === 'function') { handler = opts opts = null } if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { throw new InvalidArgumentError('invalid url') } if (opts != null && typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (opts && opts.path != null) { if (typeof opts.path !== 'string') { throw new InvalidArgumentError('invalid opts.path') } let path = opts.path if (!opts.path.startsWith('/')) { path = `/${path}` } url = new URL(util.parseOrigin(url).origin + path) } else { if (!opts) { opts = typeof url === 'object' ? url : {} } url = util.parseURL(url) } const { agent, dispatcher = getGlobalDispatcher() } = opts if (agent) { throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } return fn.call(dispatcher, { ...opts, origin: url.origin, path: url.search ? `${url.pathname}${url.search}` : url.pathname, method: opts.method || (opts.body ? 'PUT' : 'GET') }, handler) } } __webpack_unused_export__ = setGlobalDispatcher __webpack_unused_export__ = getGlobalDispatcher const fetchImpl = (__nccwpck_require__(4398).fetch) __webpack_unused_export__ = async function fetch (init, options = undefined) { try { return await fetchImpl(init, options) } catch (err) { if (err && typeof err === 'object') { Error.captureStackTrace(err) } throw err } } /* unused reexport */ __nccwpck_require__(660).Headers /* unused reexport */ __nccwpck_require__(9051).Response /* unused reexport */ __nccwpck_require__(9967).Request /* unused reexport */ __nccwpck_require__(5910).FormData __webpack_unused_export__ = globalThis.File ?? (__nccwpck_require__(4573).File) /* unused reexport */ __nccwpck_require__(8355).FileReader const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1059) __webpack_unused_export__ = setGlobalOrigin __webpack_unused_export__ = getGlobalOrigin const { CacheStorage } = __nccwpck_require__(3245) const { kConstruct } = __nccwpck_require__(109) // Cache & CacheStorage are tightly coupled with fetch. Even if it may run // in an older version of Node, it doesn't have any use without fetch. __webpack_unused_export__ = new CacheStorage(kConstruct) const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(9061) __webpack_unused_export__ = deleteCookie __webpack_unused_export__ = getCookies __webpack_unused_export__ = getSetCookies __webpack_unused_export__ = setCookie const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(1900) __webpack_unused_export__ = parseMIMEType __webpack_unused_export__ = serializeAMimeType const { CloseEvent, ErrorEvent, MessageEvent } = __nccwpck_require__(5188) /* unused reexport */ __nccwpck_require__(3726).WebSocket __webpack_unused_export__ = CloseEvent __webpack_unused_export__ = ErrorEvent __webpack_unused_export__ = MessageEvent __webpack_unused_export__ = makeDispatcher(api.request) __webpack_unused_export__ = makeDispatcher(api.stream) __webpack_unused_export__ = makeDispatcher(api.pipeline) __webpack_unused_export__ = makeDispatcher(api.connect) __webpack_unused_export__ = makeDispatcher(api.upgrade) __webpack_unused_export__ = MockClient __webpack_unused_export__ = MockPool __webpack_unused_export__ = MockAgent __webpack_unused_export__ = mockErrors const { EventSource } = __nccwpck_require__(1238) __webpack_unused_export__ = EventSource /***/ }), /***/ 158: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { addAbortListener } = __nccwpck_require__(3440) const { RequestAbortedError } = __nccwpck_require__(8707) const kListener = Symbol('kListener') const kSignal = Symbol('kSignal') function abort (self) { if (self.abort) { self.abort(self[kSignal]?.reason) } else { self.reason = self[kSignal]?.reason ?? new RequestAbortedError() } removeSignal(self) } function addSignal (self, signal) { self.reason = null self[kSignal] = null self[kListener] = null if (!signal) { return } if (signal.aborted) { abort(self) return } self[kSignal] = signal self[kListener] = () => { abort(self) } addAbortListener(self[kSignal], self[kListener]) } function removeSignal (self) { if (!self[kSignal]) { return } if ('removeEventListener' in self[kSignal]) { self[kSignal].removeEventListener('abort', self[kListener]) } else { self[kSignal].removeListener('abort', self[kListener]) } self[kSignal] = null self[kListener] = null } module.exports = { addSignal, removeSignal } /***/ }), /***/ 2279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { AsyncResource } = __nccwpck_require__(6698) const { InvalidArgumentError, SocketError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { addSignal, removeSignal } = __nccwpck_require__(158) class ConnectHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } const { signal, opaque, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } super('UNDICI_CONNECT') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.callback = callback this.abort = null addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders () { throw new SocketError('bad connect', null) } onUpgrade (statusCode, rawHeaders, socket) { const { callback, opaque, context } = this removeSignal(this) this.callback = null let headers = rawHeaders // Indicates is an HTTP2Session if (headers != null) { headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) } this.runInAsyncScope(callback, null, null, { statusCode, headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function connect (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { connect.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const connectHandler = new ConnectHandler(opts, callback) this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = connect /***/ }), /***/ 6862: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Readable, Duplex, PassThrough } = __nccwpck_require__(7075) const { InvalidArgumentError, InvalidReturnValueError, RequestAbortedError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { AsyncResource } = __nccwpck_require__(6698) const { addSignal, removeSignal } = __nccwpck_require__(158) const assert = __nccwpck_require__(4589) const kResume = Symbol('resume') class PipelineRequest extends Readable { constructor () { super({ autoDestroy: true }) this[kResume] = null } _read () { const { [kResume]: resume } = this if (resume) { this[kResume] = null resume() } } _destroy (err, callback) { this._read() callback(err) } } class PipelineResponse extends Readable { constructor (resume) { super({ autoDestroy: true }) this[kResume] = resume } _read () { this[kResume]() } _destroy (err, callback) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } callback(err) } } class PipelineHandler extends AsyncResource { constructor (opts, handler) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof handler !== 'function') { throw new InvalidArgumentError('invalid handler') } const { signal, method, opaque, onInfo, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_PIPELINE') this.opaque = opaque || null this.responseHeaders = responseHeaders || null this.handler = handler this.abort = null this.context = null this.onInfo = onInfo || null this.req = new PipelineRequest().on('error', util.nop) this.ret = new Duplex({ readableObjectMode: opts.objectMode, autoDestroy: true, read: () => { const { body } = this if (body?.resume) { body.resume() } }, write: (chunk, encoding, callback) => { const { req } = this if (req.push(chunk, encoding) || req._readableState.destroyed) { callback() } else { req[kResume] = callback } }, destroy: (err, callback) => { const { body, req, res, ret, abort } = this if (!err && !ret._readableState.endEmitted) { err = new RequestAbortedError() } if (abort && err) { abort() } util.destroy(body, err) util.destroy(req, err) util.destroy(res, err) removeSignal(this) callback(err) } }).on('prefinish', () => { const { req } = this // Node < 15 does not call _final in same tick. req.push(null) }) this.res = null addSignal(this, signal) } onConnect (abort, context) { const { ret, res } = this if (this.reason) { abort(this.reason) return } assert(!res, 'pipeline cannot be retried') assert(!ret.destroyed) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume) { const { opaque, handler, context } = this if (statusCode < 200) { if (this.onInfo) { const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.onInfo({ statusCode, headers }) } return } this.res = new PipelineResponse(resume) let body try { this.handler = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) body = this.runInAsyncScope(handler, null, { statusCode, headers, opaque, body: this.res, context }) } catch (err) { this.res.on('error', util.nop) throw err } if (!body || typeof body.on !== 'function') { throw new InvalidReturnValueError('expected Readable') } body .on('data', (chunk) => { const { ret, body } = this if (!ret.push(chunk) && body.pause) { body.pause() } }) .on('error', (err) => { const { ret } = this util.destroy(ret, err) }) .on('end', () => { const { ret } = this ret.push(null) }) .on('close', () => { const { ret } = this if (!ret._readableState.ended) { util.destroy(ret, new RequestAbortedError()) } }) this.body = body } onData (chunk) { const { res } = this return res.push(chunk) } onComplete (trailers) { const { res } = this res.push(null) } onError (err) { const { ret } = this this.handler = null util.destroy(ret, err) } } function pipeline (opts, handler) { try { const pipelineHandler = new PipelineHandler(opts, handler) this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) return pipelineHandler.ret } catch (err) { return new PassThrough().destroy(err) } } module.exports = pipeline /***/ }), /***/ 4043: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { Readable } = __nccwpck_require__(9927) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) const { AsyncResource } = __nccwpck_require__(6698) class RequestHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { throw new InvalidArgumentError('invalid highWaterMark') } if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_REQUEST') } catch (err) { if (util.isStream(body)) { util.destroy(body.on('error', util.nop), err) } throw err } this.method = method this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.res = null this.abort = null this.body = body this.trailers = {} this.context = null this.onInfo = onInfo || null this.throwOnError = throwOnError this.highWaterMark = highWaterMark this.signal = signal this.reason = null this.removeAbortListener = null if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } if (this.signal) { if (this.signal.aborted) { this.reason = this.signal.reason ?? new RequestAbortedError() } else { this.removeAbortListener = util.addAbortListener(this.signal, () => { this.reason = this.signal.reason ?? new RequestAbortedError() if (this.res) { util.destroy(this.res.on('error', util.nop), this.reason) } else if (this.abort) { this.abort(this.reason) } if (this.removeAbortListener) { this.res?.off('close', this.removeAbortListener) this.removeAbortListener() this.removeAbortListener = null } }) } } } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] const contentLength = parsedHeaders['content-length'] const res = new Readable({ resume, abort, contentType, contentLength: this.method !== 'HEAD' && contentLength ? Number(contentLength) : null, highWaterMark }) if (this.removeAbortListener) { res.on('close', this.removeAbortListener) } this.callback = null this.res = res if (callback !== null) { if (this.throwOnError && statusCode >= 400) { this.runInAsyncScope(getResolveErrorBodyCallback, null, { callback, body: res, contentType, statusCode, statusMessage, headers } ) } else { this.runInAsyncScope(callback, null, null, { statusCode, headers, trailers: this.trailers, opaque, body: res, context }) } } } onData (chunk) { return this.res.push(chunk) } onComplete (trailers) { util.parseHeaders(trailers, this.trailers) this.res.push(null) } onError (err) { const { res, callback, body, opaque } = this if (callback) { // TODO: Does this need queueMicrotask? this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (res) { this.res = null // Ensure all queued handlers are invoked before destroying res. queueMicrotask(() => { util.destroy(res, err) }) } if (body) { this.body = null util.destroy(body, err) } if (this.removeAbortListener) { res?.off('close', this.removeAbortListener) this.removeAbortListener() this.removeAbortListener = null } } } function request (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { request.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { this.dispatch(opts, new RequestHandler(opts, callback)) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = request module.exports.RequestHandler = RequestHandler /***/ }), /***/ 3560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { finished, PassThrough } = __nccwpck_require__(7075) const { InvalidArgumentError, InvalidReturnValueError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) const { AsyncResource } = __nccwpck_require__(6698) const { addSignal, removeSignal } = __nccwpck_require__(158) class StreamHandler extends AsyncResource { constructor (opts, factory, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts try { if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (typeof factory !== 'function') { throw new InvalidArgumentError('invalid factory') } if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } if (method === 'CONNECT') { throw new InvalidArgumentError('invalid method') } if (onInfo && typeof onInfo !== 'function') { throw new InvalidArgumentError('invalid onInfo callback') } super('UNDICI_STREAM') } catch (err) { if (util.isStream(body)) { util.destroy(body.on('error', util.nop), err) } throw err } this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.factory = factory this.callback = callback this.res = null this.abort = null this.context = null this.trailers = null this.body = body this.onInfo = onInfo || null this.throwOnError = throwOnError || false if (util.isStream(body)) { body.on('error', (err) => { this.onError(err) }) } addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = context } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const { factory, opaque, context, callback, responseHeaders } = this const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) if (statusCode < 200) { if (this.onInfo) { this.onInfo({ statusCode, headers }) } return } this.factory = null let res if (this.throwOnError && statusCode >= 400) { const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers const contentType = parsedHeaders['content-type'] res = new PassThrough() this.callback = null this.runInAsyncScope(getResolveErrorBodyCallback, null, { callback, body: res, contentType, statusCode, statusMessage, headers } ) } else { if (factory === null) { return } res = this.runInAsyncScope(factory, null, { statusCode, headers, opaque, context }) if ( !res || typeof res.write !== 'function' || typeof res.end !== 'function' || typeof res.on !== 'function' ) { throw new InvalidReturnValueError('expected Writable') } // TODO: Avoid finished. It registers an unnecessary amount of listeners. finished(res, { readable: false }, (err) => { const { callback, res, opaque, trailers, abort } = this this.res = null if (err || !res.readable) { util.destroy(res, err) } this.callback = null this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) if (err) { abort() } }) } res.on('drain', resume) this.res = res const needDrain = res.writableNeedDrain !== undefined ? res.writableNeedDrain : res._writableState?.needDrain return needDrain !== true } onData (chunk) { const { res } = this return res ? res.write(chunk) : true } onComplete (trailers) { const { res } = this removeSignal(this) if (!res) { return } this.trailers = util.parseHeaders(trailers) res.end() } onError (err) { const { res, callback, opaque, body } = this removeSignal(this) this.factory = null if (res) { this.res = null util.destroy(res, err) } else if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } if (body) { this.body = null util.destroy(body, err) } } } function stream (opts, factory, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { stream.call(this, opts, factory, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { this.dispatch(opts, new StreamHandler(opts, factory, callback)) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = stream /***/ }), /***/ 1882: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { InvalidArgumentError, SocketError } = __nccwpck_require__(8707) const { AsyncResource } = __nccwpck_require__(6698) const util = __nccwpck_require__(3440) const { addSignal, removeSignal } = __nccwpck_require__(158) const assert = __nccwpck_require__(4589) class UpgradeHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } const { signal, opaque, responseHeaders } = opts if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } super('UNDICI_UPGRADE') this.responseHeaders = responseHeaders || null this.opaque = opaque || null this.callback = callback this.abort = null this.context = null addSignal(this, signal) } onConnect (abort, context) { if (this.reason) { abort(this.reason) return } assert(this.callback) this.abort = abort this.context = null } onHeaders () { throw new SocketError('bad upgrade', null) } onUpgrade (statusCode, rawHeaders, socket) { assert(statusCode === 101) const { callback, opaque, context } = this removeSignal(this) this.callback = null const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.runInAsyncScope(callback, null, null, { headers, socket, opaque, context }) } onError (err) { const { callback, opaque } = this removeSignal(this) if (callback) { this.callback = null queueMicrotask(() => { this.runInAsyncScope(callback, null, err, { opaque }) }) } } } function upgrade (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { upgrade.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { const upgradeHandler = new UpgradeHandler(opts, callback) this.dispatch({ ...opts, method: opts.method || 'GET', upgrade: opts.protocol || 'Websocket' }, upgradeHandler) } catch (err) { if (typeof callback !== 'function') { throw err } const opaque = opts?.opaque queueMicrotask(() => callback(err, { opaque })) } } module.exports = upgrade /***/ }), /***/ 6615: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports.request = __nccwpck_require__(4043) module.exports.stream = __nccwpck_require__(3560) module.exports.pipeline = __nccwpck_require__(6862) module.exports.upgrade = __nccwpck_require__(1882) module.exports.connect = __nccwpck_require__(2279) /***/ }), /***/ 9927: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Ported from https://github.com/nodejs/undici/pull/907 const assert = __nccwpck_require__(4589) const { Readable } = __nccwpck_require__(7075) const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { ReadableStreamFrom } = __nccwpck_require__(3440) const kConsume = Symbol('kConsume') const kReading = Symbol('kReading') const kBody = Symbol('kBody') const kAbort = Symbol('kAbort') const kContentType = Symbol('kContentType') const kContentLength = Symbol('kContentLength') const noop = () => {} class BodyReadable extends Readable { constructor ({ resume, abort, contentType = '', contentLength, highWaterMark = 64 * 1024 // Same as nodejs fs streams. }) { super({ autoDestroy: true, read: resume, highWaterMark }) this._readableState.dataEmitted = false this[kAbort] = abort this[kConsume] = null this[kBody] = null this[kContentType] = contentType this[kContentLength] = contentLength // Is stream being consumed through Readable API? // This is an optimization so that we avoid checking // for 'data' and 'readable' listeners in the hot path // inside push(). this[kReading] = false } destroy (err) { if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } if (err) { this[kAbort]() } return super.destroy(err) } _destroy (err, callback) { // Workaround for Node "bug". If the stream is destroyed in same // tick as it is created, then a user who is waiting for a // promise (i.e micro tick) for installing a 'error' listener will // never get a chance and will always encounter an unhandled exception. if (!this[kReading]) { setImmediate(() => { callback(err) }) } else { callback(err) } } on (ev, ...args) { if (ev === 'data' || ev === 'readable') { this[kReading] = true } return super.on(ev, ...args) } addListener (ev, ...args) { return this.on(ev, ...args) } off (ev, ...args) { const ret = super.off(ev, ...args) if (ev === 'data' || ev === 'readable') { this[kReading] = ( this.listenerCount('data') > 0 || this.listenerCount('readable') > 0 ) } return ret } removeListener (ev, ...args) { return this.off(ev, ...args) } push (chunk) { if (this[kConsume] && chunk !== null) { consumePush(this[kConsume], chunk) return this[kReading] ? super.push(chunk) : true } return super.push(chunk) } // https://fetch.spec.whatwg.org/#dom-body-text async text () { return consume(this, 'text') } // https://fetch.spec.whatwg.org/#dom-body-json async json () { return consume(this, 'json') } // https://fetch.spec.whatwg.org/#dom-body-blob async blob () { return consume(this, 'blob') } // https://fetch.spec.whatwg.org/#dom-body-bytes async bytes () { return consume(this, 'bytes') } // https://fetch.spec.whatwg.org/#dom-body-arraybuffer async arrayBuffer () { return consume(this, 'arrayBuffer') } // https://fetch.spec.whatwg.org/#dom-body-formdata async formData () { // TODO: Implement. throw new NotSupportedError() } // https://fetch.spec.whatwg.org/#dom-body-bodyused get bodyUsed () { return util.isDisturbed(this) } // https://fetch.spec.whatwg.org/#dom-body-body get body () { if (!this[kBody]) { this[kBody] = ReadableStreamFrom(this) if (this[kConsume]) { // TODO: Is this the best way to force a lock? this[kBody].getReader() // Ensure stream is locked. assert(this[kBody].locked) } } return this[kBody] } async dump (opts) { let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024 const signal = opts?.signal if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) { throw new InvalidArgumentError('signal must be an AbortSignal') } signal?.throwIfAborted() if (this._readableState.closeEmitted) { return null } return await new Promise((resolve, reject) => { if (this[kContentLength] > limit) { this.destroy(new AbortError()) } const onAbort = () => { this.destroy(signal.reason ?? new AbortError()) } signal?.addEventListener('abort', onAbort) this .on('close', function () { signal?.removeEventListener('abort', onAbort) if (signal?.aborted) { reject(signal.reason ?? new AbortError()) } else { resolve(null) } }) .on('error', noop) .on('data', function (chunk) { limit -= chunk.length if (limit <= 0) { this.destroy() } }) .resume() }) } } // https://streams.spec.whatwg.org/#readablestream-locked function isLocked (self) { // Consume is an implicit lock. return (self[kBody] && self[kBody].locked === true) || self[kConsume] } // https://fetch.spec.whatwg.org/#body-unusable function isUnusable (self) { return util.isDisturbed(self) || isLocked(self) } async function consume (stream, type) { assert(!stream[kConsume]) return new Promise((resolve, reject) => { if (isUnusable(stream)) { const rState = stream._readableState if (rState.destroyed && rState.closeEmitted === false) { stream .on('error', err => { reject(err) }) .on('close', () => { reject(new TypeError('unusable')) }) } else { reject(rState.errored ?? new TypeError('unusable')) } } else { queueMicrotask(() => { stream[kConsume] = { type, stream, resolve, reject, length: 0, body: [] } stream .on('error', function (err) { consumeFinish(this[kConsume], err) }) .on('close', function () { if (this[kConsume].body !== null) { consumeFinish(this[kConsume], new RequestAbortedError()) } }) consumeStart(stream[kConsume]) }) } }) } function consumeStart (consume) { if (consume.body === null) { return } const { _readableState: state } = consume.stream if (state.bufferIndex) { const start = state.bufferIndex const end = state.buffer.length for (let n = start; n < end; n++) { consumePush(consume, state.buffer[n]) } } else { for (const chunk of state.buffer) { consumePush(consume, chunk) } } if (state.endEmitted) { consumeEnd(this[kConsume]) } else { consume.stream.on('end', function () { consumeEnd(this[kConsume]) }) } consume.stream.resume() while (consume.stream.read() != null) { // Loop } } /** * @param {Buffer[]} chunks * @param {number} length */ function chunksDecode (chunks, length) { if (chunks.length === 0 || length === 0) { return '' } const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length) const bufferLength = buffer.length // Skip BOM. const start = bufferLength > 2 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf ? 3 : 0 return buffer.utf8Slice(start, bufferLength) } /** * @param {Buffer[]} chunks * @param {number} length * @returns {Uint8Array} */ function chunksConcat (chunks, length) { if (chunks.length === 0 || length === 0) { return new Uint8Array(0) } if (chunks.length === 1) { // fast-path return new Uint8Array(chunks[0]) } const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer) let offset = 0 for (let i = 0; i < chunks.length; ++i) { const chunk = chunks[i] buffer.set(chunk, offset) offset += chunk.length } return buffer } function consumeEnd (consume) { const { type, body, resolve, stream, length } = consume try { if (type === 'text') { resolve(chunksDecode(body, length)) } else if (type === 'json') { resolve(JSON.parse(chunksDecode(body, length))) } else if (type === 'arrayBuffer') { resolve(chunksConcat(body, length).buffer) } else if (type === 'blob') { resolve(new Blob(body, { type: stream[kContentType] })) } else if (type === 'bytes') { resolve(chunksConcat(body, length)) } consumeFinish(consume) } catch (err) { stream.destroy(err) } } function consumePush (consume, chunk) { consume.length += chunk.length consume.body.push(chunk) } function consumeFinish (consume, err) { if (consume.body === null) { return } if (err) { consume.reject(err) } else { consume.resolve() } consume.type = null consume.stream = null consume.resolve = null consume.reject = null consume.length = 0 consume.body = null } module.exports = { Readable: BodyReadable, chunksDecode } /***/ }), /***/ 7655: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { ResponseStatusCodeError } = __nccwpck_require__(8707) const { chunksDecode } = __nccwpck_require__(9927) const CHUNK_LIMIT = 128 * 1024 async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { assert(body) let chunks = [] let length = 0 try { for await (const chunk of body) { chunks.push(chunk) length += chunk.length if (length > CHUNK_LIMIT) { chunks = [] length = 0 break } } } catch { chunks = [] length = 0 // Do nothing.... } const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}` if (statusCode === 204 || !contentType || !length) { queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers))) return } const stackTraceLimit = Error.stackTraceLimit Error.stackTraceLimit = 0 let payload try { if (isContentTypeApplicationJson(contentType)) { payload = JSON.parse(chunksDecode(chunks, length)) } else if (isContentTypeText(contentType)) { payload = chunksDecode(chunks, length) } } catch { // process in a callback to avoid throwing in the microtask queue } finally { Error.stackTraceLimit = stackTraceLimit } queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload))) } const isContentTypeApplicationJson = (contentType) => { return ( contentType.length > 15 && contentType[11] === '/' && contentType[0] === 'a' && contentType[1] === 'p' && contentType[2] === 'p' && contentType[3] === 'l' && contentType[4] === 'i' && contentType[5] === 'c' && contentType[6] === 'a' && contentType[7] === 't' && contentType[8] === 'i' && contentType[9] === 'o' && contentType[10] === 'n' && contentType[12] === 'j' && contentType[13] === 's' && contentType[14] === 'o' && contentType[15] === 'n' ) } const isContentTypeText = (contentType) => { return ( contentType.length > 4 && contentType[4] === '/' && contentType[0] === 't' && contentType[1] === 'e' && contentType[2] === 'x' && contentType[3] === 't' ) } module.exports = { getResolveErrorBodyCallback, isContentTypeApplicationJson, isContentTypeText } /***/ }), /***/ 9136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const net = __nccwpck_require__(7030) const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(3440) const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) const timers = __nccwpck_require__(6603) function noop () {} let tls // include tls conditionally since it is not always available // TODO: session re-use does not wait for the first // connection to resolve the session and might therefore // resolve the same servername multiple times even when // re-use is enabled. let SessionCache // FIXME: remove workaround when the Node bug is fixed // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 if (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) { SessionCache = class WeakSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() this._sessionRegistry = new global.FinalizationRegistry((key) => { if (this._sessionCache.size < this._maxCachedSessions) { return } const ref = this._sessionCache.get(key) if (ref !== undefined && ref.deref() === undefined) { this._sessionCache.delete(key) } }) } get (sessionKey) { const ref = this._sessionCache.get(sessionKey) return ref ? ref.deref() : null } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } this._sessionCache.set(sessionKey, new WeakRef(session)) this._sessionRegistry.register(session, sessionKey) } } } else { SessionCache = class SimpleSessionCache { constructor (maxCachedSessions) { this._maxCachedSessions = maxCachedSessions this._sessionCache = new Map() } get (sessionKey) { return this._sessionCache.get(sessionKey) } set (sessionKey, session) { if (this._maxCachedSessions === 0) { return } if (this._sessionCache.size >= this._maxCachedSessions) { // remove the oldest session const { value: oldestKey } = this._sessionCache.keys().next() this._sessionCache.delete(oldestKey) } this._sessionCache.set(sessionKey, session) } } } function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) { if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') } const options = { path: socketPath, ...opts } const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) timeout = timeout == null ? 10e3 : timeout allowH2 = allowH2 != null ? allowH2 : false return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { let socket if (protocol === 'https:') { if (!tls) { tls = __nccwpck_require__(1692) } servername = servername || options.servername || util.getServerName(host) || null const sessionKey = servername || hostname assert(sessionKey) const session = customSession || sessionCache.get(sessionKey) || null port = port || 443 socket = tls.connect({ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... ...options, servername, session, localAddress, // TODO(HTTP/2): Add support for h2c ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], socket: httpSocket, // upgrade socket connection port, host: hostname }) socket .on('session', function (session) { // TODO (fix): Can a session become invalid once established? Don't think so? sessionCache.set(sessionKey, session) }) } else { assert(!httpSocket, 'httpSocket can only be sent on TLS update') port = port || 80 socket = net.connect({ highWaterMark: 64 * 1024, // Same as nodejs fs streams. ...options, localAddress, port, host: hostname }) } // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket if (options.keepAlive == null || options.keepAlive) { const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay socket.setKeepAlive(true, keepAliveInitialDelay) } const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port }) socket .setNoDelay(true) .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(null, this) } }) .on('error', function (err) { queueMicrotask(clearConnectTimeout) if (callback) { const cb = callback callback = null cb(err) } }) return socket } } /** * @param {WeakRef} socketWeakRef * @param {object} opts * @param {number} opts.timeout * @param {string} opts.hostname * @param {number} opts.port * @returns {() => void} */ const setupConnectTimeout = process.platform === 'win32' ? (socketWeakRef, opts) => { if (!opts.timeout) { return noop } let s1 = null let s2 = null const fastTimer = timers.setFastTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { // Windows needs an extra setImmediate probably due to implementation differences in the socket logic s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts)) }) }, opts.timeout) return () => { timers.clearFastTimeout(fastTimer) clearImmediate(s1) clearImmediate(s2) } } : (socketWeakRef, opts) => { if (!opts.timeout) { return noop } let s1 = null const fastTimer = timers.setFastTimeout(() => { // setImmediate is added to make sure that we prioritize socket error events over timeouts s1 = setImmediate(() => { onConnectTimeout(socketWeakRef.deref(), opts) }) }, opts.timeout) return () => { timers.clearFastTimeout(fastTimer) clearImmediate(s1) } } /** * @param {net.Socket} socket * @param {object} opts * @param {number} opts.timeout * @param {string} opts.hostname * @param {number} opts.port */ function onConnectTimeout (socket, opts) { // The socket could be already garbage collected if (socket == null) { return } let message = 'Connect Timeout Error' if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) { message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},` } else { message += ` (attempted address: ${opts.hostname}:${opts.port},` } message += ` timeout: ${opts.timeout}ms)` util.destroy(socket, new ConnectTimeoutError(message)) } module.exports = buildConnector /***/ }), /***/ 735: /***/ ((module) => { /** @type {Record} */ const headerNameLowerCasedRecord = {} // https://developer.mozilla.org/docs/Web/HTTP/Headers const wellknownHeaderNames = [ 'Accept', 'Accept-Encoding', 'Accept-Language', 'Accept-Ranges', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Headers', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Origin', 'Access-Control-Expose-Headers', 'Access-Control-Max-Age', 'Access-Control-Request-Headers', 'Access-Control-Request-Method', 'Age', 'Allow', 'Alt-Svc', 'Alt-Used', 'Authorization', 'Cache-Control', 'Clear-Site-Data', 'Connection', 'Content-Disposition', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-Range', 'Content-Security-Policy', 'Content-Security-Policy-Report-Only', 'Content-Type', 'Cookie', 'Cross-Origin-Embedder-Policy', 'Cross-Origin-Opener-Policy', 'Cross-Origin-Resource-Policy', 'Date', 'Device-Memory', 'Downlink', 'ECT', 'ETag', 'Expect', 'Expect-CT', 'Expires', 'Forwarded', 'From', 'Host', 'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Range', 'If-Unmodified-Since', 'Keep-Alive', 'Last-Modified', 'Link', 'Location', 'Max-Forwards', 'Origin', 'Permissions-Policy', 'Pragma', 'Proxy-Authenticate', 'Proxy-Authorization', 'RTT', 'Range', 'Referer', 'Referrer-Policy', 'Refresh', 'Retry-After', 'Sec-WebSocket-Accept', 'Sec-WebSocket-Extensions', 'Sec-WebSocket-Key', 'Sec-WebSocket-Protocol', 'Sec-WebSocket-Version', 'Server', 'Server-Timing', 'Service-Worker-Allowed', 'Service-Worker-Navigation-Preload', 'Set-Cookie', 'SourceMap', 'Strict-Transport-Security', 'Supports-Loading-Mode', 'TE', 'Timing-Allow-Origin', 'Trailer', 'Transfer-Encoding', 'Upgrade', 'Upgrade-Insecure-Requests', 'User-Agent', 'Vary', 'Via', 'WWW-Authenticate', 'X-Content-Type-Options', 'X-DNS-Prefetch-Control', 'X-Frame-Options', 'X-Permitted-Cross-Domain-Policies', 'X-Powered-By', 'X-Requested-With', 'X-XSS-Protection' ] for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = wellknownHeaderNames[i] const lowerCasedKey = key.toLowerCase() headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey } // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(headerNameLowerCasedRecord, null) module.exports = { wellknownHeaderNames, headerNameLowerCasedRecord } /***/ }), /***/ 2414: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const diagnosticsChannel = __nccwpck_require__(3053) const util = __nccwpck_require__(7975) const undiciDebugLog = util.debuglog('undici') const fetchDebuglog = util.debuglog('fetch') const websocketDebuglog = util.debuglog('websocket') let isClientSet = false const channels = { // Client beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'), connected: diagnosticsChannel.channel('undici:client:connected'), connectError: diagnosticsChannel.channel('undici:client:connectError'), sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'), // Request create: diagnosticsChannel.channel('undici:request:create'), bodySent: diagnosticsChannel.channel('undici:request:bodySent'), headers: diagnosticsChannel.channel('undici:request:headers'), trailers: diagnosticsChannel.channel('undici:request:trailers'), error: diagnosticsChannel.channel('undici:request:error'), // WebSocket open: diagnosticsChannel.channel('undici:websocket:open'), close: diagnosticsChannel.channel('undici:websocket:close'), socketError: diagnosticsChannel.channel('undici:websocket:socket_error'), ping: diagnosticsChannel.channel('undici:websocket:ping'), pong: diagnosticsChannel.channel('undici:websocket:pong') } if (undiciDebugLog.enabled || fetchDebuglog.enabled) { const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog // Track all Client events diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connecting to %s using %s%s', `${host}${port ? `:${port}` : ''}`, protocol, version ) }) diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connected to %s using %s%s', `${host}${port ? `:${port}` : ''}`, protocol, version ) }) diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { const { connectParams: { version, protocol, port, host }, error } = evt debuglog( 'connection to %s using %s%s errored - %s', `${host}${port ? `:${port}` : ''}`, protocol, version, error.message ) }) diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { const { request: { method, path, origin } } = evt debuglog('sending request to %s %s/%s', method, origin, path) }) // Track Request events diagnosticsChannel.channel('undici:request:headers').subscribe(evt => { const { request: { method, path, origin }, response: { statusCode } } = evt debuglog( 'received response to %s %s/%s - HTTP %d', method, origin, path, statusCode ) }) diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => { const { request: { method, path, origin } } = evt debuglog('trailers received from %s %s/%s', method, origin, path) }) diagnosticsChannel.channel('undici:request:error').subscribe(evt => { const { request: { method, path, origin }, error } = evt debuglog( 'request to %s %s/%s errored - %s', method, origin, path, error.message ) }) isClientSet = true } if (websocketDebuglog.enabled) { if (!isClientSet) { const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connecting to %s%s using %s%s', host, port ? `:${port}` : '', protocol, version ) }) diagnosticsChannel.channel('undici:client:connected').subscribe(evt => { const { connectParams: { version, protocol, port, host } } = evt debuglog( 'connected to %s%s using %s%s', host, port ? `:${port}` : '', protocol, version ) }) diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => { const { connectParams: { version, protocol, port, host }, error } = evt debuglog( 'connection to %s%s using %s%s errored - %s', host, port ? `:${port}` : '', protocol, version, error.message ) }) diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => { const { request: { method, path, origin } } = evt debuglog('sending request to %s %s/%s', method, origin, path) }) } // Track all WebSocket events diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => { const { address: { address, port } } = evt websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '') }) diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => { const { websocket, code, reason } = evt websocketDebuglog( 'closed connection to %s - %s %s', websocket.url, code, reason ) }) diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => { websocketDebuglog('connection errored - %s', err.message) }) diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => { websocketDebuglog('ping received') }) diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => { websocketDebuglog('pong received') }) } module.exports = { channels } /***/ }), /***/ 8707: /***/ ((module) => { const kUndiciError = Symbol.for('undici.error.UND_ERR') class UndiciError extends Error { constructor (message) { super(message) this.name = 'UndiciError' this.code = 'UND_ERR' } static [Symbol.hasInstance] (instance) { return instance && instance[kUndiciError] === true } [kUndiciError] = true } const kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT') class ConnectTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'ConnectTimeoutError' this.message = message || 'Connect Timeout Error' this.code = 'UND_ERR_CONNECT_TIMEOUT' } static [Symbol.hasInstance] (instance) { return instance && instance[kConnectTimeoutError] === true } [kConnectTimeoutError] = true } const kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT') class HeadersTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'HeadersTimeoutError' this.message = message || 'Headers Timeout Error' this.code = 'UND_ERR_HEADERS_TIMEOUT' } static [Symbol.hasInstance] (instance) { return instance && instance[kHeadersTimeoutError] === true } [kHeadersTimeoutError] = true } const kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW') class HeadersOverflowError extends UndiciError { constructor (message) { super(message) this.name = 'HeadersOverflowError' this.message = message || 'Headers Overflow Error' this.code = 'UND_ERR_HEADERS_OVERFLOW' } static [Symbol.hasInstance] (instance) { return instance && instance[kHeadersOverflowError] === true } [kHeadersOverflowError] = true } const kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT') class BodyTimeoutError extends UndiciError { constructor (message) { super(message) this.name = 'BodyTimeoutError' this.message = message || 'Body Timeout Error' this.code = 'UND_ERR_BODY_TIMEOUT' } static [Symbol.hasInstance] (instance) { return instance && instance[kBodyTimeoutError] === true } [kBodyTimeoutError] = true } const kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE') class ResponseStatusCodeError extends UndiciError { constructor (message, statusCode, headers, body) { super(message) this.name = 'ResponseStatusCodeError' this.message = message || 'Response Status Code Error' this.code = 'UND_ERR_RESPONSE_STATUS_CODE' this.body = body this.status = statusCode this.statusCode = statusCode this.headers = headers } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseStatusCodeError] === true } [kResponseStatusCodeError] = true } const kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG') class InvalidArgumentError extends UndiciError { constructor (message) { super(message) this.name = 'InvalidArgumentError' this.message = message || 'Invalid Argument Error' this.code = 'UND_ERR_INVALID_ARG' } static [Symbol.hasInstance] (instance) { return instance && instance[kInvalidArgumentError] === true } [kInvalidArgumentError] = true } const kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE') class InvalidReturnValueError extends UndiciError { constructor (message) { super(message) this.name = 'InvalidReturnValueError' this.message = message || 'Invalid Return Value Error' this.code = 'UND_ERR_INVALID_RETURN_VALUE' } static [Symbol.hasInstance] (instance) { return instance && instance[kInvalidReturnValueError] === true } [kInvalidReturnValueError] = true } const kAbortError = Symbol.for('undici.error.UND_ERR_ABORT') class AbortError extends UndiciError { constructor (message) { super(message) this.name = 'AbortError' this.message = message || 'The operation was aborted' this.code = 'UND_ERR_ABORT' } static [Symbol.hasInstance] (instance) { return instance && instance[kAbortError] === true } [kAbortError] = true } const kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED') class RequestAbortedError extends AbortError { constructor (message) { super(message) this.name = 'AbortError' this.message = message || 'Request aborted' this.code = 'UND_ERR_ABORTED' } static [Symbol.hasInstance] (instance) { return instance && instance[kRequestAbortedError] === true } [kRequestAbortedError] = true } const kInformationalError = Symbol.for('undici.error.UND_ERR_INFO') class InformationalError extends UndiciError { constructor (message) { super(message) this.name = 'InformationalError' this.message = message || 'Request information' this.code = 'UND_ERR_INFO' } static [Symbol.hasInstance] (instance) { return instance && instance[kInformationalError] === true } [kInformationalError] = true } const kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') class RequestContentLengthMismatchError extends UndiciError { constructor (message) { super(message) this.name = 'RequestContentLengthMismatchError' this.message = message || 'Request body length does not match content-length header' this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' } static [Symbol.hasInstance] (instance) { return instance && instance[kRequestContentLengthMismatchError] === true } [kRequestContentLengthMismatchError] = true } const kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH') class ResponseContentLengthMismatchError extends UndiciError { constructor (message) { super(message) this.name = 'ResponseContentLengthMismatchError' this.message = message || 'Response body length does not match content-length header' this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseContentLengthMismatchError] === true } [kResponseContentLengthMismatchError] = true } const kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED') class ClientDestroyedError extends UndiciError { constructor (message) { super(message) this.name = 'ClientDestroyedError' this.message = message || 'The client is destroyed' this.code = 'UND_ERR_DESTROYED' } static [Symbol.hasInstance] (instance) { return instance && instance[kClientDestroyedError] === true } [kClientDestroyedError] = true } const kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED') class ClientClosedError extends UndiciError { constructor (message) { super(message) this.name = 'ClientClosedError' this.message = message || 'The client is closed' this.code = 'UND_ERR_CLOSED' } static [Symbol.hasInstance] (instance) { return instance && instance[kClientClosedError] === true } [kClientClosedError] = true } const kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET') class SocketError extends UndiciError { constructor (message, socket) { super(message) this.name = 'SocketError' this.message = message || 'Socket error' this.code = 'UND_ERR_SOCKET' this.socket = socket } static [Symbol.hasInstance] (instance) { return instance && instance[kSocketError] === true } [kSocketError] = true } const kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED') class NotSupportedError extends UndiciError { constructor (message) { super(message) this.name = 'NotSupportedError' this.message = message || 'Not supported error' this.code = 'UND_ERR_NOT_SUPPORTED' } static [Symbol.hasInstance] (instance) { return instance && instance[kNotSupportedError] === true } [kNotSupportedError] = true } const kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM') class BalancedPoolMissingUpstreamError extends UndiciError { constructor (message) { super(message) this.name = 'MissingUpstreamError' this.message = message || 'No upstream has been added to the BalancedPool' this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' } static [Symbol.hasInstance] (instance) { return instance && instance[kBalancedPoolMissingUpstreamError] === true } [kBalancedPoolMissingUpstreamError] = true } const kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER') class HTTPParserError extends Error { constructor (message, code, data) { super(message) this.name = 'HTTPParserError' this.code = code ? `HPE_${code}` : undefined this.data = data ? data.toString() : undefined } static [Symbol.hasInstance] (instance) { return instance && instance[kHTTPParserError] === true } [kHTTPParserError] = true } const kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE') class ResponseExceededMaxSizeError extends UndiciError { constructor (message) { super(message) this.name = 'ResponseExceededMaxSizeError' this.message = message || 'Response content exceeded max size' this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseExceededMaxSizeError] === true } [kResponseExceededMaxSizeError] = true } const kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY') class RequestRetryError extends UndiciError { constructor (message, code, { headers, data }) { super(message) this.name = 'RequestRetryError' this.message = message || 'Request retry error' this.code = 'UND_ERR_REQ_RETRY' this.statusCode = code this.data = data this.headers = headers } static [Symbol.hasInstance] (instance) { return instance && instance[kRequestRetryError] === true } [kRequestRetryError] = true } const kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE') class ResponseError extends UndiciError { constructor (message, code, { headers, data }) { super(message) this.name = 'ResponseError' this.message = message || 'Response error' this.code = 'UND_ERR_RESPONSE' this.statusCode = code this.data = data this.headers = headers } static [Symbol.hasInstance] (instance) { return instance && instance[kResponseError] === true } [kResponseError] = true } const kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS') class SecureProxyConnectionError extends UndiciError { constructor (cause, message, options) { super(message, { cause, ...(options ?? {}) }) this.name = 'SecureProxyConnectionError' this.message = message || 'Secure Proxy Connection failed' this.code = 'UND_ERR_PRX_TLS' this.cause = cause } static [Symbol.hasInstance] (instance) { return instance && instance[kSecureProxyConnectionError] === true } [kSecureProxyConnectionError] = true } const kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED') class MessageSizeExceededError extends UndiciError { constructor (message) { super(message) this.name = 'MessageSizeExceededError' this.message = message || 'Max decompressed message size exceeded' this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED' } static [Symbol.hasInstance] (instance) { return instance && instance[kMessageSizeExceededError] === true } get [kMessageSizeExceededError] () { return true } } module.exports = { AbortError, HTTPParserError, UndiciError, HeadersTimeoutError, HeadersOverflowError, BodyTimeoutError, RequestContentLengthMismatchError, ConnectTimeoutError, ResponseStatusCodeError, InvalidArgumentError, InvalidReturnValueError, RequestAbortedError, ClientDestroyedError, ClientClosedError, InformationalError, SocketError, NotSupportedError, ResponseContentLengthMismatchError, BalancedPoolMissingUpstreamError, ResponseExceededMaxSizeError, RequestRetryError, ResponseError, SecureProxyConnectionError, MessageSizeExceededError } /***/ }), /***/ 4655: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { InvalidArgumentError, NotSupportedError } = __nccwpck_require__(8707) const assert = __nccwpck_require__(4589) const { isValidHTTPToken, isValidHeaderValue, isStream, destroy, isBuffer, isFormDataLike, isIterable, isBlobLike, buildURL, validateHandler, getServerName, normalizedMethodRecords } = __nccwpck_require__(3440) const { channels } = __nccwpck_require__(2414) const { headerNameLowerCasedRecord } = __nccwpck_require__(735) // Verifies that a given path is valid does not contain control chars \x00 to \x20 const invalidPathRegex = /[^\u0021-\u00ff]/ const kHandler = Symbol('handler') class Request { constructor (origin, { path, method, body, headers, query, idempotent, blocking, upgrade, headersTimeout, bodyTimeout, reset, throwOnError, expectContinue, servername }, handler) { if (typeof path !== 'string') { throw new InvalidArgumentError('path must be a string') } else if ( path[0] !== '/' && !(path.startsWith('http://') || path.startsWith('https://')) && method !== 'CONNECT' ) { throw new InvalidArgumentError('path must be an absolute URL or start with a slash') } else if (invalidPathRegex.test(path)) { throw new InvalidArgumentError('invalid request path') } if (typeof method !== 'string') { throw new InvalidArgumentError('method must be a string') } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) { throw new InvalidArgumentError('invalid request method') } if (upgrade && typeof upgrade !== 'string') { throw new InvalidArgumentError('upgrade must be a string') } if (upgrade && !isValidHeaderValue(upgrade)) { throw new InvalidArgumentError('invalid upgrade header') } if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('invalid headersTimeout') } if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('invalid bodyTimeout') } if (reset != null && typeof reset !== 'boolean') { throw new InvalidArgumentError('invalid reset') } if (expectContinue != null && typeof expectContinue !== 'boolean') { throw new InvalidArgumentError('invalid expectContinue') } this.headersTimeout = headersTimeout this.bodyTimeout = bodyTimeout this.throwOnError = throwOnError === true this.method = method this.abort = null if (body == null) { this.body = null } else if (isStream(body)) { this.body = body const rState = this.body._readableState if (!rState || !rState.autoDestroy) { this.endHandler = function autoDestroy () { destroy(this) } this.body.on('end', this.endHandler) } this.errorHandler = err => { if (this.abort) { this.abort(err) } else { this.error = err } } this.body.on('error', this.errorHandler) } else if (isBuffer(body)) { this.body = body.byteLength ? body : null } else if (ArrayBuffer.isView(body)) { this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null } else if (body instanceof ArrayBuffer) { this.body = body.byteLength ? Buffer.from(body) : null } else if (typeof body === 'string') { this.body = body.length ? Buffer.from(body) : null } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) { this.body = body } else { throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') } this.completed = false this.aborted = false this.upgrade = upgrade || null this.path = query ? buildURL(path, query) : path this.origin = origin this.idempotent = idempotent == null ? method === 'HEAD' || method === 'GET' : idempotent this.blocking = blocking == null ? false : blocking this.reset = reset == null ? null : reset this.host = null this.contentLength = null this.contentType = null this.headers = [] // Only for H2 this.expectContinue = expectContinue != null ? expectContinue : false if (Array.isArray(headers)) { if (headers.length % 2 !== 0) { throw new InvalidArgumentError('headers array must be even') } for (let i = 0; i < headers.length; i += 2) { processHeader(this, headers[i], headers[i + 1]) } } else if (headers && typeof headers === 'object') { if (headers[Symbol.iterator]) { for (const header of headers) { if (!Array.isArray(header) || header.length !== 2) { throw new InvalidArgumentError('headers must be in key-value pair format') } processHeader(this, header[0], header[1]) } } else { const keys = Object.keys(headers) for (let i = 0; i < keys.length; ++i) { processHeader(this, keys[i], headers[keys[i]]) } } } else if (headers != null) { throw new InvalidArgumentError('headers must be an object or an array') } validateHandler(handler, method, upgrade) this.servername = servername || getServerName(this.host) this[kHandler] = handler if (channels.create.hasSubscribers) { channels.create.publish({ request: this }) } } onBodySent (chunk) { if (this[kHandler].onBodySent) { try { return this[kHandler].onBodySent(chunk) } catch (err) { this.abort(err) } } } onRequestSent () { if (channels.bodySent.hasSubscribers) { channels.bodySent.publish({ request: this }) } if (this[kHandler].onRequestSent) { try { return this[kHandler].onRequestSent() } catch (err) { this.abort(err) } } } onConnect (abort) { assert(!this.aborted) assert(!this.completed) if (this.error) { abort(this.error) } else { this.abort = abort return this[kHandler].onConnect(abort) } } onResponseStarted () { return this[kHandler].onResponseStarted?.() } onHeaders (statusCode, headers, resume, statusText) { assert(!this.aborted) assert(!this.completed) if (channels.headers.hasSubscribers) { channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) } try { return this[kHandler].onHeaders(statusCode, headers, resume, statusText) } catch (err) { this.abort(err) } } onData (chunk) { assert(!this.aborted) assert(!this.completed) try { return this[kHandler].onData(chunk) } catch (err) { this.abort(err) return false } } onUpgrade (statusCode, headers, socket) { assert(!this.aborted) assert(!this.completed) return this[kHandler].onUpgrade(statusCode, headers, socket) } onComplete (trailers) { this.onFinally() assert(!this.aborted) this.completed = true if (channels.trailers.hasSubscribers) { channels.trailers.publish({ request: this, trailers }) } try { return this[kHandler].onComplete(trailers) } catch (err) { // TODO (fix): This might be a bad idea? this.onError(err) } } onError (error) { this.onFinally() if (channels.error.hasSubscribers) { channels.error.publish({ request: this, error }) } if (this.aborted) { return } this.aborted = true return this[kHandler].onError(error) } onFinally () { if (this.errorHandler) { this.body.off('error', this.errorHandler) this.errorHandler = null } if (this.endHandler) { this.body.off('end', this.endHandler) this.endHandler = null } } addHeader (key, value) { processHeader(this, key, value) return this } } function processHeader (request, key, val) { if (val && (typeof val === 'object' && !Array.isArray(val))) { throw new InvalidArgumentError(`invalid ${key} header`) } else if (val === undefined) { return } let headerName = headerNameLowerCasedRecord[key] if (headerName === undefined) { headerName = key.toLowerCase() if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) { throw new InvalidArgumentError('invalid header key') } } if (Array.isArray(val)) { const arr = [] for (let i = 0; i < val.length; i++) { if (typeof val[i] === 'string') { if (!isValidHeaderValue(val[i])) { throw new InvalidArgumentError(`invalid ${key} header`) } arr.push(val[i]) } else if (val[i] === null) { arr.push('') } else if (typeof val[i] === 'object') { throw new InvalidArgumentError(`invalid ${key} header`) } else { arr.push(`${val[i]}`) } } val = arr } else if (typeof val === 'string') { if (!isValidHeaderValue(val)) { throw new InvalidArgumentError(`invalid ${key} header`) } } else if (val === null) { val = '' } else { val = `${val}` } if (headerName === 'host') { if (request.host !== null) { throw new InvalidArgumentError('duplicate host header') } if (typeof val !== 'string') { throw new InvalidArgumentError('invalid host header') } // Consumed by Client request.host = val } else if (headerName === 'content-length') { if (request.contentLength !== null) { throw new InvalidArgumentError('duplicate content-length header') } request.contentLength = parseInt(val, 10) if (!Number.isFinite(request.contentLength)) { throw new InvalidArgumentError('invalid content-length header') } } else if (request.contentType === null && headerName === 'content-type') { request.contentType = val request.headers.push(key, val) } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') { throw new InvalidArgumentError(`invalid ${headerName} header`) } else if (headerName === 'connection') { const value = typeof val === 'string' ? val.toLowerCase() : null if (value !== 'close' && value !== 'keep-alive') { throw new InvalidArgumentError('invalid connection header') } if (value === 'close') { request.reset = true } } else if (headerName === 'expect') { throw new NotSupportedError('expect header not supported') } else { request.headers.push(key, val) } } module.exports = Request /***/ }), /***/ 6443: /***/ ((module) => { module.exports = { kClose: Symbol('close'), kDestroy: Symbol('destroy'), kDispatch: Symbol('dispatch'), kUrl: Symbol('url'), kWriting: Symbol('writing'), kResuming: Symbol('resuming'), kQueue: Symbol('queue'), kConnect: Symbol('connect'), kConnecting: Symbol('connecting'), kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), kKeepAliveTimeoutValue: Symbol('keep alive timeout'), kKeepAlive: Symbol('keep alive'), kHeadersTimeout: Symbol('headers timeout'), kBodyTimeout: Symbol('body timeout'), kServerName: Symbol('server name'), kLocalAddress: Symbol('local address'), kHost: Symbol('host'), kNoRef: Symbol('no ref'), kBodyUsed: Symbol('used'), kBody: Symbol('abstracted request body'), kRunning: Symbol('running'), kBlocking: Symbol('blocking'), kPending: Symbol('pending'), kSize: Symbol('size'), kBusy: Symbol('busy'), kQueued: Symbol('queued'), kFree: Symbol('free'), kConnected: Symbol('connected'), kClosed: Symbol('closed'), kNeedDrain: Symbol('need drain'), kReset: Symbol('reset'), kDestroyed: Symbol.for('nodejs.stream.destroyed'), kResume: Symbol('resume'), kOnError: Symbol('on error'), kMaxHeadersSize: Symbol('max headers size'), kRunningIdx: Symbol('running index'), kPendingIdx: Symbol('pending index'), kError: Symbol('error'), kClients: Symbol('clients'), kClient: Symbol('client'), kParser: Symbol('parser'), kOnDestroyed: Symbol('destroy callbacks'), kPipelining: Symbol('pipelining'), kSocket: Symbol('socket'), kHostHeader: Symbol('host header'), kConnector: Symbol('connector'), kStrictContentLength: Symbol('strict content length'), kMaxRedirections: Symbol('maxRedirections'), kMaxRequests: Symbol('maxRequestsPerClient'), kProxy: Symbol('proxy agent options'), kCounter: Symbol('socket request counter'), kInterceptors: Symbol('dispatch interceptors'), kMaxResponseSize: Symbol('max response size'), kHTTP2Session: Symbol('http2Session'), kHTTP2SessionState: Symbol('http2Session state'), kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), kConstruct: Symbol('constructable'), kListeners: Symbol('listeners'), kHTTPContext: Symbol('http context'), kMaxConcurrentStreams: Symbol('max concurrent streams'), kNoProxyAgent: Symbol('no proxy agent'), kHttpProxyAgent: Symbol('http proxy agent'), kHttpsProxyAgent: Symbol('https proxy agent') } /***/ }), /***/ 7752: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { wellknownHeaderNames, headerNameLowerCasedRecord } = __nccwpck_require__(735) class TstNode { /** @type {any} */ value = null /** @type {null | TstNode} */ left = null /** @type {null | TstNode} */ middle = null /** @type {null | TstNode} */ right = null /** @type {number} */ code /** * @param {string} key * @param {any} value * @param {number} index */ constructor (key, value, index) { if (index === undefined || index >= key.length) { throw new TypeError('Unreachable') } const code = this.code = key.charCodeAt(index) // check code is ascii string if (code > 0x7F) { throw new TypeError('key must be ascii string') } if (key.length !== ++index) { this.middle = new TstNode(key, value, index) } else { this.value = value } } /** * @param {string} key * @param {any} value */ add (key, value) { const length = key.length if (length === 0) { throw new TypeError('Unreachable') } let index = 0 let node = this while (true) { const code = key.charCodeAt(index) // check code is ascii string if (code > 0x7F) { throw new TypeError('key must be ascii string') } if (node.code === code) { if (length === ++index) { node.value = value break } else if (node.middle !== null) { node = node.middle } else { node.middle = new TstNode(key, value, index) break } } else if (node.code < code) { if (node.left !== null) { node = node.left } else { node.left = new TstNode(key, value, index) break } } else if (node.right !== null) { node = node.right } else { node.right = new TstNode(key, value, index) break } } } /** * @param {Uint8Array} key * @return {TstNode | null} */ search (key) { const keylength = key.length let index = 0 let node = this while (node !== null && index < keylength) { let code = key[index] // A-Z // First check if it is bigger than 0x5a. // Lowercase letters have higher char codes than uppercase ones. // Also we assume that headers will mostly contain lowercase characters. if (code <= 0x5a && code >= 0x41) { // Lowercase for uppercase. code |= 32 } while (node !== null) { if (code === node.code) { if (keylength === ++index) { // Returns Node since it is the last key. return node } node = node.middle break } node = node.code < code ? node.left : node.right } } return null } } class TernarySearchTree { /** @type {TstNode | null} */ node = null /** * @param {string} key * @param {any} value * */ insert (key, value) { if (this.node === null) { this.node = new TstNode(key, value, 0) } else { this.node.add(key, value) } } /** * @param {Uint8Array} key * @return {any} */ lookup (key) { return this.node?.search(key)?.value ?? null } } const tree = new TernarySearchTree() for (let i = 0; i < wellknownHeaderNames.length; ++i) { const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]] tree.insert(key, key) } module.exports = { TernarySearchTree, tree } /***/ }), /***/ 3440: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { kDestroyed, kBodyUsed, kListeners, kBody } = __nccwpck_require__(6443) const { IncomingMessage } = __nccwpck_require__(7067) const stream = __nccwpck_require__(7075) const net = __nccwpck_require__(7030) const { Blob } = __nccwpck_require__(4573) const nodeUtil = __nccwpck_require__(7975) const { stringify } = __nccwpck_require__(1792) const { EventEmitter: EE } = __nccwpck_require__(8474) const { InvalidArgumentError } = __nccwpck_require__(8707) const { headerNameLowerCasedRecord } = __nccwpck_require__(735) const { tree } = __nccwpck_require__(7752) const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } function wrapRequestBody (body) { if (isStream(body)) { // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp // so that it can be dispatched again? // TODO (fix): Do we need 100-expect support to provide a way to do this properly? if (bodyLength(body) === 0) { body .on('data', function () { assert(false) }) } if (typeof body.readableDidRead !== 'boolean') { body[kBodyUsed] = false EE.prototype.on.call(body, 'data', function () { this[kBodyUsed] = true }) } return body } else if (body && typeof body.pipeTo === 'function') { // TODO (fix): We can't access ReadableStream internal state // to determine whether or not it has been disturbed. This is just // a workaround. return new BodyAsyncIterable(body) } else if ( body && typeof body !== 'string' && !ArrayBuffer.isView(body) && isIterable(body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? return new BodyAsyncIterable(body) } else { return body } } function nop () {} function isStream (obj) { return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) function isBlobLike (object) { if (object === null) { return false } else if (object instanceof Blob) { return true } else if (typeof object !== 'object') { return false } else { const sTag = object[Symbol.toStringTag] return (sTag === 'Blob' || sTag === 'File') && ( ('stream' in object && typeof object.stream === 'function') || ('arrayBuffer' in object && typeof object.arrayBuffer === 'function') ) } } function buildURL (url, queryParams) { if (url.includes('?') || url.includes('#')) { throw new Error('Query params cannot be passed when url already contains "?" or "#".') } const stringified = stringify(queryParams) if (stringified) { url += '?' + stringified } return url } function isValidPort (port) { const value = parseInt(port, 10) return ( value === Number(port) && value >= 0 && value <= 65535 ) } function isHttpOrHttpsPrefixed (value) { return ( value != null && value[0] === 'h' && value[1] === 't' && value[2] === 't' && value[3] === 'p' && ( value[4] === ':' || ( value[4] === 's' && value[5] === ':' ) ) ) } function parseURL (url) { if (typeof url === 'string') { url = new URL(url) if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } if (!url || typeof url !== 'object') { throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') } if (!(url instanceof URL)) { if (url.port != null && url.port !== '' && isValidPort(url.port) === false) { throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') } if (url.path != null && typeof url.path !== 'string') { throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') } if (url.pathname != null && typeof url.pathname !== 'string') { throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') } if (url.hostname != null && typeof url.hostname !== 'string') { throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') } if (url.origin != null && typeof url.origin !== 'string') { throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } const port = url.port != null ? url.port : (url.protocol === 'https:' ? 443 : 80) let origin = url.origin != null ? url.origin : `${url.protocol || ''}//${url.hostname || ''}:${port}` let path = url.path != null ? url.path : `${url.pathname || ''}${url.search || ''}` if (origin[origin.length - 1] === '/') { origin = origin.slice(0, origin.length - 1) } if (path && path[0] !== '/') { path = `/${path}` } // new URL(path, origin) is unsafe when `path` contains an absolute URL // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: // If first parameter is a relative URL, second param is required, and will be used as the base URL. // If first parameter is an absolute URL, a given second param will be ignored. return new URL(`${origin}${path}`) } if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) { throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') } return url } function parseOrigin (url) { url = parseURL(url) if (url.pathname !== '/' || url.search || url.hash) { throw new InvalidArgumentError('invalid url') } return url } function getHostname (host) { if (host[0] === '[') { const idx = host.indexOf(']') assert(idx !== -1) return host.substring(1, idx) } const idx = host.indexOf(':') if (idx === -1) return host return host.substring(0, idx) } // IP addresses are not valid server names per RFC6066 // > Currently, the only server names supported are DNS hostnames function getServerName (host) { if (!host) { return null } assert(typeof host === 'string') const servername = getHostname(host) if (net.isIP(servername)) { return '' } return servername } function deepClone (obj) { return JSON.parse(JSON.stringify(obj)) } function isAsyncIterable (obj) { return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') } function isIterable (obj) { return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) } function bodyLength (body) { if (body == null) { return 0 } else if (isStream(body)) { const state = body._readableState return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null } else if (isBlobLike(body)) { return body.size != null ? body.size : null } else if (isBuffer(body)) { return body.byteLength } return null } function isDestroyed (body) { return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body))) } function destroy (stream, err) { if (stream == null || !isStream(stream) || isDestroyed(stream)) { return } if (typeof stream.destroy === 'function') { if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { // See: https://github.com/nodejs/node/pull/38505/files stream.socket = null } stream.destroy(err) } else if (err) { queueMicrotask(() => { stream.emit('error', err) }) } if (stream.destroyed !== true) { stream[kDestroyed] = true } } const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ function parseKeepAliveTimeout (val) { const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) return m ? parseInt(m[1], 10) * 1000 : null } /** * Retrieves a header name and returns its lowercase value. * @param {string | Buffer} value Header name * @returns {string} */ function headerNameToString (value) { return typeof value === 'string' ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString('latin1').toLowerCase() } /** * Receive the buffer as a string and return its lowercase value. * @param {Buffer} value Header name * @returns {string} */ function bufferToLowerCasedHeaderName (value) { return tree.lookup(value) ?? value.toString('latin1').toLowerCase() } /** * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers * @param {Record} [obj] * @returns {Record} */ function parseHeaders (headers, obj) { if (obj === undefined) obj = {} for (let i = 0; i < headers.length; i += 2) { const key = headerNameToString(headers[i]) let val = obj[key] if (val) { if (typeof val === 'string') { val = [val] obj[key] = val } val.push(headers[i + 1].toString('utf8')) } else { const headersValue = headers[i + 1] if (typeof headersValue === 'string') { obj[key] = headersValue } else { obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8') } } } // See https://github.com/nodejs/node/pull/46528 if ('content-length' in obj && 'content-disposition' in obj) { obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') } return obj } function parseRawHeaders (headers) { const len = headers.length const ret = new Array(len) let hasContentLength = false let contentDispositionIdx = -1 let key let val let kLen = 0 for (let n = 0; n < headers.length; n += 2) { key = headers[n] val = headers[n + 1] typeof key !== 'string' && (key = key.toString()) typeof val !== 'string' && (val = val.toString('utf8')) kLen = key.length if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) { hasContentLength = true } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { contentDispositionIdx = n + 1 } ret[n] = key ret[n + 1] = val } // See https://github.com/nodejs/node/pull/46528 if (hasContentLength && contentDispositionIdx !== -1) { ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') } return ret } function isBuffer (buffer) { // See, https://github.com/mcollina/undici/pull/319 return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) } function validateHandler (handler, method, upgrade) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } if (typeof handler.onConnect !== 'function') { throw new InvalidArgumentError('invalid onConnect method') } if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { throw new InvalidArgumentError('invalid onBodySent method') } if (upgrade || method === 'CONNECT') { if (typeof handler.onUpgrade !== 'function') { throw new InvalidArgumentError('invalid onUpgrade method') } } else { if (typeof handler.onHeaders !== 'function') { throw new InvalidArgumentError('invalid onHeaders method') } if (typeof handler.onData !== 'function') { throw new InvalidArgumentError('invalid onData method') } if (typeof handler.onComplete !== 'function') { throw new InvalidArgumentError('invalid onComplete method') } } } // A body is disturbed if it has been read from and it cannot // be re-used without losing state or data. function isDisturbed (body) { // TODO (fix): Why is body[kBodyUsed] needed? return !!(body && (stream.isDisturbed(body) || body[kBodyUsed])) } function isErrored (body) { return !!(body && stream.isErrored(body)) } function isReadable (body) { return !!(body && stream.isReadable(body)) } function getSocketInfo (socket) { return { localAddress: socket.localAddress, localPort: socket.localPort, remoteAddress: socket.remoteAddress, remotePort: socket.remotePort, remoteFamily: socket.remoteFamily, timeout: socket.timeout, bytesWritten: socket.bytesWritten, bytesRead: socket.bytesRead } } /** @type {globalThis['ReadableStream']} */ function ReadableStreamFrom (iterable) { // We cannot use ReadableStream.from here because it does not return a byte stream. let iterator return new ReadableStream( { async start () { iterator = iterable[Symbol.asyncIterator]() }, async pull (controller) { const { done, value } = await iterator.next() if (done) { queueMicrotask(() => { controller.close() controller.byobRequest?.respond(0) }) } else { const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) if (buf.byteLength) { controller.enqueue(new Uint8Array(buf)) } } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() }, type: 'bytes' } ) } // The chunk should be a FormData instance and contains // all the required methods. function isFormDataLike (object) { return ( object && typeof object === 'object' && typeof object.append === 'function' && typeof object.delete === 'function' && typeof object.get === 'function' && typeof object.getAll === 'function' && typeof object.has === 'function' && typeof object.set === 'function' && object[Symbol.toStringTag] === 'FormData' ) } function addAbortListener (signal, listener) { if ('addEventListener' in signal) { signal.addEventListener('abort', listener, { once: true }) return () => signal.removeEventListener('abort', listener) } signal.addListener('abort', listener) return () => signal.removeListener('abort', listener) } const hasToWellFormed = typeof String.prototype.toWellFormed === 'function' const hasIsWellFormed = typeof String.prototype.isWellFormed === 'function' /** * @param {string} val */ function toUSVString (val) { return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val) } /** * @param {string} val */ // TODO: move this to webidl function isUSVString (val) { return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}` } /** * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 * @param {number} c */ function isTokenCharCode (c) { switch (c) { case 0x22: case 0x28: case 0x29: case 0x2c: case 0x2f: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x5b: case 0x5c: case 0x5d: case 0x7b: case 0x7d: // DQUOTE and "(),/:;<=>?@[\]{}" return false default: // VCHAR %x21-7E return c >= 0x21 && c <= 0x7e } } /** * @param {string} characters */ function isValidHTTPToken (characters) { if (characters.length === 0) { return false } for (let i = 0; i < characters.length; ++i) { if (!isTokenCharCode(characters.charCodeAt(i))) { return false } } return true } // headerCharRegex have been lifted from // https://github.com/nodejs/node/blob/main/lib/_http_common.js /** * Matches if val contains an invalid field-vchar * field-value = *( field-content / obs-fold ) * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-vchar = VCHAR / obs-text */ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ /** * @param {string} characters */ function isValidHeaderValue (characters) { return !headerCharRegex.test(characters) } // Parsed accordingly to RFC 9110 // https://www.rfc-editor.org/rfc/rfc9110#field.content-range function parseRangeHeader (range) { if (range == null || range === '') return { start: 0, end: null, size: null } const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null return m ? { start: parseInt(m[1]), end: m[2] ? parseInt(m[2]) : null, size: m[3] ? parseInt(m[3]) : null } : null } function addListener (obj, name, listener) { const listeners = (obj[kListeners] ??= []) listeners.push([name, listener]) obj.on(name, listener) return obj } function removeAllListeners (obj) { for (const [name, listener] of obj[kListeners] ?? []) { obj.removeListener(name, listener) } obj[kListeners] = null } function errorRequest (client, request, err) { try { request.onError(err) assert(request.aborted) } catch (err) { client.emit('error', err) } } const kEnumerableProperty = Object.create(null) kEnumerableProperty.enumerable = true const normalizedMethodRecordsBase = { delete: 'DELETE', DELETE: 'DELETE', get: 'GET', GET: 'GET', head: 'HEAD', HEAD: 'HEAD', options: 'OPTIONS', OPTIONS: 'OPTIONS', post: 'POST', POST: 'POST', put: 'PUT', PUT: 'PUT' } const normalizedMethodRecords = { ...normalizedMethodRecordsBase, patch: 'patch', PATCH: 'PATCH' } // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. Object.setPrototypeOf(normalizedMethodRecordsBase, null) Object.setPrototypeOf(normalizedMethodRecords, null) module.exports = { kEnumerableProperty, nop, isDisturbed, isErrored, isReadable, toUSVString, isUSVString, isBlobLike, parseOrigin, parseURL, getServerName, isStream, isIterable, isAsyncIterable, isDestroyed, headerNameToString, bufferToLowerCasedHeaderName, addListener, removeAllListeners, errorRequest, parseRawHeaders, parseHeaders, parseKeepAliveTimeout, destroy, bodyLength, deepClone, ReadableStreamFrom, isBuffer, validateHandler, getSocketInfo, isFormDataLike, buildURL, addAbortListener, isValidHTTPToken, isValidHeaderValue, isTokenCharCode, parseRangeHeader, normalizedMethodRecordsBase, normalizedMethodRecords, isValidPort, isHttpOrHttpsPrefixed, nodeMajor, nodeMinor, safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'], wrapRequestBody } /***/ }), /***/ 7405: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { InvalidArgumentError } = __nccwpck_require__(8707) const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) const DispatcherBase = __nccwpck_require__(1841) const Pool = __nccwpck_require__(628) const Client = __nccwpck_require__(3701) const util = __nccwpck_require__(3440) const createRedirectInterceptor = __nccwpck_require__(5092) const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kMaxRedirections = Symbol('maxRedirections') const kOnDrain = Symbol('onDrain') const kFactory = Symbol('factory') const kOptions = Symbol('options') function defaultFactory (origin, opts) { return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts) } class Agent extends DispatcherBase { constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { throw new InvalidArgumentError('maxRedirections must be a positive number') } super(options) if (connect && typeof connect !== 'function') { connect = { ...connect } } this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent) ? options.interceptors.Agent : [createRedirectInterceptor({ maxRedirections })] this[kOptions] = { ...util.deepClone(options), connect } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kMaxRedirections] = maxRedirections this[kFactory] = factory this[kClients] = new Map() this[kOnDrain] = (origin, targets) => { this.emit('drain', origin, [this, ...targets]) } this[kOnConnect] = (origin, targets) => { this.emit('connect', origin, [this, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { this.emit('disconnect', origin, [this, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { this.emit('connectionError', origin, [this, ...targets], err) } } get [kRunning] () { let ret = 0 for (const client of this[kClients].values()) { ret += client[kRunning] } return ret } [kDispatch] (opts, handler) { let key if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { key = String(opts.origin) } else { throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') } let dispatcher = this[kClients].get(key) if (!dispatcher) { dispatcher = this[kFactory](opts.origin, this[kOptions]) .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) // This introduces a tiny memory leak, as dispatchers are never removed from the map. // TODO(mcollina): remove te timer when the client/pool do not have any more // active connections. this[kClients].set(key, dispatcher) } return dispatcher.dispatch(opts, handler) } async [kClose] () { const closePromises = [] for (const client of this[kClients].values()) { closePromises.push(client.close()) } this[kClients].clear() await Promise.all(closePromises) } async [kDestroy] (err) { const destroyPromises = [] for (const client of this[kClients].values()) { destroyPromises.push(client.destroy(err)) } this[kClients].clear() await Promise.all(destroyPromises) } } module.exports = Agent /***/ }), /***/ 837: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { BalancedPoolMissingUpstreamError, InvalidArgumentError } = __nccwpck_require__(8707) const { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } = __nccwpck_require__(2128) const Pool = __nccwpck_require__(628) const { kUrl, kInterceptors } = __nccwpck_require__(6443) const { parseOrigin } = __nccwpck_require__(3440) const kFactory = Symbol('factory') const kOptions = Symbol('options') const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') const kCurrentWeight = Symbol('kCurrentWeight') const kIndex = Symbol('kIndex') const kWeight = Symbol('kWeight') const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') const kErrorPenalty = Symbol('kErrorPenalty') /** * Calculate the greatest common divisor of two numbers by * using the Euclidean algorithm. * * @param {number} a * @param {number} b * @returns {number} */ function getGreatestCommonDivisor (a, b) { if (a === 0) return b while (b !== 0) { const t = b b = a % b a = t } return a } function defaultFactory (origin, opts) { return new Pool(origin, opts) } class BalancedPool extends PoolBase { constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { super() this[kOptions] = opts this[kIndex] = -1 this[kCurrentWeight] = 0 this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 this[kErrorPenalty] = this[kOptions].errorPenalty || 15 if (!Array.isArray(upstreams)) { upstreams = [upstreams] } if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) ? opts.interceptors.BalancedPool : [] this[kFactory] = factory for (const upstream of upstreams) { this.addUpstream(upstream) } this._updateBalancedPoolStats() } addUpstream (upstream) { const upstreamOrigin = parseOrigin(upstream).origin if (this[kClients].find((pool) => ( pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true ))) { return this } const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) this[kAddClient](pool) pool.on('connect', () => { pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) }) pool.on('connectionError', () => { pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) this._updateBalancedPoolStats() }) pool.on('disconnect', (...args) => { const err = args[2] if (err && err.code === 'UND_ERR_SOCKET') { // decrease the weight of the pool. pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) this._updateBalancedPoolStats() } }) for (const client of this[kClients]) { client[kWeight] = this[kMaxWeightPerServer] } this._updateBalancedPoolStats() return this } _updateBalancedPoolStats () { let result = 0 for (let i = 0; i < this[kClients].length; i++) { result = getGreatestCommonDivisor(this[kClients][i][kWeight], result) } this[kGreatestCommonDivisor] = result } removeUpstream (upstream) { const upstreamOrigin = parseOrigin(upstream).origin const pool = this[kClients].find((pool) => ( pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true )) if (pool) { this[kRemoveClient](pool) } return this } get upstreams () { return this[kClients] .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) .map((p) => p[kUrl].origin) } [kGetDispatcher] () { // We validate that pools is greater than 0, // otherwise we would have to wait until an upstream // is added, which might never happen. if (this[kClients].length === 0) { throw new BalancedPoolMissingUpstreamError() } const dispatcher = this[kClients].find(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) if (!dispatcher) { return } const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) if (allClientsBusy) { return } let counter = 0 let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) while (counter++ < this[kClients].length) { this[kIndex] = (this[kIndex] + 1) % this[kClients].length const pool = this[kClients][this[kIndex]] // find pool index with the largest weight if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { maxWeightIndex = this[kIndex] } // decrease the current weight every `this[kClients].length`. if (this[kIndex] === 0) { // Set the current weight to the next lower weight. this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] if (this[kCurrentWeight] <= 0) { this[kCurrentWeight] = this[kMaxWeightPerServer] } } if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { return pool } } this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] this[kIndex] = maxWeightIndex return this[kClients][maxWeightIndex] } } module.exports = BalancedPool /***/ }), /***/ 637: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* global WebAssembly */ const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(3440) const { channels } = __nccwpck_require__(2414) const timers = __nccwpck_require__(6603) const { RequestContentLengthMismatchError, ResponseContentLengthMismatchError, RequestAbortedError, HeadersTimeoutError, HeadersOverflowError, SocketError, InformationalError, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError } = __nccwpck_require__(8707) const { kUrl, kReset, kClient, kParser, kBlocking, kRunning, kPending, kSize, kWriting, kQueue, kNoRef, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kSocket, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kMaxRequests, kCounter, kMaxResponseSize, kOnError, kResume, kHTTPContext } = __nccwpck_require__(6443) const constants = __nccwpck_require__(2824) const EMPTY_BUF = Buffer.alloc(0) const FastBuffer = Buffer[Symbol.species] const addListener = util.addListener const removeAllListeners = util.removeAllListeners const kIdleSocketValidation = Symbol('kIdleSocketValidation') const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout') const kSocketUsed = Symbol('kSocketUsed') let extractBody async function lazyllhttp () { const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined let mod try { mod = await WebAssembly.compile(__nccwpck_require__(3434)) } catch (e) { /* istanbul ignore next */ // We could check if the error was caused by the simd option not // being enabled, but the occurring of this other error // * https://github.com/emscripten-core/emscripten/issues/11495 // got me to remove that check to avoid breaking Node 12. mod = await WebAssembly.compile(llhttpWasmData || __nccwpck_require__(3870)) } return await WebAssembly.instantiate(mod, { env: { /* eslint-disable camelcase */ wasm_on_url: (p, at, len) => { /* istanbul ignore next */ return 0 }, wasm_on_status: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_message_begin: (p) => { assert(currentParser.ptr === p) return currentParser.onMessageBegin() || 0 }, wasm_on_header_field: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_header_value: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { assert(currentParser.ptr === p) return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 }, wasm_on_body: (p, at, len) => { assert(currentParser.ptr === p) const start = at - currentBufferPtr + currentBufferRef.byteOffset return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 }, wasm_on_message_complete: (p) => { assert(currentParser.ptr === p) return currentParser.onMessageComplete() || 0 } /* eslint-enable camelcase */ } }) } let llhttpInstance = null let llhttpPromise = lazyllhttp() llhttpPromise.catch() let currentParser = null let currentBufferRef = null let currentBufferSize = 0 let currentBufferPtr = null const USE_NATIVE_TIMER = 0 const USE_FAST_TIMER = 1 // Use fast timers for headers and body to take eventual event loop // latency into account. const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER const TIMEOUT_BODY = 4 | USE_FAST_TIMER // Use native timers to ignore event loop latency for keep-alive // handling. const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER class Parser { constructor (client, socket, { exports }) { assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) this.llhttp = exports this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) this.client = client this.socket = socket this.timeout = null this.timeoutValue = null this.timeoutType = null this.statusCode = null this.statusText = '' this.upgrade = false this.headers = [] this.headersSize = 0 this.headersMaxSize = client[kMaxHeadersSize] this.shouldKeepAlive = false this.paused = false this.resume = this.resume.bind(this) this.bytesRead = 0 this.keepAlive = '' this.contentLength = '' this.connection = '' this.maxResponseSize = client[kMaxResponseSize] } setTimeout (delay, type) { // If the existing timer and the new timer are of different timer type // (fast or native) or have different delay, we need to clear the existing // timer and set a new one. if ( delay !== this.timeoutValue || (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER) ) { // If a timeout is already set, clear it with clearTimeout of the fast // timer implementation, as it can clear fast and native timers. if (this.timeout) { timers.clearTimeout(this.timeout) this.timeout = null } if (delay) { if (type & USE_FAST_TIMER) { this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this)) } else { this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this)) this.timeout.unref() } } this.timeoutValue = delay } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.timeoutType = type } resume () { if (this.socket.destroyed || !this.paused) { return } assert(this.ptr != null) assert(currentParser == null) this.llhttp.llhttp_resume(this.ptr) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } this.paused = false this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. this.readMore() } readMore () { while (!this.paused && this.ptr) { const chunk = this.socket.read() if (chunk === null) { break } this.execute(chunk) } } execute (data) { assert(this.ptr != null) assert(currentParser == null) assert(!this.paused) const { socket, llhttp } = this if (data.length > currentBufferSize) { if (currentBufferPtr) { llhttp.free(currentBufferPtr) } currentBufferSize = Math.ceil(data.length / 4096) * 4096 currentBufferPtr = llhttp.malloc(currentBufferSize) } new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) // Call `execute` on the wasm parser. // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, // and finally the length of bytes to parse. // The return value is an error code or `constants.ERROR.OK`. try { let ret try { currentBufferRef = data currentParser = this ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) /* eslint-disable-next-line no-useless-catch */ } catch (err) { /* istanbul ignore next: difficult to make a test case for */ throw err } finally { currentParser = null currentBufferRef = null } const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr if (ret !== constants.ERROR.OK) { const body = data.subarray(offset) if (ret === constants.ERROR.PAUSED_UPGRADE) { this.onUpgrade(body) } else if (ret === constants.ERROR.PAUSED) { this.paused = true socket.unshift(body) } else { throw this.createError(ret, body) } } } catch (err) { util.destroy(socket, err) } } finish () { assert(currentParser === null) assert(this.ptr != null) assert(!this.paused) const { llhttp } = this let ret try { currentParser = this ret = llhttp.llhttp_finish(this.ptr) } finally { currentParser = null } if (ret === constants.ERROR.OK) { return null } if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) { this.paused = true return null } return this.createError(ret, EMPTY_BUF) } createError (ret, data) { const { llhttp, contentLength, bytesRead } = this if (contentLength && bytesRead !== parseInt(contentLength, 10)) { return new ResponseContentLengthMismatchError() } const ptr = llhttp.llhttp_get_error_reason(this.ptr) let message = '' if (ptr) { const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) message = 'Response does not match the HTTP/1.1 protocol (' + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ')' } return new HTTPParserError(message, constants.ERROR[ret], data) } destroy () { assert(this.ptr != null) assert(currentParser == null) this.llhttp.llhttp_free(this.ptr) this.ptr = null this.timeout && timers.clearTimeout(this.timeout) this.timeout = null this.timeoutValue = null this.timeoutType = null this.paused = false } onStatus (buf) { this.statusText = buf.toString() } onMessageBegin () { const { socket, client } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } if (client[kRunning] === 0) { util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) return -1 } const request = client[kQueue][client[kRunningIdx]] if (!request) { return -1 } request.onResponseStarted() } onHeaderField (buf) { const len = this.headers.length if ((len & 1) === 0) { this.headers.push(buf) } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } this.trackHeader(buf.length) } onHeaderValue (buf) { let len = this.headers.length if ((len & 1) === 1) { this.headers.push(buf) len += 1 } else { this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) } const key = this.headers[len - 2] if (key.length === 10) { const headerName = util.bufferToLowerCasedHeaderName(key) if (headerName === 'keep-alive') { this.keepAlive += buf.toString() } else if (headerName === 'connection') { this.connection += buf.toString() } } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') { this.contentLength += buf.toString() } this.trackHeader(buf.length) } trackHeader (len) { this.headersSize += len if (this.headersSize >= this.headersMaxSize) { util.destroy(this.socket, new HeadersOverflowError()) } } onUpgrade (head) { const { upgrade, client, socket, headers, statusCode } = this assert(upgrade) assert(client[kSocket] === socket) assert(!socket.destroyed) assert(!this.paused) assert((headers.length & 1) === 0) const request = client[kQueue][client[kRunningIdx]] assert(request) assert(request.upgrade || request.method === 'CONNECT') this.statusCode = null this.statusText = '' this.shouldKeepAlive = null this.headers = [] this.headersSize = 0 socket.unshift(head) socket[kParser].destroy() socket[kParser] = null socket[kClient] = null socket[kError] = null removeAllListeners(socket) client[kSocket] = null client[kHTTPContext] = null // TODO (fix): This is hacky... client[kQueue][client[kRunningIdx]++] = null client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) try { request.onUpgrade(statusCode, headers, socket) } catch (err) { util.destroy(socket, err) } client[kResume]() } onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { const { client, socket, headers, statusText } = this /* istanbul ignore next: difficult to make a test case for */ if (socket.destroyed) { return -1 } if (client[kRunning] === 0) { util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) return -1 } const request = client[kQueue][client[kRunningIdx]] /* istanbul ignore next: difficult to make a test case for */ if (!request) { return -1 } assert(!this.upgrade) assert(this.statusCode < 200) if (statusCode === 100) { util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) return -1 } /* this can only happen if server is misbehaving */ if (upgrade && !request.upgrade) { util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) return -1 } assert(this.timeoutType === TIMEOUT_HEADERS) this.statusCode = statusCode this.shouldKeepAlive = ( shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD. (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') ) if (this.statusCode >= 200) { const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout] this.setTimeout(bodyTimeout, TIMEOUT_BODY) } else if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } if (request.method === 'CONNECT') { assert(client[kRunning] === 1) this.upgrade = true return 2 } if (upgrade) { assert(client[kRunning] === 1) this.upgrade = true return 2 } assert((this.headers.length & 1) === 0) this.headers = [] this.headersSize = 0 if (this.shouldKeepAlive && client[kPipelining]) { const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null if (keepAliveTimeout != null) { const timeout = Math.min( keepAliveTimeout - client[kKeepAliveTimeoutThreshold], client[kKeepAliveMaxTimeout] ) if (timeout <= 0) { socket[kReset] = true } else { client[kKeepAliveTimeoutValue] = timeout } } else { client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] } } else { // Stop more requests from being dispatched. socket[kReset] = true } const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false if (request.aborted) { return -1 } if (request.method === 'HEAD') { return 1 } if (statusCode < 200) { return 1 } if (socket[kBlocking]) { socket[kBlocking] = false client[kResume]() } return pause ? constants.ERROR.PAUSED : 0 } onBody (buf) { const { client, socket, statusCode, maxResponseSize } = this if (socket.destroyed) { return -1 } const request = client[kQueue][client[kRunningIdx]] assert(request) assert(this.timeoutType === TIMEOUT_BODY) if (this.timeout) { // istanbul ignore else: only for jest if (this.timeout.refresh) { this.timeout.refresh() } } assert(statusCode >= 200) if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { util.destroy(socket, new ResponseExceededMaxSizeError()) return -1 } this.bytesRead += buf.length if (request.onData(buf) === false) { return constants.ERROR.PAUSED } } onMessageComplete () { const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this if (socket.destroyed && (!statusCode || shouldKeepAlive)) { return -1 } if (upgrade) { return } assert(statusCode >= 100) assert((this.headers.length & 1) === 0) const request = client[kQueue][client[kRunningIdx]] assert(request) this.statusCode = null this.statusText = '' this.bytesRead = 0 this.contentLength = '' this.keepAlive = '' this.connection = '' this.headers = [] this.headersSize = 0 if (statusCode < 200) { return } /* istanbul ignore next: should be handled by llhttp? */ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { util.destroy(socket, new ResponseContentLengthMismatchError()) return -1 } request.onComplete(headers) client[kQueue][client[kRunningIdx]++] = null socket[kSocketUsed] = true if (socket[kWriting]) { assert(client[kRunning] === 0) // Response completed before request. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (!shouldKeepAlive) { util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (socket[kReset] && client[kRunning] === 0) { // Destroy socket once all requests have completed. // The request at the tail of the pipeline is the one // that requested reset and no further requests should // have been queued since then. util.destroy(socket, new InformationalError('reset')) return constants.ERROR.PAUSED } else if (client[kPipelining] == null || client[kPipelining] === 1) { // We must wait a full event loop cycle to reuse this socket to make sure // that non-spec compliant servers are not closing the connection even if they // said they won't. setImmediate(() => client[kResume]()) } else { client[kResume]() } } } function onParserTimeout (parser) { const { socket, timeoutType, client, paused } = parser.deref() /* istanbul ignore else */ if (timeoutType === TIMEOUT_HEADERS) { if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { assert(!paused, 'cannot be paused while waiting for headers') util.destroy(socket, new HeadersTimeoutError()) } } else if (timeoutType === TIMEOUT_BODY) { if (!paused) { util.destroy(socket, new BodyTimeoutError()) } } else if (timeoutType === TIMEOUT_KEEP_ALIVE) { assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) util.destroy(socket, new InformationalError('socket idle timeout')) } } async function connectH1 (client, socket) { client[kSocket] = socket if (!llhttpInstance) { llhttpInstance = await llhttpPromise llhttpPromise = null } socket[kNoRef] = false socket[kWriting] = false socket[kReset] = false socket[kBlocking] = false socket[kIdleSocketValidation] = 0 socket[kIdleSocketValidationTimeout] = null socket[kSocketUsed] = false socket[kParser] = new Parser(client, socket, llhttpInstance) addListener(socket, 'error', function (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') const parser = this[kParser] // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded // to the user. if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { const parserErr = parser.finish() if (parserErr) { this[kError] = parserErr this[kClient][kOnError](parserErr) } return } this[kError] = err this[kClient][kOnError](err) }) addListener(socket, 'readable', function () { const parser = this[kParser] if (parser) { parser.readMore() } }) addListener(socket, 'end', function () { const parser = this[kParser] if (parser.statusCode && !parser.shouldKeepAlive) { const parserErr = parser.finish() if (parserErr) { util.destroy(this, parserErr) } return } util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) }) addListener(socket, 'close', function () { const client = this[kClient] const parser = this[kParser] clearIdleSocketValidation(this) if (parser) { if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { this[kError] = parser.finish() || this[kError] } this[kParser].destroy() this[kParser] = null } const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) client[kSocket] = null client[kHTTPContext] = null // TODO (fix): This is hacky... if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { // Fail head of pipeline. const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null util.errorRequest(client, request, err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() }) let closed = false socket.on('close', () => { closed = true }) return { version: 'h1', defaultPipelining: 1, write (...args) { return writeH1(client, ...args) }, resume () { resumeH1(client) }, destroy (err, callback) { if (closed) { queueMicrotask(callback) } else { socket.destroy(err).on('close', callback) } }, get destroyed () { return socket.destroyed }, busy (request) { if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) { return true } if (request) { if (client[kRunning] > 0 && !request.idempotent) { // Non-idempotent request cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return true } if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { // Don't dispatch an upgrade until all preceding requests have completed. // A misbehaving server might upgrade the connection before all pipelined // request has completed. return true } if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) { // Request with stream or iterator body can error while other requests // are inflight and indirectly error those as well. // Ensure this doesn't happen by waiting for inflight // to complete before dispatching. // Request with stream or iterator body cannot be retried. // Ensure that no other requests are inflight and // could cause failure. return true } } return false } } } function clearIdleSocketValidation (socket) { if (socket[kIdleSocketValidationTimeout]) { clearTimeout(socket[kIdleSocketValidationTimeout]) socket[kIdleSocketValidationTimeout] = null } socket[kIdleSocketValidation] = 0 } function scheduleIdleSocketValidation (client, socket) { socket[kIdleSocketValidation] = 1 socket[kIdleSocketValidationTimeout] = setTimeout(() => { socket[kIdleSocketValidationTimeout] = null socket[kIdleSocketValidation] = 2 if (client[kSocket] === socket && !socket.destroyed) { client[kResume]() } }, 0) socket[kIdleSocketValidationTimeout].unref?.() } /** * @param {import('./client.js')} client */ function resumeH1 (client) { const socket = client[kSocket] if (socket && !socket.destroyed) { if (client[kSize] === 0) { if (!socket[kNoRef] && socket.unref) { socket.unref() socket[kNoRef] = true } } else if (socket[kNoRef] && socket.ref) { socket.ref() socket[kNoRef] = false } if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { if (socket[kIdleSocketValidation] === 0) { scheduleIdleSocketValidation(client, socket) socket[kParser].readMore() if (socket.destroyed) { return } return } if (socket[kIdleSocketValidation] === 1) { socket[kParser].readMore() if (socket.destroyed) { return } return } } if (client[kRunning] === 0) { socket[kParser].readMore() if (socket.destroyed) { return } } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) } } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { const request = client[kQueue][client[kRunningIdx]] const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout] socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) } } } } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } function writeH1 (client, request) { const { method, path, host, upgrade, blocking, reset } = request let { body, headers, contentLength } = request // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' || method === 'QUERY' || method === 'PROPFIND' || method === 'PROPPATCH' ) if (util.isFormDataLike(body)) { if (!extractBody) { extractBody = (__nccwpck_require__(4492).extractBody) } const [bodyStream, contentType] = extractBody(body) if (request.contentType == null) { headers.push('content-type', contentType) } body = bodyStream.stream contentLength = bodyStream.length } else if (util.isBlobLike(body) && request.contentType == null && body.type) { headers.push('content-type', body.type) } if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } const bodyLength = util.bodyLength(body) contentLength = bodyLength ?? contentLength if (contentLength === null) { contentLength = request.contentLength } if (contentLength === 0 && !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { util.errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } const socket = client[kSocket] clearIdleSocketValidation(socket) const abort = (err) => { if (request.aborted || request.completed) { return } util.errorRequest(client, request, err || new RequestAbortedError()) util.destroy(body) util.destroy(socket, new InformationalError('aborted')) } try { request.onConnect(abort) } catch (err) { util.errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'HEAD') { // https://github.com/mcollina/undici/issues/258 // Close after a HEAD request to interop with misbehaving servers // that may send a body in the response. socket[kReset] = true } if (upgrade || method === 'CONNECT') { // On CONNECT or upgrade, block pipeline from dispatching further // requests on this connection. socket[kReset] = true } if (reset != null) { socket[kReset] = reset } if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { socket[kReset] = true } if (blocking) { socket[kBlocking] = true } let header = `${method} ${path} HTTP/1.1\r\n` if (typeof host === 'string') { header += `host: ${host}\r\n` } else { header += client[kHostHeader] } if (upgrade) { header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` } else if (client[kPipelining] && !socket[kReset]) { header += 'connection: keep-alive\r\n' } else { header += 'connection: close\r\n' } if (Array.isArray(headers)) { for (let n = 0; n < headers.length; n += 2) { const key = headers[n + 0] const val = headers[n + 1] if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { header += `${key}: ${val[i]}\r\n` } } else { header += `${key}: ${val}\r\n` } } } if (channels.sendHeaders.hasSubscribers) { channels.sendHeaders.publish({ request, headers: header, socket }) } /* istanbul ignore else: assertion */ if (!body || bodyLength === 0) { writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload) } else if (util.isBuffer(body)) { writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload) } else { writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) } } else if (util.isStream(body)) { writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) } else if (util.isIterable(body)) { writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) } else { assert(false) } return true } function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') let finished = false const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) const onData = function (chunk) { if (finished) { return } try { if (!writer.write(chunk) && this.pause) { this.pause() } } catch (err) { util.destroy(this, err) } } const onDrain = function () { if (finished) { return } if (body.resume) { body.resume() } } const onClose = function () { // 'close' might be emitted *before* 'error' for // broken streams. Wait a tick to avoid this case. queueMicrotask(() => { // It's only safe to remove 'error' listener after // 'close'. body.removeListener('error', onFinished) }) if (!finished) { const err = new RequestAbortedError() queueMicrotask(() => onFinished(err)) } } const onFinished = function (err) { if (finished) { return } finished = true assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) socket .off('drain', onDrain) .off('error', onFinished) body .removeListener('data', onData) .removeListener('end', onFinished) .removeListener('close', onClose) if (!err) { try { writer.end() } catch (er) { err = er } } writer.destroy(err) if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { util.destroy(body, err) } else { util.destroy(body) } } body .on('data', onData) .on('end', onFinished) .on('error', onFinished) .on('close', onClose) if (body.resume) { body.resume() } socket .on('drain', onDrain) .on('error', onFinished) if (body.errorEmitted ?? body.errored) { setImmediate(() => onFinished(body.errored)) } else if (body.endEmitted ?? body.readableEnded) { setImmediate(() => onFinished(null)) } if (body.closeEmitted ?? body.closed) { setImmediate(onClose) } } function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) { try { if (!body) { if (contentLength === 0) { socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { assert(contentLength === null, 'no body must not have content length') socket.write(`${header}\r\n`, 'latin1') } } else if (util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(body) socket.uncork() request.onBodySent(body) if (!expectsPayload && request.reset !== false) { socket[kReset] = true } } request.onRequestSent() client[kResume]() } catch (err) { abort(err) } } async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength === body.size, 'blob body must have content length') try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) socket.cork() socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') socket.write(buffer) socket.uncork() request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload && request.reset !== false) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } } async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) socket .on('close', onDrain) .on('drain', onDrain) const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header }) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } if (!writer.write(chunk)) { await waitForDrain() } } writer.end() } catch (err) { writer.destroy(err) } finally { socket .off('close', onDrain) .off('drain', onDrain) } } class AsyncWriter { constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) { this.socket = socket this.request = request this.contentLength = contentLength this.client = client this.bytesWritten = 0 this.expectsPayload = expectsPayload this.header = header this.abort = abort socket[kWriting] = true } write (chunk) { const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return false } const len = Buffer.byteLength(chunk) if (!len) { return true } // We should defer writing chunks. if (contentLength !== null && bytesWritten + len > contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } process.emitWarning(new RequestContentLengthMismatchError()) } socket.cork() if (bytesWritten === 0) { if (!expectsPayload && request.reset !== false) { socket[kReset] = true } if (contentLength === null) { socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') } else { socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') } } if (contentLength === null) { socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') } this.bytesWritten += len const ret = socket.write(chunk) socket.uncork() request.onBodySent(chunk) if (!ret) { if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } } return ret } end () { const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this request.onRequestSent() socket[kWriting] = false if (socket[kError]) { throw socket[kError] } if (socket.destroyed) { return } if (bytesWritten === 0) { if (expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD send a Content-Length in a request message when // no Transfer-Encoding is sent and the request method defines a meaning // for an enclosed payload body. socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { socket.write(`${header}\r\n`, 'latin1') } } else if (contentLength === null) { socket.write('\r\n0\r\n\r\n', 'latin1') } if (contentLength !== null && bytesWritten !== contentLength) { if (client[kStrictContentLength]) { throw new RequestContentLengthMismatchError() } else { process.emitWarning(new RequestContentLengthMismatchError()) } } if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { // istanbul ignore else: only for jest if (socket[kParser].timeout.refresh) { socket[kParser].timeout.refresh() } } client[kResume]() } destroy (err) { const { socket, client, abort } = this socket[kWriting] = false if (err) { assert(client[kRunning] <= 1, 'pipeline should only contain this request') abort(err) } } } module.exports = connectH1 /***/ }), /***/ 8788: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { pipeline } = __nccwpck_require__(7075) const util = __nccwpck_require__(3440) const { RequestContentLengthMismatchError, RequestAbortedError, SocketError, InformationalError } = __nccwpck_require__(8707) const { kUrl, kReset, kClient, kRunning, kPending, kQueue, kPendingIdx, kRunningIdx, kError, kSocket, kStrictContentLength, kOnError, kMaxConcurrentStreams, kHTTP2Session, kResume, kSize, kHTTPContext } = __nccwpck_require__(6443) const kOpenStreams = Symbol('open streams') let extractBody // Experimental let h2ExperimentalWarned = false /** @type {import('http2')} */ let http2 try { http2 = __nccwpck_require__(2467) } catch { // @ts-ignore http2 = { constants: {} } } const { constants: { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS } } = http2 function parseH2Headers (headers) { const result = [] for (const [name, value] of Object.entries(headers)) { // h2 may concat the header value by array // e.g. Set-Cookie if (Array.isArray(value)) { for (const subvalue of value) { // we need to provide each header value of header name // because the headers handler expect name-value pair result.push(Buffer.from(name), Buffer.from(subvalue)) } } else { result.push(Buffer.from(name), Buffer.from(value)) } } return result } async function connectH2 (client, socket) { client[kSocket] = socket if (!h2ExperimentalWarned) { h2ExperimentalWarned = true process.emitWarning('H2 support is experimental, expect them to change at any time.', { code: 'UNDICI-H2' }) } const session = http2.connect(client[kUrl], { createConnection: () => socket, peerMaxConcurrentStreams: client[kMaxConcurrentStreams] }) session[kOpenStreams] = 0 session[kClient] = client session[kSocket] = socket util.addListener(session, 'error', onHttp2SessionError) util.addListener(session, 'frameError', onHttp2FrameError) util.addListener(session, 'end', onHttp2SessionEnd) util.addListener(session, 'goaway', onHTTP2GoAway) util.addListener(session, 'close', function () { const { [kClient]: client } = this const { [kSocket]: socket } = client const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket)) client[kHTTP2Session] = null if (client.destroyed) { assert(client[kPending] === 0) // Fail entire queue. const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } } }) session.unref() client[kHTTP2Session] = session socket[kHTTP2Session] = session util.addListener(socket, 'error', function (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kError] = err this[kClient][kOnError](err) }) util.addListener(socket, 'end', function () { util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) }) util.addListener(socket, 'close', function () { const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) client[kSocket] = null if (this[kHTTP2Session] != null) { this[kHTTP2Session].destroy(err) } client[kPendingIdx] = client[kRunningIdx] assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() }) let closed = false socket.on('close', () => { closed = true }) return { version: 'h2', defaultPipelining: Infinity, write (...args) { return writeH2(client, ...args) }, resume () { resumeH2(client) }, destroy (err, callback) { if (closed) { queueMicrotask(callback) } else { // Destroying the socket will trigger the session close socket.destroy(err).on('close', callback) } }, get destroyed () { return socket.destroyed }, busy () { return false } } } function resumeH2 (client) { const socket = client[kSocket] if (socket?.destroyed === false) { if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) { socket.unref() client[kHTTP2Session].unref() } else { socket.ref() client[kHTTP2Session].ref() } } } function onHttp2SessionError (err) { assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') this[kSocket][kError] = err this[kClient][kOnError](err) } function onHttp2FrameError (type, code, id) { if (id === 0) { const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) this[kSocket][kError] = err this[kClient][kOnError](err) } } function onHttp2SessionEnd () { const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket])) this.destroy(err) util.destroy(this[kSocket], err) } /** * This is the root cause of #3011 * We need to handle GOAWAY frames properly, and trigger the session close * along with the socket right away */ function onHTTP2GoAway (code) { // We cannot recover, so best to close the session and the socket const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${code}`, util.getSocketInfo(this)) const client = this[kClient] client[kSocket] = null client[kHTTPContext] = null if (this[kHTTP2Session] != null) { this[kHTTP2Session].destroy(err) this[kHTTP2Session] = null } util.destroy(this[kSocket], err) // Fail head of pipeline. if (client[kRunningIdx] < client[kQueue].length) { const request = client[kQueue][client[kRunningIdx]] client[kQueue][client[kRunningIdx]++] = null util.errorRequest(client, request, err) client[kPendingIdx] = client[kRunningIdx] } assert(client[kRunning] === 0) client.emit('disconnect', client[kUrl], [client], err) client[kResume]() } // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 function shouldSendContentLength (method) { return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' } function writeH2 (client, request) { const session = client[kHTTP2Session] const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request let { body } = request if (upgrade) { util.errorRequest(client, request, new Error('Upgrade not supported for H2')) return false } const headers = {} for (let n = 0; n < reqHeaders.length; n += 2) { const key = reqHeaders[n + 0] const val = reqHeaders[n + 1] if (Array.isArray(val)) { for (let i = 0; i < val.length; i++) { if (headers[key]) { headers[key] += `,${val[i]}` } else { headers[key] = val[i] } } } else { headers[key] = val } } /** @type {import('node:http2').ClientHttp2Stream} */ let stream const { hostname, port } = client[kUrl] headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}` headers[HTTP2_HEADER_METHOD] = method const abort = (err) => { if (request.aborted || request.completed) { return } err = err || new RequestAbortedError() util.errorRequest(client, request, err) if (stream != null) { util.destroy(stream, err) } // We do not destroy the socket as we can continue using the session // the stream get's destroyed and the session remains to create new streams util.destroy(body, err) client[kQueue][client[kRunningIdx]++] = null client[kResume]() } try { // We are already connected, streams are pending. // We can call on connect, and wait for abort request.onConnect(abort) } catch (err) { util.errorRequest(client, request, err) } if (request.aborted) { return false } if (method === 'CONNECT') { session.ref() // We are already connected, streams are pending, first request // will create a new stream. We trigger a request to create the stream and wait until // `ready` event is triggered // We disabled endStream to allow the user to write to the stream stream = session.request(headers, { endStream: false, signal }) if (stream.id && !stream.pending) { request.onUpgrade(null, null, stream) ++session[kOpenStreams] client[kQueue][client[kRunningIdx]++] = null } else { stream.once('ready', () => { request.onUpgrade(null, null, stream) ++session[kOpenStreams] client[kQueue][client[kRunningIdx]++] = null }) } stream.once('close', () => { session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) session.unref() }) return true } // https://tools.ietf.org/html/rfc7540#section-8.3 // :path and :scheme headers must be omitted when sending CONNECT headers[HTTP2_HEADER_PATH] = path headers[HTTP2_HEADER_SCHEME] = 'https' // https://tools.ietf.org/html/rfc7231#section-4.3.1 // https://tools.ietf.org/html/rfc7231#section-4.3.2 // https://tools.ietf.org/html/rfc7231#section-4.3.5 // Sending a payload body on a request that does not // expect it can cause undefined behavior on some // servers and corrupt connection state. Do not // re-use the connection for further requests. const expectsPayload = ( method === 'PUT' || method === 'POST' || method === 'PATCH' ) if (body && typeof body.read === 'function') { // Try to read EOF in order to get length. body.read(0) } let contentLength = util.bodyLength(body) if (util.isFormDataLike(body)) { extractBody ??= (__nccwpck_require__(4492).extractBody) const [bodyStream, contentType] = extractBody(body) headers['content-type'] = contentType body = bodyStream.stream contentLength = bodyStream.length } if (contentLength == null) { contentLength = request.contentLength } if (contentLength === 0 || !expectsPayload) { // https://tools.ietf.org/html/rfc7230#section-3.3.2 // A user agent SHOULD NOT send a Content-Length header field when // the request message does not contain a payload body and the method // semantics do not anticipate such a body. contentLength = null } // https://github.com/nodejs/undici/issues/2046 // A user agent may send a Content-Length header with 0 value, this should be allowed. if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { if (client[kStrictContentLength]) { util.errorRequest(client, request, new RequestContentLengthMismatchError()) return false } process.emitWarning(new RequestContentLengthMismatchError()) } if (contentLength != null) { assert(body, 'no body must not have content length') headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` } session.ref() const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null if (expectContinue) { headers[HTTP2_HEADER_EXPECT] = '100-continue' stream = session.request(headers, { endStream: shouldEndStream, signal }) stream.once('continue', writeBodyH2) } else { stream = session.request(headers, { endStream: shouldEndStream, signal }) writeBodyH2() } // Increment counter as we have new streams open ++session[kOpenStreams] stream.once('response', headers => { const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers request.onResponseStarted() // Due to the stream nature, it is possible we face a race condition // where the stream has been assigned, but the request has been aborted // the request remains in-flight and headers hasn't been received yet // for those scenarios, best effort is to destroy the stream immediately // as there's no value to keep it open. if (request.aborted) { const err = new RequestAbortedError() util.errorRequest(client, request, err) util.destroy(stream, err) return } if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) { stream.pause() } stream.on('data', (chunk) => { if (request.onData(chunk) === false) { stream.pause() } }) }) stream.once('end', () => { // When state is null, it means we haven't consumed body and the stream still do not have // a state. // Present specially when using pipeline or stream if (stream.state?.state == null || stream.state.state < 6) { request.onComplete([]) } if (session[kOpenStreams] === 0) { // Stream is closed or half-closed-remote (6), decrement counter and cleanup // It does not have sense to continue working with the stream as we do not // have yet RST_STREAM support on client-side session.unref() } abort(new InformationalError('HTTP/2: stream half-closed (remote)')) client[kQueue][client[kRunningIdx]++] = null client[kPendingIdx] = client[kRunningIdx] client[kResume]() }) stream.once('close', () => { session[kOpenStreams] -= 1 if (session[kOpenStreams] === 0) { session.unref() } }) stream.once('error', function (err) { abort(err) }) stream.once('frameError', (type, code) => { abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)) }) // stream.on('aborted', () => { // // TODO(HTTP/2): Support aborted // }) // stream.on('timeout', () => { // // TODO(HTTP/2): Support timeout // }) // stream.on('push', headers => { // // TODO(HTTP/2): Support push // }) // stream.on('trailers', headers => { // // TODO(HTTP/2): Support trailers // }) return true function writeBodyH2 () { /* istanbul ignore else: assertion */ if (!body || contentLength === 0) { writeBuffer( abort, stream, null, client, request, client[kSocket], contentLength, expectsPayload ) } else if (util.isBuffer(body)) { writeBuffer( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } else if (util.isBlobLike(body)) { if (typeof body.stream === 'function') { writeIterable( abort, stream, body.stream(), client, request, client[kSocket], contentLength, expectsPayload ) } else { writeBlob( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } } else if (util.isStream(body)) { writeStream( abort, client[kSocket], expectsPayload, stream, body, client, request, contentLength ) } else if (util.isIterable(body)) { writeIterable( abort, stream, body, client, request, client[kSocket], contentLength, expectsPayload ) } else { assert(false) } } } function writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { try { if (body != null && util.isBuffer(body)) { assert(contentLength === body.byteLength, 'buffer body must have content length') h2stream.cork() h2stream.write(body) h2stream.uncork() h2stream.end() request.onBodySent(body) } if (!expectsPayload) { socket[kReset] = true } request.onRequestSent() client[kResume]() } catch (error) { abort(error) } } function writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) { assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') // For HTTP/2, is enough to pipe the stream const pipe = pipeline( body, h2stream, (err) => { if (err) { util.destroy(pipe, err) abort(err) } else { util.removeAllListeners(pipe) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } } ) util.addListener(pipe, 'data', onPipeData) function onPipeData (chunk) { request.onBodySent(chunk) } } async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { assert(contentLength === body.size, 'blob body must have content length') try { if (contentLength != null && contentLength !== body.size) { throw new RequestContentLengthMismatchError() } const buffer = Buffer.from(await body.arrayBuffer()) h2stream.cork() h2stream.write(buffer) h2stream.uncork() h2stream.end() request.onBodySent(buffer) request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } } async function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) { assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') let callback = null function onDrain () { if (callback) { const cb = callback callback = null cb() } } const waitForDrain = () => new Promise((resolve, reject) => { assert(callback === null) if (socket[kError]) { reject(socket[kError]) } else { callback = resolve } }) h2stream .on('close', onDrain) .on('drain', onDrain) try { // It's up to the user to somehow abort the async iterable. for await (const chunk of body) { if (socket[kError]) { throw socket[kError] } const res = h2stream.write(chunk) request.onBodySent(chunk) if (!res) { await waitForDrain() } } h2stream.end() request.onRequestSent() if (!expectsPayload) { socket[kReset] = true } client[kResume]() } catch (err) { abort(err) } finally { h2stream .off('close', onDrain) .off('drain', onDrain) } } module.exports = connectH2 /***/ }), /***/ 3701: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // @ts-check const assert = __nccwpck_require__(4589) const net = __nccwpck_require__(7030) const http = __nccwpck_require__(7067) const util = __nccwpck_require__(3440) const { channels } = __nccwpck_require__(2414) const Request = __nccwpck_require__(4655) const DispatcherBase = __nccwpck_require__(1841) const { InvalidArgumentError, InformationalError, ClientDestroyedError } = __nccwpck_require__(8707) const buildConnector = __nccwpck_require__(9136) const { kUrl, kServerName, kClient, kBusy, kConnect, kResuming, kRunning, kPending, kSize, kQueue, kConnected, kConnecting, kNeedDrain, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kConnector, kMaxRedirections, kMaxRequests, kCounter, kClose, kDestroy, kDispatch, kInterceptors, kLocalAddress, kMaxResponseSize, kOnError, kHTTPContext, kMaxConcurrentStreams, kResume } = __nccwpck_require__(6443) const connectH1 = __nccwpck_require__(637) const connectH2 = __nccwpck_require__(8788) let deprecatedInterceptorWarned = false const kClosedResolve = Symbol('kClosedResolve') const noop = () => {} function getPipelining (client) { return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1 } /** * @type {import('../../types/client.js').default} */ class Client extends DispatcherBase { /** * * @param {string|URL} url * @param {import('../../types/client.js').Client.Options} options */ constructor (url, { interceptors, maxHeaderSize, headersTimeout, socketTimeout, requestTimeout, connectTimeout, bodyTimeout, idleTimeout, keepAlive, keepAliveTimeout, maxKeepAliveTimeout, keepAliveMaxTimeout, keepAliveTimeoutThreshold, socketPath, pipelining, tls, strictContentLength, maxCachedSessions, maxRedirections, connect, maxRequestsPerClient, localAddress, maxResponseSize, autoSelectFamily, autoSelectFamilyAttemptTimeout, // h2 maxConcurrentStreams, allowH2, webSocket } = {}) { super({ webSocket }) if (keepAlive !== undefined) { throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') } if (socketTimeout !== undefined) { throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') } if (requestTimeout !== undefined) { throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') } if (idleTimeout !== undefined) { throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') } if (maxKeepAliveTimeout !== undefined) { throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') } if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { throw new InvalidArgumentError('invalid maxHeaderSize') } if (socketPath != null && typeof socketPath !== 'string') { throw new InvalidArgumentError('invalid socketPath') } if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { throw new InvalidArgumentError('invalid connectTimeout') } if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveTimeout') } if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { throw new InvalidArgumentError('invalid keepAliveMaxTimeout') } if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') } if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') } if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') } if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { throw new InvalidArgumentError('localAddress must be valid string IP address') } if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { throw new InvalidArgumentError('maxResponseSize must be a positive number') } if ( autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) ) { throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') } // h2 if (allowH2 != null && typeof allowH2 !== 'boolean') { throw new InvalidArgumentError('allowH2 must be a valid boolean value') } if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0') } if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } if (interceptors?.Client && Array.isArray(interceptors.Client)) { this[kInterceptors] = interceptors.Client if (!deprecatedInterceptorWarned) { deprecatedInterceptorWarned = true process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', { code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED' }) } } else { this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })] } this[kUrl] = util.parseOrigin(url) this[kConnector] = connect this[kPipelining] = pipelining != null ? pipelining : 1 this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] this[kServerName] = null this[kLocalAddress] = localAddress != null ? localAddress : null this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength this[kMaxRedirections] = maxRedirections this[kMaxRequests] = maxRequestsPerClient this[kClosedResolve] = null this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server this[kHTTPContext] = null // kQueue is built up of 3 sections separated by // the kRunningIdx and kPendingIdx indices. // | complete | running | pending | // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length // kRunningIdx points to the first running element. // kPendingIdx points to the first pending element. // This implements a fast queue with an amortized // time of O(1). this[kQueue] = [] this[kRunningIdx] = 0 this[kPendingIdx] = 0 this[kResume] = (sync) => resume(this, sync) this[kOnError] = (err) => onError(this, err) } get pipelining () { return this[kPipelining] } set pipelining (value) { this[kPipelining] = value this[kResume](true) } get [kPending] () { return this[kQueue].length - this[kPendingIdx] } get [kRunning] () { return this[kPendingIdx] - this[kRunningIdx] } get [kSize] () { return this[kQueue].length - this[kRunningIdx] } get [kConnected] () { return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed } get [kBusy] () { return Boolean( this[kHTTPContext]?.busy(null) || (this[kSize] >= (getPipelining(this) || 1)) || this[kPending] > 0 ) } /* istanbul ignore: only used for test */ [kConnect] (cb) { connect(this) this.once('connect', cb) } [kDispatch] (opts, handler) { const origin = opts.origin || this[kUrl].origin const request = new Request(origin, opts, handler) this[kQueue].push(request) if (this[kResuming]) { // Do nothing. } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { // Wait a tick in case stream/iterator is ended in the same tick. this[kResuming] = 1 queueMicrotask(() => resume(this)) } else { this[kResume](true) } if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { this[kNeedDrain] = 2 } return this[kNeedDrain] < 2 } async [kClose] () { // TODO: for H2 we need to gracefully flush the remaining enqueued // request and close each stream. return new Promise((resolve) => { if (this[kSize]) { this[kClosedResolve] = resolve } else { resolve(null) } }) } async [kDestroy] (err) { return new Promise((resolve) => { const requests = this[kQueue].splice(this[kPendingIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(this, request, err) } const callback = () => { if (this[kClosedResolve]) { // TODO (fix): Should we error here with ClientDestroyedError? this[kClosedResolve]() this[kClosedResolve] = null } resolve(null) } if (this[kHTTPContext]) { this[kHTTPContext].destroy(err, callback) this[kHTTPContext] = null } else { queueMicrotask(callback) } this[kResume]() }) } } const createRedirectInterceptor = __nccwpck_require__(5092) function onError (client, err) { if ( client[kRunning] === 0 && err.code !== 'UND_ERR_INFO' && err.code !== 'UND_ERR_SOCKET' ) { // Error is not caused by running request and not a recoverable // socket error. assert(client[kPendingIdx] === client[kRunningIdx]) const requests = client[kQueue].splice(client[kRunningIdx]) for (let i = 0; i < requests.length; i++) { const request = requests[i] util.errorRequest(client, request, err) } assert(client[kSize] === 0) } } /** * @param {Client} client * @returns */ async function connect (client) { assert(!client[kConnecting]) assert(!client[kHTTPContext]) let { host, hostname, protocol, port } = client[kUrl] // Resolve ipv6 if (hostname[0] === '[') { const idx = hostname.indexOf(']') assert(idx !== -1) const ip = hostname.substring(1, idx) assert(net.isIP(ip)) hostname = ip } client[kConnecting] = true if (channels.beforeConnect.hasSubscribers) { channels.beforeConnect.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector] }) } try { const socket = await new Promise((resolve, reject) => { client[kConnector]({ host, hostname, protocol, port, servername: client[kServerName], localAddress: client[kLocalAddress] }, (err, socket) => { if (err) { reject(err) } else { resolve(socket) } }) }) if (client.destroyed) { util.destroy(socket.on('error', noop), new ClientDestroyedError()) return } assert(socket) try { client[kHTTPContext] = socket.alpnProtocol === 'h2' ? await connectH2(client, socket) : await connectH1(client, socket) } catch (err) { socket.destroy().on('error', noop) throw err } client[kConnecting] = false socket[kCounter] = 0 socket[kMaxRequests] = client[kMaxRequests] socket[kClient] = client socket[kError] = null if (channels.connected.hasSubscribers) { channels.connected.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], socket }) } client.emit('connect', client[kUrl], [client]) } catch (err) { if (client.destroyed) { return } client[kConnecting] = false if (channels.connectError.hasSubscribers) { channels.connectError.publish({ connectParams: { host, hostname, protocol, port, version: client[kHTTPContext]?.version, servername: client[kServerName], localAddress: client[kLocalAddress] }, connector: client[kConnector], error: err }) } if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { assert(client[kRunning] === 0) while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { const request = client[kQueue][client[kPendingIdx]++] util.errorRequest(client, request, err) } } else { onError(client, err) } client.emit('connectionError', client[kUrl], [client], err) } client[kResume]() } function emitDrain (client) { client[kNeedDrain] = 0 client.emit('drain', client[kUrl], [client]) } function resume (client, sync) { if (client[kResuming] === 2) { return } client[kResuming] = 2 _resume(client, sync) client[kResuming] = 0 if (client[kRunningIdx] > 256) { client[kQueue].splice(0, client[kRunningIdx]) client[kPendingIdx] -= client[kRunningIdx] client[kRunningIdx] = 0 } } function _resume (client, sync) { while (true) { if (client.destroyed) { assert(client[kPending] === 0) return } if (client[kClosedResolve] && !client[kSize]) { client[kClosedResolve]() client[kClosedResolve] = null return } if (client[kHTTPContext]) { client[kHTTPContext].resume() } if (client[kBusy]) { client[kNeedDrain] = 2 } else if (client[kNeedDrain] === 2) { if (sync) { client[kNeedDrain] = 1 queueMicrotask(() => emitDrain(client)) } else { emitDrain(client) } continue } if (client[kPending] === 0) { return } if (client[kRunning] >= (getPipelining(client) || 1)) { return } const request = client[kQueue][client[kPendingIdx]] if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { if (client[kRunning] > 0) { return } client[kServerName] = request.servername client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => { client[kHTTPContext] = null resume(client) }) } if (client[kConnecting]) { return } if (!client[kHTTPContext]) { connect(client) return } if (client[kHTTPContext].destroyed) { return } if (client[kHTTPContext].busy(request)) { return } if (!request.aborted && client[kHTTPContext].write(request)) { client[kPendingIdx]++ } else { client[kQueue].splice(client[kPendingIdx], 1) } } } module.exports = Client /***/ }), /***/ 1841: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Dispatcher = __nccwpck_require__(883) const { ClientDestroyedError, ClientClosedError, InvalidArgumentError } = __nccwpck_require__(8707) const { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = __nccwpck_require__(6443) const kOnDestroyed = Symbol('onDestroyed') const kOnClosed = Symbol('onClosed') const kInterceptedDispatch = Symbol('Intercepted Dispatch') const kWebSocketOptions = Symbol('webSocketOptions') class DispatcherBase extends Dispatcher { constructor (opts) { super() this[kDestroyed] = false this[kOnDestroyed] = null this[kClosed] = false this[kOnClosed] = [] this[kWebSocketOptions] = opts?.webSocket ?? {} } get webSocketOptions () { return { maxFragments: this[kWebSocketOptions].maxFragments ?? 131072, maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024 } } get destroyed () { return this[kDestroyed] } get closed () { return this[kClosed] } get interceptors () { return this[kInterceptors] } set interceptors (newInterceptors) { if (newInterceptors) { for (let i = newInterceptors.length - 1; i >= 0; i--) { const interceptor = this[kInterceptors][i] if (typeof interceptor !== 'function') { throw new InvalidArgumentError('interceptor must be an function') } } } this[kInterceptors] = newInterceptors } close (callback) { if (callback === undefined) { return new Promise((resolve, reject) => { this.close((err, data) => { return err ? reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { queueMicrotask(() => callback(new ClientDestroyedError(), null)) return } if (this[kClosed]) { if (this[kOnClosed]) { this[kOnClosed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } this[kClosed] = true this[kOnClosed].push(callback) const onClosed = () => { const callbacks = this[kOnClosed] this[kOnClosed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kClose]() .then(() => this.destroy()) .then(() => { queueMicrotask(onClosed) }) } destroy (err, callback) { if (typeof err === 'function') { callback = err err = null } if (callback === undefined) { return new Promise((resolve, reject) => { this.destroy(err, (err, data) => { return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) }) }) } if (typeof callback !== 'function') { throw new InvalidArgumentError('invalid callback') } if (this[kDestroyed]) { if (this[kOnDestroyed]) { this[kOnDestroyed].push(callback) } else { queueMicrotask(() => callback(null, null)) } return } if (!err) { err = new ClientDestroyedError() } this[kDestroyed] = true this[kOnDestroyed] = this[kOnDestroyed] || [] this[kOnDestroyed].push(callback) const onDestroyed = () => { const callbacks = this[kOnDestroyed] this[kOnDestroyed] = null for (let i = 0; i < callbacks.length; i++) { callbacks[i](null, null) } } // Should not error. this[kDestroy](err).then(() => { queueMicrotask(onDestroyed) }) } [kInterceptedDispatch] (opts, handler) { if (!this[kInterceptors] || this[kInterceptors].length === 0) { this[kInterceptedDispatch] = this[kDispatch] return this[kDispatch](opts, handler) } let dispatch = this[kDispatch].bind(this) for (let i = this[kInterceptors].length - 1; i >= 0; i--) { dispatch = this[kInterceptors][i](dispatch) } this[kInterceptedDispatch] = dispatch return dispatch(opts, handler) } dispatch (opts, handler) { if (!handler || typeof handler !== 'object') { throw new InvalidArgumentError('handler must be an object') } try { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object.') } if (this[kDestroyed] || this[kOnDestroyed]) { throw new ClientDestroyedError() } if (this[kClosed]) { throw new ClientClosedError() } return this[kInterceptedDispatch](opts, handler) } catch (err) { if (typeof handler.onError !== 'function') { throw new InvalidArgumentError('invalid onError method') } handler.onError(err) return false } } } module.exports = DispatcherBase /***/ }), /***/ 883: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const EventEmitter = __nccwpck_require__(8474) class Dispatcher extends EventEmitter { dispatch () { throw new Error('not implemented') } close () { throw new Error('not implemented') } destroy () { throw new Error('not implemented') } compose (...args) { // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ... const interceptors = Array.isArray(args[0]) ? args[0] : args let dispatch = this.dispatch.bind(this) for (const interceptor of interceptors) { if (interceptor == null) { continue } if (typeof interceptor !== 'function') { throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) } dispatch = interceptor(dispatch) if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { throw new TypeError('invalid interceptor') } } return new ComposedDispatcher(this, dispatch) } } class ComposedDispatcher extends Dispatcher { #dispatcher = null #dispatch = null constructor (dispatcher, dispatch) { super() this.#dispatcher = dispatcher this.#dispatch = dispatch } dispatch (...args) { this.#dispatch(...args) } close (...args) { return this.#dispatcher.close(...args) } destroy (...args) { return this.#dispatcher.destroy(...args) } } module.exports = Dispatcher /***/ }), /***/ 3137: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const DispatcherBase = __nccwpck_require__(1841) const { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = __nccwpck_require__(6443) const ProxyAgent = __nccwpck_require__(6672) const Agent = __nccwpck_require__(7405) const DEFAULT_PORTS = { 'http:': 80, 'https:': 443 } let experimentalWarned = false class EnvHttpProxyAgent extends DispatcherBase { #noProxyValue = null #noProxyEntries = null #opts = null constructor (opts = {}) { super() this.#opts = opts if (!experimentalWarned) { experimentalWarned = true process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', { code: 'UNDICI-EHPA' }) } const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts this[kNoProxyAgent] = new Agent(agentOpts) const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY if (HTTP_PROXY) { this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY }) } else { this[kHttpProxyAgent] = this[kNoProxyAgent] } const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY if (HTTPS_PROXY) { this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY }) } else { this[kHttpsProxyAgent] = this[kHttpProxyAgent] } this.#parseNoProxy() } [kDispatch] (opts, handler) { const url = new URL(opts.origin) const agent = this.#getProxyAgentForUrl(url) return agent.dispatch(opts, handler) } async [kClose] () { await this[kNoProxyAgent].close() if (!this[kHttpProxyAgent][kClosed]) { await this[kHttpProxyAgent].close() } if (!this[kHttpsProxyAgent][kClosed]) { await this[kHttpsProxyAgent].close() } } async [kDestroy] (err) { await this[kNoProxyAgent].destroy(err) if (!this[kHttpProxyAgent][kDestroyed]) { await this[kHttpProxyAgent].destroy(err) } if (!this[kHttpsProxyAgent][kDestroyed]) { await this[kHttpsProxyAgent].destroy(err) } } #getProxyAgentForUrl (url) { let { protocol, host: hostname, port } = url // Stripping ports in this way instead of using parsedUrl.hostname to make // sure that the brackets around IPv6 addresses are kept. hostname = hostname.replace(/:\d*$/, '').toLowerCase() port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0 if (!this.#shouldProxy(hostname, port)) { return this[kNoProxyAgent] } if (protocol === 'https:') { return this[kHttpsProxyAgent] } return this[kHttpProxyAgent] } #shouldProxy (hostname, port) { if (this.#noProxyChanged) { this.#parseNoProxy() } if (this.#noProxyEntries.length === 0) { return true // Always proxy if NO_PROXY is not set or empty. } if (this.#noProxyValue === '*') { return false // Never proxy if wildcard is set. } for (let i = 0; i < this.#noProxyEntries.length; i++) { const entry = this.#noProxyEntries[i] if (entry.port && entry.port !== port) { continue // Skip if ports don't match. } if (!/^[.*]/.test(entry.hostname)) { // No wildcards, so don't proxy only if there is not an exact match. if (hostname === entry.hostname) { return false } } else { // Don't proxy if the hostname ends with the no_proxy host. if (hostname.endsWith(entry.hostname.replace(/^\*/, ''))) { return false } } } return true } #parseNoProxy () { const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv const noProxySplit = noProxyValue.split(/[,\s]/) const noProxyEntries = [] for (let i = 0; i < noProxySplit.length; i++) { const entry = noProxySplit[i] if (!entry) { continue } const parsed = entry.match(/^(.+):(\d+)$/) noProxyEntries.push({ hostname: (parsed ? parsed[1] : entry).toLowerCase(), port: parsed ? Number.parseInt(parsed[2], 10) : 0 }) } this.#noProxyValue = noProxyValue this.#noProxyEntries = noProxyEntries } get #noProxyChanged () { if (this.#opts.noProxy !== undefined) { return false } return this.#noProxyValue !== this.#noProxyEnv } get #noProxyEnv () { return process.env.no_proxy ?? process.env.NO_PROXY ?? '' } } module.exports = EnvHttpProxyAgent /***/ }), /***/ 4660: /***/ ((module) => { /* eslint-disable */ // Extracted from node/lib/internal/fixed_queue.js // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. const kSize = 2048; const kMask = kSize - 1; // The FixedQueue is implemented as a singly-linked list of fixed-size // circular buffers. It looks something like this: // // head tail // | | // v v // +-----------+ <-----\ +-----------+ <------\ +-----------+ // | [null] | \----- | next | \------- | next | // +-----------+ +-----------+ +-----------+ // | item | <-- bottom | item | <-- bottom | [empty] | // | item | | item | | [empty] | // | item | | item | | [empty] | // | item | | item | | [empty] | // | item | | item | bottom --> | item | // | item | | item | | item | // | ... | | ... | | ... | // | item | | item | | item | // | item | | item | | item | // | [empty] | <-- top | item | | item | // | [empty] | | item | | item | // | [empty] | | [empty] | <-- top top --> | [empty] | // +-----------+ +-----------+ +-----------+ // // Or, if there is only one circular buffer, it looks something // like either of these: // // head tail head tail // | | | | // v v v v // +-----------+ +-----------+ // | [null] | | [null] | // +-----------+ +-----------+ // | [empty] | | item | // | [empty] | | item | // | item | <-- bottom top --> | [empty] | // | item | | [empty] | // | [empty] | <-- top bottom --> | item | // | [empty] | | item | // +-----------+ +-----------+ // // Adding a value means moving `top` forward by one, removing means // moving `bottom` forward by one. After reaching the end, the queue // wraps around. // // When `top === bottom` the current queue is empty and when // `top + 1 === bottom` it's full. This wastes a single space of storage // but allows much quicker checks. class FixedCircularBuffer { constructor() { this.bottom = 0; this.top = 0; this.list = new Array(kSize); this.next = null; } isEmpty() { return this.top === this.bottom; } isFull() { return ((this.top + 1) & kMask) === this.bottom; } push(data) { this.list[this.top] = data; this.top = (this.top + 1) & kMask; } shift() { const nextItem = this.list[this.bottom]; if (nextItem === undefined) return null; this.list[this.bottom] = undefined; this.bottom = (this.bottom + 1) & kMask; return nextItem; } } module.exports = class FixedQueue { constructor() { this.head = this.tail = new FixedCircularBuffer(); } isEmpty() { return this.head.isEmpty(); } push(data) { if (this.head.isFull()) { // Head is full: Creates a new queue, sets the old queue's `.next` to it, // and sets it as the new main queue. this.head = this.head.next = new FixedCircularBuffer(); } this.head.push(data); } shift() { const tail = this.tail; const next = tail.shift(); if (tail.isEmpty() && tail.next !== null) { // If there is another queue, it forms the new tail. this.tail = tail.next; } return next; } }; /***/ }), /***/ 2128: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const DispatcherBase = __nccwpck_require__(1841) const FixedQueue = __nccwpck_require__(4660) const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443) const PoolStats = __nccwpck_require__(3246) const kClients = Symbol('clients') const kNeedDrain = Symbol('needDrain') const kQueue = Symbol('queue') const kClosedResolve = Symbol('closed resolve') const kOnDrain = Symbol('onDrain') const kOnConnect = Symbol('onConnect') const kOnDisconnect = Symbol('onDisconnect') const kOnConnectionError = Symbol('onConnectionError') const kGetDispatcher = Symbol('get dispatcher') const kAddClient = Symbol('add client') const kRemoveClient = Symbol('remove client') const kStats = Symbol('stats') class PoolBase extends DispatcherBase { constructor (opts) { super(opts) this[kQueue] = new FixedQueue() this[kClients] = [] this[kQueued] = 0 const pool = this this[kOnDrain] = function onDrain (origin, targets) { const queue = pool[kQueue] let needDrain = false while (!needDrain) { const item = queue.shift() if (!item) { break } pool[kQueued]-- needDrain = !this.dispatch(item.opts, item.handler) } this[kNeedDrain] = needDrain if (!this[kNeedDrain] && pool[kNeedDrain]) { pool[kNeedDrain] = false pool.emit('drain', origin, [pool, ...targets]) } if (pool[kClosedResolve] && queue.isEmpty()) { Promise .all(pool[kClients].map(c => c.close())) .then(pool[kClosedResolve]) } } this[kOnConnect] = (origin, targets) => { pool.emit('connect', origin, [pool, ...targets]) } this[kOnDisconnect] = (origin, targets, err) => { pool.emit('disconnect', origin, [pool, ...targets], err) } this[kOnConnectionError] = (origin, targets, err) => { pool.emit('connectionError', origin, [pool, ...targets], err) } this[kStats] = new PoolStats(this) } get [kBusy] () { return this[kNeedDrain] } get [kConnected] () { return this[kClients].filter(client => client[kConnected]).length } get [kFree] () { return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length } get [kPending] () { let ret = this[kQueued] for (const { [kPending]: pending } of this[kClients]) { ret += pending } return ret } get [kRunning] () { let ret = 0 for (const { [kRunning]: running } of this[kClients]) { ret += running } return ret } get [kSize] () { let ret = this[kQueued] for (const { [kSize]: size } of this[kClients]) { ret += size } return ret } get stats () { return this[kStats] } async [kClose] () { if (this[kQueue].isEmpty()) { await Promise.all(this[kClients].map(c => c.close())) } else { await new Promise((resolve) => { this[kClosedResolve] = resolve }) } } async [kDestroy] (err) { while (true) { const item = this[kQueue].shift() if (!item) { break } item.handler.onError(err) } await Promise.all(this[kClients].map(c => c.destroy(err))) } [kDispatch] (opts, handler) { const dispatcher = this[kGetDispatcher]() if (!dispatcher) { this[kNeedDrain] = true this[kQueue].push({ opts, handler }) this[kQueued]++ } else if (!dispatcher.dispatch(opts, handler)) { dispatcher[kNeedDrain] = true this[kNeedDrain] = !this[kGetDispatcher]() } return !this[kNeedDrain] } [kAddClient] (client) { client .on('drain', this[kOnDrain]) .on('connect', this[kOnConnect]) .on('disconnect', this[kOnDisconnect]) .on('connectionError', this[kOnConnectionError]) this[kClients].push(client) if (this[kNeedDrain]) { queueMicrotask(() => { if (this[kNeedDrain]) { this[kOnDrain](client[kUrl], [this, client]) } }) } return this } [kRemoveClient] (client) { client.close(() => { const idx = this[kClients].indexOf(client) if (idx !== -1) { this[kClients].splice(idx, 1) } }) this[kNeedDrain] = this[kClients].some(dispatcher => ( !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true )) } } module.exports = { PoolBase, kClients, kNeedDrain, kAddClient, kRemoveClient, kGetDispatcher } /***/ }), /***/ 3246: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443) const kPool = Symbol('pool') class PoolStats { constructor (pool) { this[kPool] = pool } get connected () { return this[kPool][kConnected] } get free () { return this[kPool][kFree] } get pending () { return this[kPool][kPending] } get queued () { return this[kPool][kQueued] } get running () { return this[kPool][kRunning] } get size () { return this[kPool][kSize] } } module.exports = PoolStats /***/ }), /***/ 628: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { PoolBase, kClients, kNeedDrain, kAddClient, kGetDispatcher } = __nccwpck_require__(2128) const Client = __nccwpck_require__(3701) const { InvalidArgumentError } = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) const { kUrl, kInterceptors } = __nccwpck_require__(6443) const buildConnector = __nccwpck_require__(9136) const kOptions = Symbol('options') const kConnections = Symbol('connections') const kFactory = Symbol('factory') function defaultFactory (origin, opts) { return new Client(origin, opts) } class Pool extends PoolBase { constructor (origin, { connections, factory = defaultFactory, connect, connectTimeout, tls, maxCachedSessions, socketPath, autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, ...options } = {}) { if (connections != null && (!Number.isFinite(connections) || connections < 0)) { throw new InvalidArgumentError('invalid connections') } if (typeof factory !== 'function') { throw new InvalidArgumentError('factory must be a function.') } if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { throw new InvalidArgumentError('connect must be a function or an object') } if (typeof connect !== 'function') { connect = buildConnector({ ...tls, maxCachedSessions, allowH2, socketPath, timeout: connectTimeout, ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), ...connect }) } super(options) this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool) ? options.interceptors.Pool : [] this[kConnections] = connections || null this[kUrl] = util.parseOrigin(origin) this[kOptions] = { ...util.deepClone(options), connect, allowH2 } this[kOptions].interceptors = options.interceptors ? { ...options.interceptors } : undefined this[kFactory] = factory this.on('connectionError', (origin, targets, error) => { // If a connection error occurs, we remove the client from the pool, // and emit a connectionError event. They will not be re-used. // Fixes https://github.com/nodejs/undici/issues/3895 for (const target of targets) { // Do not use kRemoveClient here, as it will close the client, // but the client cannot be closed in this state. const idx = this[kClients].indexOf(target) if (idx !== -1) { this[kClients].splice(idx, 1) } } }) } [kGetDispatcher] () { for (const client of this[kClients]) { if (!client[kNeedDrain]) { return client } } if (!this[kConnections] || this[kClients].length < this[kConnections]) { const dispatcher = this[kFactory](this[kUrl], this[kOptions]) this[kAddClient](dispatcher) return dispatcher } } } module.exports = Pool /***/ }), /***/ 6672: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) const { URL } = __nccwpck_require__(3136) const Agent = __nccwpck_require__(7405) const Pool = __nccwpck_require__(628) const DispatcherBase = __nccwpck_require__(1841) const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = __nccwpck_require__(8707) const buildConnector = __nccwpck_require__(9136) const Client = __nccwpck_require__(3701) const kAgent = Symbol('proxy agent') const kClient = Symbol('proxy client') const kProxyHeaders = Symbol('proxy headers') const kRequestTls = Symbol('request tls settings') const kProxyTls = Symbol('proxy tls settings') const kConnectEndpoint = Symbol('connect endpoint function') const kTunnelProxy = Symbol('tunnel proxy') function defaultProtocolPort (protocol) { return protocol === 'https:' ? 443 : 80 } function defaultFactory (origin, opts) { return new Pool(origin, opts) } const noop = () => {} function defaultAgentFactory (origin, opts) { if (opts.connections === 1) { return new Client(origin, opts) } return new Pool(origin, opts) } class Http1ProxyWrapper extends DispatcherBase { #client constructor (proxyUrl, { headers = {}, connect, factory }) { super() if (!proxyUrl) { throw new InvalidArgumentError('Proxy URL is mandatory') } this[kProxyHeaders] = headers if (factory) { this.#client = factory(proxyUrl, { connect }) } else { this.#client = new Client(proxyUrl, { connect }) } } [kDispatch] (opts, handler) { const onHeaders = handler.onHeaders handler.onHeaders = function (statusCode, data, resume) { if (statusCode === 407) { if (typeof handler.onError === 'function') { handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)')) } return } if (onHeaders) onHeaders.call(this, statusCode, data, resume) } // Rewrite request as an HTTP1 Proxy request, without tunneling. const { origin, path = '/', headers = {} } = opts opts.path = origin + path if (!('host' in headers) && !('Host' in headers)) { const { host } = new URL(origin) headers.host = host } opts.headers = { ...this[kProxyHeaders], ...headers } return this.#client[kDispatch](opts, handler) } async [kClose] () { return this.#client.close() } async [kDestroy] (err) { return this.#client.destroy(err) } } class ProxyAgent extends DispatcherBase { constructor (opts) { super() if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) { throw new InvalidArgumentError('Proxy uri is mandatory') } const { clientFactory = defaultFactory } = opts if (typeof clientFactory !== 'function') { throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') } const { proxyTunnel = true } = opts const url = this.#getUrl(opts) const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url this[kProxy] = { uri: href, protocol } this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) ? opts.interceptors.ProxyAgent : [] this[kRequestTls] = opts.requestTls this[kProxyTls] = opts.proxyTls this[kProxyHeaders] = opts.headers || {} this[kTunnelProxy] = proxyTunnel if (opts.auth && opts.token) { throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') } else if (opts.auth) { /* @deprecated in favour of opts.token */ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` } else if (opts.token) { this[kProxyHeaders]['proxy-authorization'] = opts.token } else if (username && password) { this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` } const connect = buildConnector({ ...opts.proxyTls }) this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) const agentFactory = opts.factory || defaultAgentFactory const factory = (origin, options) => { const { protocol } = new URL(origin) if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') { return new Http1ProxyWrapper(this[kProxy].uri, { headers: this[kProxyHeaders], connect, factory: agentFactory }) } return agentFactory(origin, options) } this[kClient] = clientFactory(url, { connect }) this[kAgent] = new Agent({ ...opts, factory, connect: async (opts, callback) => { let requestedPath = opts.host if (!opts.port) { requestedPath += `:${defaultProtocolPort(opts.protocol)}` } try { const { socket, statusCode } = await this[kClient].connect({ origin, port, path: requestedPath, signal: opts.signal, headers: { ...this[kProxyHeaders], host: opts.host }, servername: this[kProxyTls]?.servername || proxyHostname }) if (statusCode !== 200) { socket.on('error', noop).destroy() callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) } if (opts.protocol !== 'https:') { callback(null, socket) return } let servername if (this[kRequestTls]) { servername = this[kRequestTls].servername } else { servername = opts.servername } this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) } catch (err) { if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { // Throw a custom error to avoid loop in client.js#connect callback(new SecureProxyConnectionError(err)) } else { callback(err) } } } }) } dispatch (opts, handler) { const headers = buildHeaders(opts.headers) throwIfProxyAuthIsSent(headers) if (headers && !('host' in headers) && !('Host' in headers)) { const { host } = new URL(opts.origin) headers.host = host } return this[kAgent].dispatch( { ...opts, headers }, handler ) } /** * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts * @returns {URL} */ #getUrl (opts) { if (typeof opts === 'string') { return new URL(opts) } else if (opts instanceof URL) { return opts } else { return new URL(opts.uri) } } async [kClose] () { await this[kAgent].close() await this[kClient].close() } async [kDestroy] () { await this[kAgent].destroy() await this[kClient].destroy() } } /** * @param {string[] | Record} headers * @returns {Record} */ function buildHeaders (headers) { // When using undici.fetch, the headers list is stored // as an array. if (Array.isArray(headers)) { /** @type {Record} */ const headersPair = {} for (let i = 0; i < headers.length; i += 2) { headersPair[headers[i]] = headers[i + 1] } return headersPair } return headers } /** * @param {Record} headers * * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers * Nevertheless, it was changed and to avoid a security vulnerability by end users * this check was created. * It should be removed in the next major version for performance reasons */ function throwIfProxyAuthIsSent (headers) { const existProxyAuth = headers && Object.keys(headers) .find((key) => key.toLowerCase() === 'proxy-authorization') if (existProxyAuth) { throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') } } module.exports = ProxyAgent /***/ }), /***/ 50: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const Dispatcher = __nccwpck_require__(883) const RetryHandler = __nccwpck_require__(7816) class RetryAgent extends Dispatcher { #agent = null #options = null constructor (agent, options = {}) { super(options) this.#agent = agent this.#options = options } dispatch (opts, handler) { const retry = new RetryHandler({ ...opts, retryOptions: this.#options }, { dispatch: this.#agent.dispatch.bind(this.#agent), handler }) return this.#agent.dispatch(opts, retry) } close () { return this.#agent.close() } destroy () { return this.#agent.destroy() } } module.exports = RetryAgent /***/ }), /***/ 2581: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // We include a version number for the Dispatcher API. In case of breaking changes, // this version number must be increased to avoid conflicts. const globalDispatcher = Symbol.for('undici.globalDispatcher.1') const { InvalidArgumentError } = __nccwpck_require__(8707) const Agent = __nccwpck_require__(7405) if (getGlobalDispatcher() === undefined) { setGlobalDispatcher(new Agent()) } function setGlobalDispatcher (agent) { if (!agent || typeof agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument agent must implement Agent') } Object.defineProperty(globalThis, globalDispatcher, { value: agent, writable: true, enumerable: false, configurable: false }) } function getGlobalDispatcher () { return globalThis[globalDispatcher] } module.exports = { setGlobalDispatcher, getGlobalDispatcher } /***/ }), /***/ 8155: /***/ ((module) => { module.exports = class DecoratorHandler { #handler constructor (handler) { if (typeof handler !== 'object' || handler === null) { throw new TypeError('handler must be an object') } this.#handler = handler } onConnect (...args) { return this.#handler.onConnect?.(...args) } onError (...args) { return this.#handler.onError?.(...args) } onUpgrade (...args) { return this.#handler.onUpgrade?.(...args) } onResponseStarted (...args) { return this.#handler.onResponseStarted?.(...args) } onHeaders (...args) { return this.#handler.onHeaders?.(...args) } onData (...args) { return this.#handler.onData?.(...args) } onComplete (...args) { return this.#handler.onComplete?.(...args) } onBodySent (...args) { return this.#handler.onBodySent?.(...args) } } /***/ }), /***/ 8754: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const util = __nccwpck_require__(3440) const { kBodyUsed } = __nccwpck_require__(6443) const assert = __nccwpck_require__(4589) const { InvalidArgumentError } = __nccwpck_require__(8707) const EE = __nccwpck_require__(8474) const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] const kBody = Symbol('body') class BodyAsyncIterable { constructor (body) { this[kBody] = body this[kBodyUsed] = false } async * [Symbol.asyncIterator] () { assert(!this[kBodyUsed], 'disturbed') this[kBodyUsed] = true yield * this[kBody] } } class RedirectHandler { constructor (dispatch, maxRedirections, opts, handler) { if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { throw new InvalidArgumentError('maxRedirections must be a positive number') } util.validateHandler(handler, opts.method, opts.upgrade) this.dispatch = dispatch this.location = null this.abort = null this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy this.maxRedirections = maxRedirections this.handler = handler this.history = [] this.redirectionLimitReached = false if (util.isStream(this.opts.body)) { // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp // so that it can be dispatched again? // TODO (fix): Do we need 100-expect support to provide a way to do this properly? if (util.bodyLength(this.opts.body) === 0) { this.opts.body .on('data', function () { assert(false) }) } if (typeof this.opts.body.readableDidRead !== 'boolean') { this.opts.body[kBodyUsed] = false EE.prototype.on.call(this.opts.body, 'data', function () { this[kBodyUsed] = true }) } } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { // TODO (fix): We can't access ReadableStream internal state // to determine whether or not it has been disturbed. This is just // a workaround. this.opts.body = new BodyAsyncIterable(this.opts.body) } else if ( this.opts.body && typeof this.opts.body !== 'string' && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body) ) { // TODO: Should we allow re-using iterable if !this.opts.idempotent // or through some other flag? this.opts.body = new BodyAsyncIterable(this.opts.body) } } onConnect (abort) { this.abort = abort this.handler.onConnect(abort, { history: this.history }) } onUpgrade (statusCode, headers, socket) { this.handler.onUpgrade(statusCode, headers, socket) } onError (error) { this.handler.onError(error) } onHeaders (statusCode, headers, resume, statusText) { this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers) if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) { if (this.request) { this.request.abort(new Error('max redirects')) } this.redirectionLimitReached = true this.abort(new Error('max redirects')) return } if (this.opts.origin) { this.history.push(new URL(this.opts.path, this.opts.origin)) } if (!this.location) { return this.handler.onHeaders(statusCode, headers, resume, statusText) } const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) const path = search ? `${pathname}${search}` : pathname // Remove headers referring to the original URL. // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. // https://tools.ietf.org/html/rfc7231#section-6.4 this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) this.opts.path = path this.opts.origin = origin this.opts.maxRedirections = 0 this.opts.query = null // https://tools.ietf.org/html/rfc7231#section-6.4.4 // In case of HTTP 303, always replace method to be either HEAD or GET if (statusCode === 303 && this.opts.method !== 'HEAD') { this.opts.method = 'GET' this.opts.body = null } } onData (chunk) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response bodies. Redirection is used to serve the requested resource from another URL, so it is assumes that no body is generated (and thus can be ignored). Even though generating a body is not prohibited. For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually (which means it's optional and not mandated) contain just an hyperlink to the value of the Location response header, so the body can be ignored safely. For status 300, which is "Multiple Choices", the spec mentions both generating a Location response header AND a response body with the other possible location to follow. Since the spec explicitly chooses not to specify a format for such body and leave it to servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. */ } else { return this.handler.onData(chunk) } } onComplete (trailers) { if (this.location) { /* https://tools.ietf.org/html/rfc7231#section-6.4 TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections and neither are useful if present. See comment on onData method above for more detailed information. */ this.location = null this.abort = null this.dispatch(this.opts, this) } else { this.handler.onComplete(trailers) } } onBodySent (chunk) { if (this.handler.onBodySent) { this.handler.onBodySent(chunk) } } } function parseLocation (statusCode, headers) { if (redirectableStatusCodes.indexOf(statusCode) === -1) { return null } for (let i = 0; i < headers.length; i += 2) { if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') { return headers[i + 1] } } } // https://tools.ietf.org/html/rfc7231#section-6.4.4 function shouldRemoveHeader (header, removeContent, unknownOrigin) { if (header.length === 4) { return util.headerNameToString(header) === 'host' } if (removeContent && util.headerNameToString(header).startsWith('content-')) { return true } if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { const name = util.headerNameToString(header) return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' } return false } // https://tools.ietf.org/html/rfc7231#section-6.4 function cleanRequestHeaders (headers, removeContent, unknownOrigin) { const ret = [] if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { ret.push(headers[i], headers[i + 1]) } } } else if (headers && typeof headers === 'object') { for (const key of Object.keys(headers)) { if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { ret.push(key, headers[key]) } } } else { assert(headers == null, 'headers must be an object or an array') } return ret } module.exports = RedirectHandler /***/ }), /***/ 7816: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443) const { RequestRetryError } = __nccwpck_require__(8707) const { isDisturbed, parseHeaders, parseRangeHeader, wrapRequestBody } = __nccwpck_require__(3440) function calculateRetryAfterHeader (retryAfter) { const current = Date.now() return new Date(retryAfter).getTime() - current } class RetryHandler { constructor (opts, handlers) { const { retryOptions, ...dispatchOpts } = opts const { // Retry scoped retry: retryFn, maxRetries, maxTimeout, minTimeout, timeoutFactor, // Response scoped methods, errorCodes, retryAfter, statusCodes } = retryOptions ?? {} this.dispatch = handlers.dispatch this.handler = handlers.handler this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) } this.abort = null this.aborted = false this.retryOpts = { retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], retryAfter: retryAfter ?? true, maxTimeout: maxTimeout ?? 30 * 1000, // 30s, minTimeout: minTimeout ?? 500, // .5s timeoutFactor: timeoutFactor ?? 2, maxRetries: maxRetries ?? 5, // What errors we should retry methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], // Indicates which errors to retry statusCodes: statusCodes ?? [500, 502, 503, 504, 429], // List of errors to retry errorCodes: errorCodes ?? [ 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE', 'UND_ERR_SOCKET' ] } this.retryCount = 0 this.retryCountCheckpoint = 0 this.start = 0 this.end = null this.etag = null this.resume = null // Handle possible onConnect duplication this.handler.onConnect(reason => { this.aborted = true if (this.abort) { this.abort(reason) } else { this.reason = reason } }) } onRequestSent () { if (this.handler.onRequestSent) { this.handler.onRequestSent() } } onUpgrade (statusCode, headers, socket) { if (this.handler.onUpgrade) { this.handler.onUpgrade(statusCode, headers, socket) } } onConnect (abort) { if (this.aborted) { abort(this.reason) } else { this.abort = abort } } onBodySent (chunk) { if (this.handler.onBodySent) return this.handler.onBodySent(chunk) } static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { const { statusCode, code, headers } = err const { method, retryOptions } = opts const { maxRetries, minTimeout, maxTimeout, timeoutFactor, statusCodes, errorCodes, methods } = retryOptions const { counter } = state // Any code that is not a Undici's originated and allowed to retry if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) { cb(err) return } // If a set of method are provided and the current method is not in the list if (Array.isArray(methods) && !methods.includes(method)) { cb(err) return } // If a set of status code are provided and the current status code is not in the list if ( statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode) ) { cb(err) return } // If we reached the max number of retries if (counter > maxRetries) { cb(err) return } let retryAfterHeader = headers?.['retry-after'] if (retryAfterHeader) { retryAfterHeader = Number(retryAfterHeader) retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(retryAfterHeader) : retryAfterHeader * 1e3 // Retry-After is in seconds } const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout) setTimeout(() => cb(null), retryTimeout) } onHeaders (statusCode, rawHeaders, resume, statusMessage) { const headers = parseHeaders(rawHeaders) this.retryCount += 1 if (statusCode >= 300) { if (this.retryOpts.statusCodes.includes(statusCode) === false) { return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } else { this.abort( new RequestRetryError('Request failed', statusCode, { headers, data: { count: this.retryCount } }) ) return false } } // Checkpoint for resume from where we left it if (this.resume != null) { this.resume = null // Only Partial Content 206 supposed to provide Content-Range, // any other status code that partially consumed the payload // should not be retry because it would result in downstream // wrongly concatanete multiple responses. if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) { this.abort( new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, { headers, data: { count: this.retryCount } }) ) return false } const contentRange = parseRangeHeader(headers['content-range']) // If no content range if (!contentRange) { this.abort( new RequestRetryError('Content-Range mismatch', statusCode, { headers, data: { count: this.retryCount } }) ) return false } // Let's start with a weak etag check if (this.etag != null && this.etag !== headers.etag) { this.abort( new RequestRetryError('ETag mismatch', statusCode, { headers, data: { count: this.retryCount } }) ) return false } const { start, size, end = size - 1 } = contentRange assert(this.start === start, 'content-range mismatch') assert(this.end == null || this.end === end, 'content-range mismatch') this.resume = resume return true } if (this.end == null) { if (statusCode === 206) { // First time we receive 206 const range = parseRangeHeader(headers['content-range']) if (range == null) { return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } const { start, size, end = size - 1 } = range assert( start != null && Number.isFinite(start), 'content-range mismatch' ) assert(end != null && Number.isFinite(end), 'invalid content-length') this.start = start this.end = end } // We make our best to checkpoint the body for further range headers if (this.end == null) { const contentLength = headers['content-length'] this.end = contentLength != null ? Number(contentLength) - 1 : null } assert(Number.isFinite(this.start)) assert( this.end == null || Number.isFinite(this.end), 'invalid content-length' ) this.resume = resume this.etag = headers.etag != null ? headers.etag : null // Weak etags are not useful for comparison nor cache // for instance not safe to assume if the response is byte-per-byte // equal if (this.etag != null && this.etag.startsWith('W/')) { this.etag = null } return this.handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } const err = new RequestRetryError('Request failed', statusCode, { headers, data: { count: this.retryCount } }) this.abort(err) return false } onData (chunk) { this.start += chunk.length return this.handler.onData(chunk) } onComplete (rawTrailers) { this.retryCount = 0 return this.handler.onComplete(rawTrailers) } onError (err) { if (this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err) } // We reconcile in case of a mix between network errors // and server error response if (this.retryCount - this.retryCountCheckpoint > 0) { // We count the difference between the last checkpoint and the current retry count this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint) } else { this.retryCount += 1 } this.retryOpts.retry( err, { state: { counter: this.retryCount }, opts: { retryOptions: this.retryOpts, ...this.opts } }, onRetry.bind(this) ) function onRetry (err) { if (err != null || this.aborted || isDisturbed(this.opts.body)) { return this.handler.onError(err) } if (this.start !== 0) { const headers = { range: `bytes=${this.start}-${this.end ?? ''}` } // Weak etag check - weak etags will make comparison algorithms never match if (this.etag != null) { headers['if-match'] = this.etag } this.opts = { ...this.opts, headers: { ...this.opts.headers, ...headers } } } try { this.retryCountCheckpoint = this.retryCount this.dispatch(this.opts, this) } catch (err) { this.handler.onError(err) } } } } module.exports = RetryHandler /***/ }), /***/ 379: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { isIP } = __nccwpck_require__(7030) const { lookup } = __nccwpck_require__(610) const DecoratorHandler = __nccwpck_require__(8155) const { InvalidArgumentError, InformationalError } = __nccwpck_require__(8707) const maxInt = Math.pow(2, 31) - 1 class DNSInstance { #maxTTL = 0 #maxItems = 0 #records = new Map() dualStack = true affinity = null lookup = null pick = null constructor (opts) { this.#maxTTL = opts.maxTTL this.#maxItems = opts.maxItems this.dualStack = opts.dualStack this.affinity = opts.affinity this.lookup = opts.lookup ?? this.#defaultLookup this.pick = opts.pick ?? this.#defaultPick } get full () { return this.#records.size === this.#maxItems } runLookup (origin, opts, cb) { const ips = this.#records.get(origin.hostname) // If full, we just return the origin if (ips == null && this.full) { cb(null, origin.origin) return } const newOpts = { affinity: this.affinity, dualStack: this.dualStack, lookup: this.lookup, pick: this.pick, ...opts.dns, maxTTL: this.#maxTTL, maxItems: this.#maxItems } // If no IPs we lookup if (ips == null) { this.lookup(origin, newOpts, (err, addresses) => { if (err || addresses == null || addresses.length === 0) { cb(err ?? new InformationalError('No DNS entries found')) return } this.setRecords(origin, addresses) const records = this.#records.get(origin.hostname) const ip = this.pick( origin, records, newOpts.affinity ) let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (origin.port !== '') { port = `:${origin.port}` } else { port = '' } cb( null, `${origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}` ) }) } else { // If there's IPs we pick const ip = this.pick( origin, ips, newOpts.affinity ) // If no IPs we lookup - deleting old records if (ip == null) { this.#records.delete(origin.hostname) this.runLookup(origin, opts, cb) return } let port if (typeof ip.port === 'number') { port = `:${ip.port}` } else if (origin.port !== '') { port = `:${origin.port}` } else { port = '' } cb( null, `${origin.protocol}//${ ip.family === 6 ? `[${ip.address}]` : ip.address }${port}` ) } } #defaultLookup (origin, opts, cb) { lookup( origin.hostname, { all: true, family: this.dualStack === false ? this.affinity : 0, order: 'ipv4first' }, (err, addresses) => { if (err) { return cb(err) } const results = new Map() for (const addr of addresses) { // On linux we found duplicates, we attempt to remove them with // the latest record results.set(`${addr.address}:${addr.family}`, addr) } cb(null, results.values()) } ) } #defaultPick (origin, hostnameRecords, affinity) { let ip = null const { records, offset } = hostnameRecords let family if (this.dualStack) { if (affinity == null) { // Balance between ip families if (offset == null || offset === maxInt) { hostnameRecords.offset = 0 affinity = 4 } else { hostnameRecords.offset++ affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4 } } if (records[affinity] != null && records[affinity].ips.length > 0) { family = records[affinity] } else { family = records[affinity === 4 ? 6 : 4] } } else { family = records[affinity] } // If no IPs we return null if (family == null || family.ips.length === 0) { return ip } if (family.offset == null || family.offset === maxInt) { family.offset = 0 } else { family.offset++ } const position = family.offset % family.ips.length ip = family.ips[position] ?? null if (ip == null) { return ip } if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms // We delete expired records // It is possible that they have different TTL, so we manage them individually family.ips.splice(position, 1) return this.pick(origin, hostnameRecords, affinity) } return ip } setRecords (origin, addresses) { const timestamp = Date.now() const records = { records: { 4: null, 6: null } } for (const record of addresses) { record.timestamp = timestamp if (typeof record.ttl === 'number') { // The record TTL is expected to be in ms record.ttl = Math.min(record.ttl, this.#maxTTL) } else { record.ttl = this.#maxTTL } const familyRecords = records.records[record.family] ?? { ips: [] } familyRecords.ips.push(record) records.records[record.family] = familyRecords } this.#records.set(origin.hostname, records) } getHandler (meta, opts) { return new DNSDispatchHandler(this, meta, opts) } } class DNSDispatchHandler extends DecoratorHandler { #state = null #opts = null #dispatch = null #handler = null #origin = null constructor (state, { origin, handler, dispatch }, opts) { super(handler) this.#origin = origin this.#handler = handler this.#opts = { ...opts } this.#state = state this.#dispatch = dispatch } onError (err) { switch (err.code) { case 'ETIMEDOUT': case 'ECONNREFUSED': { if (this.#state.dualStack) { // We delete the record and retry this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => { if (err) { return this.#handler.onError(err) } const dispatchOpts = { ...this.#opts, origin: newOrigin } this.#dispatch(dispatchOpts, this) }) // if dual-stack disabled, we error out return } this.#handler.onError(err) return } case 'ENOTFOUND': this.#state.deleteRecord(this.#origin) // eslint-disable-next-line no-fallthrough default: this.#handler.onError(err) break } } } module.exports = interceptorOpts => { if ( interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0) ) { throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number') } if ( interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== 'number' || interceptorOpts?.maxItems < 1) ) { throw new InvalidArgumentError( 'Invalid maxItems. Must be a positive number and greater than zero' ) } if ( interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6 ) { throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6') } if ( interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== 'boolean' ) { throw new InvalidArgumentError('Invalid dualStack. Must be a boolean') } if ( interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== 'function' ) { throw new InvalidArgumentError('Invalid lookup. Must be a function') } if ( interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== 'function' ) { throw new InvalidArgumentError('Invalid pick. Must be a function') } const dualStack = interceptorOpts?.dualStack ?? true let affinity if (dualStack) { affinity = interceptorOpts?.affinity ?? null } else { affinity = interceptorOpts?.affinity ?? 4 } const opts = { maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms lookup: interceptorOpts?.lookup ?? null, pick: interceptorOpts?.pick ?? null, dualStack, affinity, maxItems: interceptorOpts?.maxItems ?? Infinity } const instance = new DNSInstance(opts) return dispatch => { return function dnsInterceptor (origDispatchOpts, handler) { const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin) if (isIP(origin.hostname) !== 0) { return dispatch(origDispatchOpts, handler) } instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => { if (err) { return handler.onError(err) } let dispatchOpts = null dispatchOpts = { ...origDispatchOpts, servername: origin.hostname, // For SNI on TLS origin: newOrigin, headers: { host: origin.hostname, ...origDispatchOpts.headers } } dispatch( dispatchOpts, instance.getHandler({ origin, dispatch, handler }, origDispatchOpts) ) }) return true } } } /***/ }), /***/ 8060: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const util = __nccwpck_require__(3440) const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) const DecoratorHandler = __nccwpck_require__(8155) class DumpHandler extends DecoratorHandler { #maxSize = 1024 * 1024 #abort = null #dumped = false #aborted = false #size = 0 #reason = null #handler = null constructor ({ maxSize }, handler) { super(handler) if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) { throw new InvalidArgumentError('maxSize must be a number greater than 0') } this.#maxSize = maxSize ?? this.#maxSize this.#handler = handler } onConnect (abort) { this.#abort = abort this.#handler.onConnect(this.#customAbort.bind(this)) } #customAbort (reason) { this.#aborted = true this.#reason = reason } // TODO: will require adjustment after new hooks are out onHeaders (statusCode, rawHeaders, resume, statusMessage) { const headers = util.parseHeaders(rawHeaders) const contentLength = headers['content-length'] if (contentLength != null && contentLength > this.#maxSize) { throw new RequestAbortedError( `Response size (${contentLength}) larger than maxSize (${ this.#maxSize })` ) } if (this.#aborted) { return true } return this.#handler.onHeaders( statusCode, rawHeaders, resume, statusMessage ) } onError (err) { if (this.#dumped) { return } err = this.#reason ?? err this.#handler.onError(err) } onData (chunk) { this.#size = this.#size + chunk.length if (this.#size >= this.#maxSize) { this.#dumped = true if (this.#aborted) { this.#handler.onError(this.#reason) } else { this.#handler.onComplete([]) } } return true } onComplete (trailers) { if (this.#dumped) { return } if (this.#aborted) { this.#handler.onError(this.reason) return } this.#handler.onComplete(trailers) } } function createDumpInterceptor ( { maxSize: defaultMaxSize } = { maxSize: 1024 * 1024 } ) { return dispatch => { return function Intercept (opts, handler) { const { dumpMaxSize = defaultMaxSize } = opts const dumpHandler = new DumpHandler( { maxSize: dumpMaxSize }, handler ) return dispatch(opts, dumpHandler) } } } module.exports = createDumpInterceptor /***/ }), /***/ 5092: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const RedirectHandler = __nccwpck_require__(8754) function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { return (dispatch) => { return function Intercept (opts, handler) { const { maxRedirections = defaultMaxRedirections } = opts if (!maxRedirections) { return dispatch(opts, handler) } const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. return dispatch(opts, redirectHandler) } } } module.exports = createRedirectInterceptor /***/ }), /***/ 1514: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const RedirectHandler = __nccwpck_require__(8754) module.exports = opts => { const globalMaxRedirections = opts?.maxRedirections return dispatch => { return function redirectInterceptor (opts, handler) { const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts if (!maxRedirections) { return dispatch(opts, handler) } const redirectHandler = new RedirectHandler( dispatch, maxRedirections, opts, handler ) return dispatch(baseOpts, redirectHandler) } } } /***/ }), /***/ 2026: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const RetryHandler = __nccwpck_require__(7816) module.exports = globalOpts => { return dispatch => { return function retryInterceptor (opts, handler) { return dispatch( opts, new RetryHandler( { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } }, { handler, dispatch } ) ) } } } /***/ }), /***/ 2824: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; const utils_1 = __nccwpck_require__(172); // C headers var ERROR; (function (ERROR) { ERROR[ERROR["OK"] = 0] = "OK"; ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; ERROR[ERROR["STRICT"] = 2] = "STRICT"; ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; ERROR[ERROR["USER"] = 24] = "USER"; })(ERROR = exports.ERROR || (exports.ERROR = {})); var TYPE; (function (TYPE) { TYPE[TYPE["BOTH"] = 0] = "BOTH"; TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; })(TYPE = exports.TYPE || (exports.TYPE = {})); var FLAGS; (function (FLAGS) { FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; // 1 << 8 is unused FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; })(FLAGS = exports.FLAGS || (exports.FLAGS = {})); var LENIENT_FLAGS; (function (LENIENT_FLAGS) { LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; })(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); var METHODS; (function (METHODS) { METHODS[METHODS["DELETE"] = 0] = "DELETE"; METHODS[METHODS["GET"] = 1] = "GET"; METHODS[METHODS["HEAD"] = 2] = "HEAD"; METHODS[METHODS["POST"] = 3] = "POST"; METHODS[METHODS["PUT"] = 4] = "PUT"; /* pathological */ METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; METHODS[METHODS["TRACE"] = 7] = "TRACE"; /* WebDAV */ METHODS[METHODS["COPY"] = 8] = "COPY"; METHODS[METHODS["LOCK"] = 9] = "LOCK"; METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; METHODS[METHODS["MOVE"] = 11] = "MOVE"; METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; METHODS[METHODS["BIND"] = 16] = "BIND"; METHODS[METHODS["REBIND"] = 17] = "REBIND"; METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; METHODS[METHODS["ACL"] = 19] = "ACL"; /* subversion */ METHODS[METHODS["REPORT"] = 20] = "REPORT"; METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; METHODS[METHODS["MERGE"] = 23] = "MERGE"; /* upnp */ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; /* RFC-5789 */ METHODS[METHODS["PATCH"] = 28] = "PATCH"; METHODS[METHODS["PURGE"] = 29] = "PURGE"; /* CalDAV */ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; /* RFC-2068, section 19.6.1.2 */ METHODS[METHODS["LINK"] = 31] = "LINK"; METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; /* icecast */ METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; /* RFC-7540, section 11.6 */ METHODS[METHODS["PRI"] = 34] = "PRI"; /* RFC-2326 RTSP */ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; METHODS[METHODS["SETUP"] = 37] = "SETUP"; METHODS[METHODS["PLAY"] = 38] = "PLAY"; METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; METHODS[METHODS["RECORD"] = 44] = "RECORD"; /* RAOP */ METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; })(METHODS = exports.METHODS || (exports.METHODS = {})); exports.METHODS_HTTP = [ METHODS.DELETE, METHODS.GET, METHODS.HEAD, METHODS.POST, METHODS.PUT, METHODS.CONNECT, METHODS.OPTIONS, METHODS.TRACE, METHODS.COPY, METHODS.LOCK, METHODS.MKCOL, METHODS.MOVE, METHODS.PROPFIND, METHODS.PROPPATCH, METHODS.SEARCH, METHODS.UNLOCK, METHODS.BIND, METHODS.REBIND, METHODS.UNBIND, METHODS.ACL, METHODS.REPORT, METHODS.MKACTIVITY, METHODS.CHECKOUT, METHODS.MERGE, METHODS['M-SEARCH'], METHODS.NOTIFY, METHODS.SUBSCRIBE, METHODS.UNSUBSCRIBE, METHODS.PATCH, METHODS.PURGE, METHODS.MKCALENDAR, METHODS.LINK, METHODS.UNLINK, METHODS.PRI, // TODO(indutny): should we allow it with HTTP? METHODS.SOURCE, ]; exports.METHODS_ICE = [ METHODS.SOURCE, ]; exports.METHODS_RTSP = [ METHODS.OPTIONS, METHODS.DESCRIBE, METHODS.ANNOUNCE, METHODS.SETUP, METHODS.PLAY, METHODS.PAUSE, METHODS.TEARDOWN, METHODS.GET_PARAMETER, METHODS.SET_PARAMETER, METHODS.REDIRECT, METHODS.RECORD, METHODS.FLUSH, // For AirPlay METHODS.GET, METHODS.POST, ]; exports.METHOD_MAP = utils_1.enumToMap(METHODS); exports.H_METHOD_MAP = {}; Object.keys(exports.METHOD_MAP).forEach((key) => { if (/^H/.test(key)) { exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; } }); var FINISH; (function (FINISH) { FINISH[FINISH["SAFE"] = 0] = "SAFE"; FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; })(FINISH = exports.FINISH || (exports.FINISH = {})); exports.ALPHA = []; for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { // Upper case exports.ALPHA.push(String.fromCharCode(i)); // Lower case exports.ALPHA.push(String.fromCharCode(i + 0x20)); } exports.NUM_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, }; exports.HEX_MAP = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, }; exports.NUM = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ]; exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; exports.USERINFO_CHARS = exports.ALPHANUM .concat(exports.MARK) .concat(['%', ';', ':', '&', '=', '+', '$', ',']); // TODO(indutny): use RFC exports.STRICT_URL_CHAR = [ '!', '"', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ].concat(exports.ALPHANUM); exports.URL_CHAR = exports.STRICT_URL_CHAR .concat(['\t', '\f']); // All characters with 0x80 bit set to 1 for (let i = 0x80; i <= 0xff; i++) { exports.URL_CHAR.push(i); } exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); /* Tokens as defined by rfc 2616. Also lowercases them. * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT */ exports.STRICT_TOKEN = [ '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~', ].concat(exports.ALPHANUM); exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); /* * Verify that a char is a valid visible (printable) US-ASCII * character or %x80-FF */ exports.HEADER_CHARS = ['\t']; for (let i = 32; i <= 255; i++) { if (i !== 127) { exports.HEADER_CHARS.push(i); } } // ',' = \x44 exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); exports.MAJOR = exports.NUM_MAP; exports.MINOR = exports.MAJOR; var HEADER_STATE; (function (HEADER_STATE) { HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; })(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); exports.SPECIAL_HEADERS = { 'connection': HEADER_STATE.CONNECTION, 'content-length': HEADER_STATE.CONTENT_LENGTH, 'proxy-connection': HEADER_STATE.CONNECTION, 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, 'upgrade': HEADER_STATE.UPGRADE, }; //# sourceMappingURL=constants.js.map /***/ }), /***/ 3870: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Buffer } = __nccwpck_require__(4573) module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQA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B0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2Agx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AQEBAQEBAQEBAEH6yAALBAEAAAIAQZDJAAtfAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAQfrKAAsEAQAAAQBBkMsACwEBAEGqywALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64') /***/ }), /***/ 3434: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Buffer } = __nccwpck_require__(4573) module.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0s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DEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHK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AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+sgACwQBAAACAEGQyQALXwMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAEH6ygALBAEAAAEAQZDLAAsBAQBBqssAC0ECAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB+swACwQBAAABAEGQzQALAQEAQZrNAAsGAgAAAAACAEGxzQALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQfDOAAuWAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64') /***/ }), /***/ 172: /***/ ((__unused_webpack_module, exports) => { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.enumToMap = void 0; function enumToMap(obj) { const res = {}; Object.keys(obj).forEach((key) => { const value = obj[key]; if (typeof value === 'number') { res[key] = value; } }); return res; } exports.enumToMap = enumToMap; //# sourceMappingURL=utils.js.map /***/ }), /***/ 7501: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kClients } = __nccwpck_require__(6443) const Agent = __nccwpck_require__(7405) const { kAgent, kMockAgentSet, kMockAgentGet, kDispatches, kIsMockActive, kNetConnect, kGetNetConnect, kOptions, kFactory } = __nccwpck_require__(1117) const MockClient = __nccwpck_require__(7365) const MockPool = __nccwpck_require__(4004) const { matchValue, buildMockOptions } = __nccwpck_require__(3397) const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707) const Dispatcher = __nccwpck_require__(883) const Pluralizer = __nccwpck_require__(1529) const PendingInterceptorsFormatter = __nccwpck_require__(6142) class MockAgent extends Dispatcher { constructor (opts) { super(opts) this[kNetConnect] = true this[kIsMockActive] = true // Instantiate Agent and encapsulate if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } const agent = opts?.agent ? opts.agent : new Agent(opts) this[kAgent] = agent this[kClients] = agent[kClients] this[kOptions] = buildMockOptions(opts) } get (origin) { let dispatcher = this[kMockAgentGet](origin) if (!dispatcher) { dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) } return dispatcher } dispatch (opts, handler) { // Call MockAgent.get to perform additional setup before dispatching as normal this.get(opts.origin) return this[kAgent].dispatch(opts, handler) } async close () { await this[kAgent].close() this[kClients].clear() } deactivate () { this[kIsMockActive] = false } activate () { this[kIsMockActive] = true } enableNetConnect (matcher) { if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { if (Array.isArray(this[kNetConnect])) { this[kNetConnect].push(matcher) } else { this[kNetConnect] = [matcher] } } else if (typeof matcher === 'undefined') { this[kNetConnect] = true } else { throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') } } disableNetConnect () { this[kNetConnect] = false } // This is required to bypass issues caused by using global symbols - see: // https://github.com/nodejs/undici/issues/1447 get isMockActive () { return this[kIsMockActive] } [kMockAgentSet] (origin, dispatcher) { this[kClients].set(origin, dispatcher) } [kFactory] (origin) { const mockOptions = Object.assign({ agent: this }, this[kOptions]) return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions) } [kMockAgentGet] (origin) { // First check if we can immediately find it const client = this[kClients].get(origin) if (client) { return client } // If the origin is not a string create a dummy parent pool and return to user if (typeof origin !== 'string') { const dispatcher = this[kFactory]('http://localhost:9999') this[kMockAgentSet](origin, dispatcher) return dispatcher } // If we match, create a pool and assign the same dispatches for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) { if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { const dispatcher = this[kFactory](origin) this[kMockAgentSet](origin, dispatcher) dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] return dispatcher } } } [kGetNetConnect] () { return this[kNetConnect] } pendingInterceptors () { const mockAgentClients = this[kClients] return Array.from(mockAgentClients.entries()) .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin }))) .filter(({ pending }) => pending) } assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { const pending = this.pendingInterceptors() if (pending.length === 0) { return } const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) throw new UndiciError(` ${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: ${pendingInterceptorsFormatter.format(pending)} `.trim()) } } module.exports = MockAgent /***/ }), /***/ 7365: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { promisify } = __nccwpck_require__(7975) const Client = __nccwpck_require__(3701) const { buildMockDispatch } = __nccwpck_require__(3397) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = __nccwpck_require__(1117) const { MockInterceptor } = __nccwpck_require__(1511) const Symbols = __nccwpck_require__(6443) const { InvalidArgumentError } = __nccwpck_require__(8707) /** * MockClient provides an API that extends the Client to influence the mockDispatches. */ class MockClient extends Client { constructor (origin, opts) { super(origin, opts) if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } this[kMockAgent] = opts.agent this[kOrigin] = origin this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor(opts, this[kDispatches]) } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockClient /***/ }), /***/ 2429: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { UndiciError } = __nccwpck_require__(8707) const kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED') /** * The request does not match any registered mock dispatches. */ class MockNotMatchedError extends UndiciError { constructor (message) { super(message) Error.captureStackTrace(this, MockNotMatchedError) this.name = 'MockNotMatchedError' this.message = message || 'The request does not match any registered mock dispatches' this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' } static [Symbol.hasInstance] (instance) { return instance && instance[kMockNotMatchedError] === true } [kMockNotMatchedError] = true } module.exports = { MockNotMatchedError } /***/ }), /***/ 1511: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397) const { kDispatches, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch } = __nccwpck_require__(1117) const { InvalidArgumentError } = __nccwpck_require__(8707) const { buildURL } = __nccwpck_require__(3440) /** * Defines the scope API for an interceptor reply */ class MockScope { constructor (mockDispatch) { this[kMockDispatch] = mockDispatch } /** * Delay a reply by a set amount in ms. */ delay (waitInMs) { if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { throw new InvalidArgumentError('waitInMs must be a valid integer > 0') } this[kMockDispatch].delay = waitInMs return this } /** * For a defined reply, never mark as consumed. */ persist () { this[kMockDispatch].persist = true return this } /** * Allow one to define a reply for a set amount of matching requests. */ times (repeatTimes) { if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') } this[kMockDispatch].times = repeatTimes return this } } /** * Defines an interceptor for a Mock */ class MockInterceptor { constructor (opts, mockDispatches) { if (typeof opts !== 'object') { throw new InvalidArgumentError('opts must be an object') } if (typeof opts.path === 'undefined') { throw new InvalidArgumentError('opts.path must be defined') } if (typeof opts.method === 'undefined') { opts.method = 'GET' } // See https://github.com/nodejs/undici/issues/1245 // As per RFC 3986, clients are not supposed to send URI // fragments to servers when they retrieve a document, if (typeof opts.path === 'string') { if (opts.query) { opts.path = buildURL(opts.path, opts.query) } else { // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811 const parsedURL = new URL(opts.path, 'data://') opts.path = parsedURL.pathname + parsedURL.search } } if (typeof opts.method === 'string') { opts.method = opts.method.toUpperCase() } this[kDispatchKey] = buildKey(opts) this[kDispatches] = mockDispatches this[kDefaultHeaders] = {} this[kDefaultTrailers] = {} this[kContentLength] = false } createMockScopeDispatchData ({ statusCode, data, responseOptions }) { const responseData = getResponseData(data) const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } return { statusCode, data, headers, trailers } } validateReplyParameters (replyParameters) { if (typeof replyParameters.statusCode === 'undefined') { throw new InvalidArgumentError('statusCode must be defined') } if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) { throw new InvalidArgumentError('responseOptions must be an object') } } /** * Mock an undici request with a defined reply. */ reply (replyOptionsCallbackOrStatusCode) { // Values of reply aren't available right now as they // can only be available when the reply callback is invoked. if (typeof replyOptionsCallbackOrStatusCode === 'function') { // We'll first wrap the provided callback in another function, // this function will properly resolve the data from the callback // when invoked. const wrappedDefaultsCallback = (opts) => { // Our reply options callback contains the parameter for statusCode, data and options. const resolvedData = replyOptionsCallbackOrStatusCode(opts) // Check if it is in the right format if (typeof resolvedData !== 'object' || resolvedData === null) { throw new InvalidArgumentError('reply options callback must return an object') } const replyParameters = { data: '', responseOptions: {}, ...resolvedData } this.validateReplyParameters(replyParameters) // Since the values can be obtained immediately we return them // from this higher order function that will be resolved later. return { ...this.createMockScopeDispatchData(replyParameters) } } // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) return new MockScope(newMockDispatch) } // We can have either one or three parameters, if we get here, // we should have 1-3 parameters. So we spread the arguments of // this function to obtain the parameters, since replyData will always // just be the statusCode. const replyParameters = { statusCode: replyOptionsCallbackOrStatusCode, data: arguments[1] === undefined ? '' : arguments[1], responseOptions: arguments[2] === undefined ? {} : arguments[2] } this.validateReplyParameters(replyParameters) // Send in-already provided data like usual const dispatchData = this.createMockScopeDispatchData(replyParameters) const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) return new MockScope(newMockDispatch) } /** * Mock an undici request with a defined error. */ replyWithError (error) { if (typeof error === 'undefined') { throw new InvalidArgumentError('error must be defined') } const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) return new MockScope(newMockDispatch) } /** * Set default reply headers on the interceptor for subsequent replies */ defaultReplyHeaders (headers) { if (typeof headers === 'undefined') { throw new InvalidArgumentError('headers must be defined') } this[kDefaultHeaders] = headers return this } /** * Set default reply trailers on the interceptor for subsequent replies */ defaultReplyTrailers (trailers) { if (typeof trailers === 'undefined') { throw new InvalidArgumentError('trailers must be defined') } this[kDefaultTrailers] = trailers return this } /** * Set reply content length header for replies on the interceptor */ replyContentLength () { this[kContentLength] = true return this } } module.exports.MockInterceptor = MockInterceptor module.exports.MockScope = MockScope /***/ }), /***/ 4004: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { promisify } = __nccwpck_require__(7975) const Pool = __nccwpck_require__(628) const { buildMockDispatch } = __nccwpck_require__(3397) const { kDispatches, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected } = __nccwpck_require__(1117) const { MockInterceptor } = __nccwpck_require__(1511) const Symbols = __nccwpck_require__(6443) const { InvalidArgumentError } = __nccwpck_require__(8707) /** * MockPool provides an API that extends the Pool to influence the mockDispatches. */ class MockPool extends Pool { constructor (origin, opts) { super(origin, opts) if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { throw new InvalidArgumentError('Argument opts.agent must implement Agent') } this[kMockAgent] = opts.agent this[kOrigin] = origin this[kDispatches] = [] this[kConnected] = 1 this[kOriginalDispatch] = this.dispatch this[kOriginalClose] = this.close.bind(this) this.dispatch = buildMockDispatch.call(this) this.close = this[kClose] } get [Symbols.kConnected] () { return this[kConnected] } /** * Sets up the base interceptor for mocking replies from undici. */ intercept (opts) { return new MockInterceptor(opts, this[kDispatches]) } async [kClose] () { await promisify(this[kOriginalClose])() this[kConnected] = 0 this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) } } module.exports = MockPool /***/ }), /***/ 1117: /***/ ((module) => { module.exports = { kAgent: Symbol('agent'), kOptions: Symbol('options'), kFactory: Symbol('factory'), kDispatches: Symbol('dispatches'), kDispatchKey: Symbol('dispatch key'), kDefaultHeaders: Symbol('default headers'), kDefaultTrailers: Symbol('default trailers'), kContentLength: Symbol('content length'), kMockAgent: Symbol('mock agent'), kMockAgentSet: Symbol('mock agent set'), kMockAgentGet: Symbol('mock agent get'), kMockDispatch: Symbol('mock dispatch'), kClose: Symbol('close'), kOriginalClose: Symbol('original agent close'), kOrigin: Symbol('origin'), kIsMockActive: Symbol('is mock active'), kNetConnect: Symbol('net connect'), kGetNetConnect: Symbol('get net connect'), kConnected: Symbol('connected') } /***/ }), /***/ 3397: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { MockNotMatchedError } = __nccwpck_require__(2429) const { kDispatches, kMockAgent, kOriginalDispatch, kOrigin, kGetNetConnect } = __nccwpck_require__(1117) const { buildURL } = __nccwpck_require__(3440) const { STATUS_CODES } = __nccwpck_require__(7067) const { types: { isPromise } } = __nccwpck_require__(7975) function matchValue (match, value) { if (typeof match === 'string') { return match === value } if (match instanceof RegExp) { return match.test(value) } if (typeof match === 'function') { return match(value) === true } return false } function lowerCaseEntries (headers) { return Object.fromEntries( Object.entries(headers).map(([headerName, headerValue]) => { return [headerName.toLocaleLowerCase(), headerValue] }) ) } /** * @param {import('../../index').Headers|string[]|Record} headers * @param {string} key */ function getHeaderByName (headers, key) { if (Array.isArray(headers)) { for (let i = 0; i < headers.length; i += 2) { if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { return headers[i + 1] } } return undefined } else if (typeof headers.get === 'function') { return headers.get(key) } else { return lowerCaseEntries(headers)[key.toLocaleLowerCase()] } } /** @param {string[]} headers */ function buildHeadersFromArray (headers) { // fetch HeadersList const clone = headers.slice() const entries = [] for (let index = 0; index < clone.length; index += 2) { entries.push([clone[index], clone[index + 1]]) } return Object.fromEntries(entries) } function matchHeaders (mockDispatch, headers) { if (typeof mockDispatch.headers === 'function') { if (Array.isArray(headers)) { // fetch HeadersList headers = buildHeadersFromArray(headers) } return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) } if (typeof mockDispatch.headers === 'undefined') { return true } if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { return false } for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { const headerValue = getHeaderByName(headers, matchHeaderName) if (!matchValue(matchHeaderValue, headerValue)) { return false } } return true } function safeUrl (path) { if (typeof path !== 'string') { return path } const pathSegments = path.split('?') if (pathSegments.length !== 2) { return path } const qp = new URLSearchParams(pathSegments.pop()) qp.sort() return [...pathSegments, qp.toString()].join('?') } function matchKey (mockDispatch, { path, method, body, headers }) { const pathMatch = matchValue(mockDispatch.path, path) const methodMatch = matchValue(mockDispatch.method, method) const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true const headersMatch = matchHeaders(mockDispatch, headers) return pathMatch && methodMatch && bodyMatch && headersMatch } function getResponseData (data) { if (Buffer.isBuffer(data)) { return data } else if (data instanceof Uint8Array) { return data } else if (data instanceof ArrayBuffer) { return data } else if (typeof data === 'object') { return JSON.stringify(data) } else { return data.toString() } } function getMockDispatch (mockDispatches, key) { const basePath = key.query ? buildURL(key.path, key.query) : key.path const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath // Match path let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) } // Match method matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`) } // Match body matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`) } // Match headers matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) if (matchedMockDispatches.length === 0) { const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`) } return matchedMockDispatches[0] } function addMockDispatch (mockDispatches, key, data) { const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } const replyData = typeof data === 'function' ? { callback: data } : { ...data } const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } mockDispatches.push(newMockDispatch) return newMockDispatch } function deleteMockDispatch (mockDispatches, key) { const index = mockDispatches.findIndex(dispatch => { if (!dispatch.consumed) { return false } return matchKey(dispatch, key) }) if (index !== -1) { mockDispatches.splice(index, 1) } } function buildKey (opts) { const { path, method, body, headers, query } = opts return { path, method, body, headers, query } } function generateKeyValues (data) { const keys = Object.keys(data) const result = [] for (let i = 0; i < keys.length; ++i) { const key = keys[i] const value = data[key] const name = Buffer.from(`${key}`) if (Array.isArray(value)) { for (let j = 0; j < value.length; ++j) { result.push(name, Buffer.from(`${value[j]}`)) } } else { result.push(name, Buffer.from(`${value}`)) } } return result } /** * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status * @param {number} statusCode */ function getStatusText (statusCode) { return STATUS_CODES[statusCode] || 'unknown' } async function getResponse (body) { const buffers = [] for await (const data of body) { buffers.push(data) } return Buffer.concat(buffers).toString('utf8') } /** * Mock dispatch function used to simulate undici dispatches */ function mockDispatch (opts, handler) { // Get mock dispatch from built key const key = buildKey(opts) const mockDispatch = getMockDispatch(this[kDispatches], key) mockDispatch.timesInvoked++ // Here's where we resolve a callback if a callback is present for the dispatch data. if (mockDispatch.data.callback) { mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } } // Parse mockDispatch data const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch const { timesInvoked, times } = mockDispatch // If it's used up and not persistent, mark as consumed mockDispatch.consumed = !persist && timesInvoked >= times mockDispatch.pending = timesInvoked < times // If specified, trigger dispatch error if (error !== null) { deleteMockDispatch(this[kDispatches], key) handler.onError(error) return true } // Handle the request with a delay if necessary if (typeof delay === 'number' && delay > 0) { setTimeout(() => { handleReply(this[kDispatches]) }, delay) } else { handleReply(this[kDispatches]) } function handleReply (mockDispatches, _data = data) { // fetch's HeadersList is a 1D string array const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers const body = typeof _data === 'function' ? _data({ ...opts, headers: optsHeaders }) : _data // util.types.isPromise is likely needed for jest. if (isPromise(body)) { // If handleReply is asynchronous, throwing an error // in the callback will reject the promise, rather than // synchronously throw the error, which breaks some tests. // Rather, we wait for the callback to resolve if it is a // promise, and then re-run handleReply with the new body. body.then((newData) => handleReply(mockDispatches, newData)) return } const responseData = getResponseData(body) const responseHeaders = generateKeyValues(headers) const responseTrailers = generateKeyValues(trailers) handler.onConnect?.(err => handler.onError(err), null) handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode)) handler.onData?.(Buffer.from(responseData)) handler.onComplete?.(responseTrailers) deleteMockDispatch(mockDispatches, key) } function resume () {} return true } function buildMockDispatch () { const agent = this[kMockAgent] const origin = this[kOrigin] const originalDispatch = this[kOriginalDispatch] return function dispatch (opts, handler) { if (agent.isMockActive) { try { mockDispatch.call(this, opts, handler) } catch (error) { if (error instanceof MockNotMatchedError) { const netConnect = agent[kGetNetConnect]() if (netConnect === false) { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) } if (checkNetConnect(netConnect, origin)) { originalDispatch.call(this, opts, handler) } else { throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) } } else { throw error } } } else { originalDispatch.call(this, opts, handler) } } } function checkNetConnect (netConnect, origin) { const url = new URL(origin) if (netConnect === true) { return true } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { return true } return false } function buildMockOptions (opts) { if (opts) { const { agent, ...mockOptions } = opts return mockOptions } } module.exports = { getResponseData, getMockDispatch, addMockDispatch, deleteMockDispatch, buildKey, generateKeyValues, matchValue, getResponse, getStatusText, mockDispatch, buildMockDispatch, checkNetConnect, buildMockOptions, getHeaderByName, buildHeadersFromArray } /***/ }), /***/ 6142: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Transform } = __nccwpck_require__(7075) const { Console } = __nccwpck_require__(7540) const PERSISTENT = process.versions.icu ? '✅' : 'Y ' const NOT_PERSISTENT = process.versions.icu ? '❌' : 'N ' /** * Gets the output of `console.table(…)` as a string. */ module.exports = class PendingInterceptorsFormatter { constructor ({ disableColors } = {}) { this.transform = new Transform({ transform (chunk, _enc, cb) { cb(null, chunk) } }) this.logger = new Console({ stdout: this.transform, inspectOptions: { colors: !disableColors && !process.env.CI } }) } format (pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, Path: path, 'Status code': statusCode, Persistent: persist ? PERSISTENT : NOT_PERSISTENT, Invocations: timesInvoked, Remaining: persist ? Infinity : times - timesInvoked })) this.logger.table(withPrettyHeaders) return this.transform.read().toString() } } /***/ }), /***/ 1529: /***/ ((module) => { const singulars = { pronoun: 'it', is: 'is', was: 'was', this: 'this' } const plurals = { pronoun: 'they', is: 'are', was: 'were', this: 'these' } module.exports = class Pluralizer { constructor (singular, plural) { this.singular = singular this.plural = plural } pluralize (count) { const one = count === 1 const keys = one ? singulars : plurals const noun = one ? this.singular : this.plural return { ...keys, count, noun } } } /***/ }), /***/ 6603: /***/ ((module) => { /** * This module offers an optimized timer implementation designed for scenarios * where high precision is not critical. * * The timer achieves faster performance by using a low-resolution approach, * with an accuracy target of within 500ms. This makes it particularly useful * for timers with delays of 1 second or more, where exact timing is less * crucial. * * It's important to note that Node.js timers are inherently imprecise, as * delays can occur due to the event loop being blocked by other operations. * Consequently, timers may trigger later than their scheduled time. */ /** * The fastNow variable contains the internal fast timer clock value. * * @type {number} */ let fastNow = 0 /** * RESOLUTION_MS represents the target resolution time in milliseconds. * * @type {number} * @default 1000 */ const RESOLUTION_MS = 1e3 /** * TICK_MS defines the desired interval in milliseconds between each tick. * The target value is set to half the resolution time, minus 1 ms, to account * for potential event loop overhead. * * @type {number} * @default 499 */ const TICK_MS = (RESOLUTION_MS >> 1) - 1 /** * fastNowTimeout is a Node.js timer used to manage and process * the FastTimers stored in the `fastTimers` array. * * @type {NodeJS.Timeout} */ let fastNowTimeout /** * The kFastTimer symbol is used to identify FastTimer instances. * * @type {Symbol} */ const kFastTimer = Symbol('kFastTimer') /** * The fastTimers array contains all active FastTimers. * * @type {FastTimer[]} */ const fastTimers = [] /** * These constants represent the various states of a FastTimer. */ /** * The `NOT_IN_LIST` constant indicates that the FastTimer is not included * in the `fastTimers` array. Timers with this status will not be processed * during the next tick by the `onTick` function. * * A FastTimer can be re-added to the `fastTimers` array by invoking the * `refresh` method on the FastTimer instance. * * @type {-2} */ const NOT_IN_LIST = -2 /** * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled * for removal from the `fastTimers` array. A FastTimer in this state will * be removed in the next tick by the `onTick` function and will no longer * be processed. * * This status is also set when the `clear` method is called on the FastTimer instance. * * @type {-1} */ const TO_BE_CLEARED = -1 /** * The `PENDING` constant signifies that the FastTimer is awaiting processing * in the next tick by the `onTick` function. Timers with this status will have * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick. * * @type {0} */ const PENDING = 0 /** * The `ACTIVE` constant indicates that the FastTimer is active and waiting * for its timer to expire. During the next tick, the `onTick` function will * check if the timer has expired, and if so, it will execute the associated callback. * * @type {1} */ const ACTIVE = 1 /** * The onTick function processes the fastTimers array. * * @returns {void} */ function onTick () { /** * Increment the fastNow value by the TICK_MS value, despite the actual time * that has passed since the last tick. This approach ensures independence * from the system clock and delays caused by a blocked event loop. * * @type {number} */ fastNow += TICK_MS /** * The `idx` variable is used to iterate over the `fastTimers` array. * Expired timers are removed by replacing them with the last element in the array. * Consequently, `idx` is only incremented when the current element is not removed. * * @type {number} */ let idx = 0 /** * The len variable will contain the length of the fastTimers array * and will be decremented when a FastTimer should be removed from the * fastTimers array. * * @type {number} */ let len = fastTimers.length while (idx < len) { /** * @type {FastTimer} */ const timer = fastTimers[idx] // If the timer is in the ACTIVE state and the timer has expired, it will // be processed in the next tick. if (timer._state === PENDING) { // Set the _idleStart value to the fastNow value minus the TICK_MS value // to account for the time the timer was in the PENDING state. timer._idleStart = fastNow - TICK_MS timer._state = ACTIVE } else if ( timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout ) { timer._state = TO_BE_CLEARED timer._idleStart = -1 timer._onTimeout(timer._timerArg) } if (timer._state === TO_BE_CLEARED) { timer._state = NOT_IN_LIST // Move the last element to the current index and decrement len if it is // not the only element in the array. if (--len !== 0) { fastTimers[idx] = fastTimers[len] } } else { ++idx } } // Set the length of the fastTimers array to the new length and thus // removing the excess FastTimers elements from the array. fastTimers.length = len // If there are still active FastTimers in the array, refresh the Timer. // If there are no active FastTimers, the timer will be refreshed again // when a new FastTimer is instantiated. if (fastTimers.length !== 0) { refreshTimeout() } } function refreshTimeout () { // If the fastNowTimeout is already set, refresh it. if (fastNowTimeout) { fastNowTimeout.refresh() // fastNowTimeout is not instantiated yet, create a new Timer. } else { clearTimeout(fastNowTimeout) fastNowTimeout = setTimeout(onTick, TICK_MS) // If the Timer has an unref method, call it to allow the process to exit if // there are no other active handles. if (fastNowTimeout.unref) { fastNowTimeout.unref() } } } /** * The `FastTimer` class is a data structure designed to store and manage * timer information. */ class FastTimer { [kFastTimer] = true /** * The state of the timer, which can be one of the following: * - NOT_IN_LIST (-2) * - TO_BE_CLEARED (-1) * - PENDING (0) * - ACTIVE (1) * * @type {-2|-1|0|1} * @private */ _state = NOT_IN_LIST /** * The number of milliseconds to wait before calling the callback. * * @type {number} * @private */ _idleTimeout = -1 /** * The time in milliseconds when the timer was started. This value is used to * calculate when the timer should expire. * * @type {number} * @default -1 * @private */ _idleStart = -1 /** * The function to be executed when the timer expires. * @type {Function} * @private */ _onTimeout /** * The argument to be passed to the callback when the timer expires. * * @type {*} * @private */ _timerArg /** * @constructor * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should wait * before the specified function or code is executed. * @param {*} arg */ constructor (callback, delay, arg) { this._onTimeout = callback this._idleTimeout = delay this._timerArg = arg this.refresh() } /** * Sets the timer's start time to the current time, and reschedules the timer * to call its callback at the previously specified duration adjusted to the * current time. * Using this on a timer that has already called its callback will reactivate * the timer. * * @returns {void} */ refresh () { // In the special case that the timer is not in the list of active timers, // add it back to the array to be processed in the next tick by the onTick // function. if (this._state === NOT_IN_LIST) { fastTimers.push(this) } // If the timer is the only active timer, refresh the fastNowTimeout for // better resolution. if (!fastNowTimeout || fastTimers.length === 1) { refreshTimeout() } // Setting the state to PENDING will cause the timer to be reset in the // next tick by the onTick function. this._state = PENDING } /** * The `clear` method cancels the timer, preventing it from executing. * * @returns {void} * @private */ clear () { // Set the state to TO_BE_CLEARED to mark the timer for removal in the next // tick by the onTick function. this._state = TO_BE_CLEARED // Reset the _idleStart value to -1 to indicate that the timer is no longer // active. this._idleStart = -1 } } /** * This module exports a setTimeout and clearTimeout function that can be * used as a drop-in replacement for the native functions. */ module.exports = { /** * The setTimeout() method sets a timer which executes a function once the * timer expires. * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should * wait before the specified function or code is executed. * @param {*} [arg] An optional argument to be passed to the callback function * when the timer expires. * @returns {NodeJS.Timeout|FastTimer} */ setTimeout (callback, delay, arg) { // If the delay is less than or equal to the RESOLUTION_MS value return a // native Node.js Timer instance. return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg) }, /** * The clearTimeout method cancels an instantiated Timer previously created * by calling setTimeout. * * @param {NodeJS.Timeout|FastTimer} timeout */ clearTimeout (timeout) { // If the timeout is a FastTimer, call its own clear method. if (timeout[kFastTimer]) { /** * @type {FastTimer} */ timeout.clear() // Otherwise it is an instance of a native NodeJS.Timeout, so call the // Node.js native clearTimeout function. } else { clearTimeout(timeout) } }, /** * The setFastTimeout() method sets a fastTimer which executes a function once * the timer expires. * @param {Function} callback A function to be executed after the timer * expires. * @param {number} delay The time, in milliseconds that the timer should * wait before the specified function or code is executed. * @param {*} [arg] An optional argument to be passed to the callback function * when the timer expires. * @returns {FastTimer} */ setFastTimeout (callback, delay, arg) { return new FastTimer(callback, delay, arg) }, /** * The clearTimeout method cancels an instantiated FastTimer previously * created by calling setFastTimeout. * * @param {FastTimer} timeout */ clearFastTimeout (timeout) { timeout.clear() }, /** * The now method returns the value of the internal fast timer clock. * * @returns {number} */ now () { return fastNow }, /** * Trigger the onTick function to process the fastTimers array. * Exported for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated * @param {number} [delay=0] The delay in milliseconds to add to the now value. */ tick (delay = 0) { fastNow += delay - RESOLUTION_MS + 1 onTick() onTick() }, /** * Reset FastTimers. * Exported for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated */ reset () { fastNow = 0 fastTimers.length = 0 clearTimeout(fastNowTimeout) fastNowTimeout = null }, /** * Exporting for testing purposes only. * Marking as deprecated to discourage any use outside of testing. * @deprecated */ kFastTimer } /***/ }), /***/ 9634: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kConstruct } = __nccwpck_require__(109) const { urlEquals, getFieldValues } = __nccwpck_require__(6798) const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) const { webidl } = __nccwpck_require__(5893) const { Response, cloneResponse, fromInnerResponse } = __nccwpck_require__(9051) const { Request, fromInnerRequest } = __nccwpck_require__(9967) const { kState } = __nccwpck_require__(3627) const { fetching } = __nccwpck_require__(4398) const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(3168) const assert = __nccwpck_require__(4589) /** * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation * @typedef {Object} CacheBatchOperation * @property {'delete' | 'put'} type * @property {any} request * @property {any} response * @property {import('../../types/cache').CacheQueryOptions} options */ /** * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list * @typedef {[any, any][]} requestResponseList */ class Cache { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list * @type {requestResponseList} */ #relevantRequestResponseList constructor () { if (arguments[0] !== kConstruct) { webidl.illegalConstructor() } webidl.util.markAsUncloneable(this) this.#relevantRequestResponseList = arguments[1] } async match (request, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.match' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') const p = this.#internalMatchAll(request, options, 1) if (p.length === 0) { return } return p[0] } async matchAll (request = undefined, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.matchAll' if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') return this.#internalMatchAll(request, options) } async add (request) { webidl.brandCheck(this, Cache) const prefix = 'Cache.add' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') // 1. const requests = [request] // 2. const responseArrayPromise = this.addAll(requests) // 3. return await responseArrayPromise } async addAll (requests) { webidl.brandCheck(this, Cache) const prefix = 'Cache.addAll' webidl.argumentLengthCheck(arguments, 1, prefix) // 1. const responsePromises = [] // 2. const requestList = [] // 3. for (let request of requests) { if (request === undefined) { throw webidl.errors.conversionFailed({ prefix, argument: 'Argument 1', types: ['undefined is not allowed'] }) } request = webidl.converters.RequestInfo(request) if (typeof request === 'string') { continue } // 3.1 const r = request[kState] // 3.2 if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { throw webidl.errors.exception({ header: prefix, message: 'Expected http/s scheme when method is not GET.' }) } } // 4. /** @type {ReturnType[]} */ const fetchControllers = [] // 5. for (const request of requests) { // 5.1 const r = new Request(request)[kState] // 5.2 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: prefix, message: 'Expected http/s scheme.' }) } // 5.4 r.initiator = 'fetch' r.destination = 'subresource' // 5.5 requestList.push(r) // 5.6 const responsePromise = createDeferredPromise() // 5.7 fetchControllers.push(fetching({ request: r, processResponse (response) { // 1. if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'Received an invalid status code or the request failed.' })) } else if (response.headersList.contains('vary')) { // 2. // 2.1 const fieldValues = getFieldValues(response.headersList.get('vary')) // 2.2 for (const fieldValue of fieldValues) { // 2.2.1 if (fieldValue === '*') { responsePromise.reject(webidl.errors.exception({ header: 'Cache.addAll', message: 'invalid vary field value' })) for (const controller of fetchControllers) { controller.abort() } return } } } }, processResponseEndOfBody (response) { // 1. if (response.aborted) { responsePromise.reject(new DOMException('aborted', 'AbortError')) return } // 2. responsePromise.resolve(response) } })) // 5.8 responsePromises.push(responsePromise.promise) } // 6. const p = Promise.all(responsePromises) // 7. const responses = await p // 7.1 const operations = [] // 7.2 let index = 0 // 7.3 for (const response of responses) { // 7.3.1 /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 7.3.2 request: requestList[index], // 7.3.3 response // 7.3.4 } operations.push(operation) // 7.3.5 index++ // 7.3.6 } // 7.5 const cacheJobPromise = createDeferredPromise() // 7.6.1 let errorData = null // 7.6.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 7.6.3 queueMicrotask(() => { // 7.6.3.1 if (errorData === null) { cacheJobPromise.resolve(undefined) } else { // 7.6.3.2 cacheJobPromise.reject(errorData) } }) // 7.7 return cacheJobPromise.promise } async put (request, response) { webidl.brandCheck(this, Cache) const prefix = 'Cache.put' webidl.argumentLengthCheck(arguments, 2, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') response = webidl.converters.Response(response, prefix, 'response') // 1. let innerRequest = null // 2. if (request instanceof Request) { innerRequest = request[kState] } else { // 3. innerRequest = new Request(request)[kState] } // 4. if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { throw webidl.errors.exception({ header: prefix, message: 'Expected an http/s scheme when method is not GET' }) } // 5. const innerResponse = response[kState] // 6. if (innerResponse.status === 206) { throw webidl.errors.exception({ header: prefix, message: 'Got 206 status' }) } // 7. if (innerResponse.headersList.contains('vary')) { // 7.1. const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) // 7.2. for (const fieldValue of fieldValues) { // 7.2.1 if (fieldValue === '*') { throw webidl.errors.exception({ header: prefix, message: 'Got * vary field value' }) } } } // 8. if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { throw webidl.errors.exception({ header: prefix, message: 'Response body is locked or disturbed' }) } // 9. const clonedResponse = cloneResponse(innerResponse) // 10. const bodyReadPromise = createDeferredPromise() // 11. if (innerResponse.body != null) { // 11.1 const stream = innerResponse.body.stream // 11.2 const reader = stream.getReader() // 11.3 readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) } else { bodyReadPromise.resolve(undefined) } // 12. /** @type {CacheBatchOperation[]} */ const operations = [] // 13. /** @type {CacheBatchOperation} */ const operation = { type: 'put', // 14. request: innerRequest, // 15. response: clonedResponse // 16. } // 17. operations.push(operation) // 19. const bytes = await bodyReadPromise.promise if (clonedResponse.body != null) { clonedResponse.body.source = bytes } // 19.1 const cacheJobPromise = createDeferredPromise() // 19.2.1 let errorData = null // 19.2.2 try { this.#batchCacheOperations(operations) } catch (e) { errorData = e } // 19.2.3 queueMicrotask(() => { // 19.2.3.1 if (errorData === null) { cacheJobPromise.resolve() } else { // 19.2.3.2 cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } async delete (request, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.delete' webidl.argumentLengthCheck(arguments, 1, prefix) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') /** * @type {Request} */ let r = null if (request instanceof Request) { r = request[kState] if (r.method !== 'GET' && !options.ignoreMethod) { return false } } else { assert(typeof request === 'string') r = new Request(request)[kState] } /** @type {CacheBatchOperation[]} */ const operations = [] /** @type {CacheBatchOperation} */ const operation = { type: 'delete', request: r, options } operations.push(operation) const cacheJobPromise = createDeferredPromise() let errorData = null let requestResponses try { requestResponses = this.#batchCacheOperations(operations) } catch (e) { errorData = e } queueMicrotask(() => { if (errorData === null) { cacheJobPromise.resolve(!!requestResponses?.length) } else { cacheJobPromise.reject(errorData) } }) return cacheJobPromise.promise } /** * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys * @param {any} request * @param {import('../../types/cache').CacheQueryOptions} options * @returns {Promise} */ async keys (request = undefined, options = {}) { webidl.brandCheck(this, Cache) const prefix = 'Cache.keys' if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request') options = webidl.converters.CacheQueryOptions(options, prefix, 'options') // 1. let r = null // 2. if (request !== undefined) { // 2.1 if (request instanceof Request) { // 2.1.1 r = request[kState] // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2 r = new Request(request)[kState] } } // 4. const promise = createDeferredPromise() // 5. // 5.1 const requests = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { // 5.2.1.1 requests.push(requestResponse[0]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { // 5.3.2.1 requests.push(requestResponse[0]) } } // 5.4 queueMicrotask(() => { // 5.4.1 const requestList = [] // 5.4.2 for (const request of requests) { const requestObject = fromInnerRequest( request, new AbortController().signal, 'immutable' ) // 5.4.2.1 requestList.push(requestObject) } // 5.4.3 promise.resolve(Object.freeze(requestList)) }) return promise.promise } /** * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm * @param {CacheBatchOperation[]} operations * @returns {requestResponseList} */ #batchCacheOperations (operations) { // 1. const cache = this.#relevantRequestResponseList // 2. const backupCache = [...cache] // 3. const addedItems = [] // 4.1 const resultList = [] try { // 4.2 for (const operation of operations) { // 4.2.1 if (operation.type !== 'delete' && operation.type !== 'put') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'operation type does not match "delete" or "put"' }) } // 4.2.2 if (operation.type === 'delete' && operation.response != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'delete operation should not have an associated response' }) } // 4.2.3 if (this.#queryCache(operation.request, operation.options, addedItems).length) { throw new DOMException('???', 'InvalidStateError') } // 4.2.4 let requestResponses // 4.2.5 if (operation.type === 'delete') { // 4.2.5.1 requestResponses = this.#queryCache(operation.request, operation.options) // TODO: the spec is wrong, this is needed to pass WPTs if (requestResponses.length === 0) { return [] } // 4.2.5.2 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.5.2.1 cache.splice(idx, 1) } } else if (operation.type === 'put') { // 4.2.6 // 4.2.6.1 if (operation.response == null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'put operation should have an associated response' }) } // 4.2.6.2 const r = operation.request // 4.2.6.3 if (!urlIsHttpHttpsScheme(r.url)) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'expected http or https scheme' }) } // 4.2.6.4 if (r.method !== 'GET') { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'not get method' }) } // 4.2.6.5 if (operation.options != null) { throw webidl.errors.exception({ header: 'Cache.#batchCacheOperations', message: 'options must not be defined' }) } // 4.2.6.6 requestResponses = this.#queryCache(operation.request) // 4.2.6.7 for (const requestResponse of requestResponses) { const idx = cache.indexOf(requestResponse) assert(idx !== -1) // 4.2.6.7.1 cache.splice(idx, 1) } // 4.2.6.8 cache.push([operation.request, operation.response]) // 4.2.6.10 addedItems.push([operation.request, operation.response]) } // 4.2.7 resultList.push([operation.request, operation.response]) } // 4.3 return resultList } catch (e) { // 5. // 5.1 this.#relevantRequestResponseList.length = 0 // 5.2 this.#relevantRequestResponseList = backupCache // 5.3 throw e } } /** * @see https://w3c.github.io/ServiceWorker/#query-cache * @param {any} requestQuery * @param {import('../../types/cache').CacheQueryOptions} options * @param {requestResponseList} targetStorage * @returns {requestResponseList} */ #queryCache (requestQuery, options, targetStorage) { /** @type {requestResponseList} */ const resultList = [] const storage = targetStorage ?? this.#relevantRequestResponseList for (const requestResponse of storage) { const [cachedRequest, cachedResponse] = requestResponse if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { resultList.push(requestResponse) } } return resultList } /** * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm * @param {any} requestQuery * @param {any} request * @param {any | null} response * @param {import('../../types/cache').CacheQueryOptions | undefined} options * @returns {boolean} */ #requestMatchesCachedItem (requestQuery, request, response = null, options) { // if (options?.ignoreMethod === false && request.method === 'GET') { // return false // } const queryURL = new URL(requestQuery.url) const cachedURL = new URL(request.url) if (options?.ignoreSearch) { cachedURL.search = '' queryURL.search = '' } if (!urlEquals(queryURL, cachedURL, true)) { return false } if ( response == null || options?.ignoreVary || !response.headersList.contains('vary') ) { return true } const fieldValues = getFieldValues(response.headersList.get('vary')) for (const fieldValue of fieldValues) { if (fieldValue === '*') { return false } const requestValue = request.headersList.get(fieldValue) const queryValue = requestQuery.headersList.get(fieldValue) // If one has the header and the other doesn't, or one has // a different value than the other, return false if (requestValue !== queryValue) { return false } } return true } #internalMatchAll (request, options, maxResponses = Infinity) { // 1. let r = null // 2. if (request !== undefined) { if (request instanceof Request) { // 2.1.1 r = request[kState] // 2.1.2 if (r.method !== 'GET' && !options.ignoreMethod) { return [] } } else if (typeof request === 'string') { // 2.2.1 r = new Request(request)[kState] } } // 5. // 5.1 const responses = [] // 5.2 if (request === undefined) { // 5.2.1 for (const requestResponse of this.#relevantRequestResponseList) { responses.push(requestResponse[1]) } } else { // 5.3 // 5.3.1 const requestResponses = this.#queryCache(r, options) // 5.3.2 for (const requestResponse of requestResponses) { responses.push(requestResponse[1]) } } // 5.4 // We don't implement CORs so we don't need to loop over the responses, yay! // 5.5.1 const responseList = [] // 5.5.2 for (const response of responses) { // 5.5.2.1 const responseObject = fromInnerResponse(response, 'immutable') responseList.push(responseObject.clone()) if (responseList.length >= maxResponses) { break } } // 6. return Object.freeze(responseList) } } Object.defineProperties(Cache.prototype, { [Symbol.toStringTag]: { value: 'Cache', configurable: true }, match: kEnumerableProperty, matchAll: kEnumerableProperty, add: kEnumerableProperty, addAll: kEnumerableProperty, put: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) const cacheQueryOptionConverters = [ { key: 'ignoreSearch', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'ignoreMethod', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'ignoreVary', converter: webidl.converters.boolean, defaultValue: () => false } ] webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ ...cacheQueryOptionConverters, { key: 'cacheName', converter: webidl.converters.DOMString } ]) webidl.converters.Response = webidl.interfaceConverter(Response) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.RequestInfo ) module.exports = { Cache } /***/ }), /***/ 3245: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kConstruct } = __nccwpck_require__(109) const { Cache } = __nccwpck_require__(9634) const { webidl } = __nccwpck_require__(5893) const { kEnumerableProperty } = __nccwpck_require__(3440) class CacheStorage { /** * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map * @type {Map} */ async has (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.has' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') // 2.1.1 // 2.2 return this.#caches.has(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open * @param {string} cacheName * @returns {Promise} */ async open (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.open' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') // 2.1 if (this.#caches.has(cacheName)) { // await caches.open('v1') !== await caches.open('v1') // 2.1.1 const cache = this.#caches.get(cacheName) // 2.1.1.1 return new Cache(kConstruct, cache) } // 2.2 const cache = [] // 2.3 this.#caches.set(cacheName, cache) // 2.4 return new Cache(kConstruct, cache) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete * @param {string} cacheName * @returns {Promise} */ async delete (cacheName) { webidl.brandCheck(this, CacheStorage) const prefix = 'CacheStorage.delete' webidl.argumentLengthCheck(arguments, 1, prefix) cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName') return this.#caches.delete(cacheName) } /** * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys * @returns {Promise} */ async keys () { webidl.brandCheck(this, CacheStorage) // 2.1 const keys = this.#caches.keys() // 2.2 return [...keys] } } Object.defineProperties(CacheStorage.prototype, { [Symbol.toStringTag]: { value: 'CacheStorage', configurable: true }, match: kEnumerableProperty, has: kEnumerableProperty, open: kEnumerableProperty, delete: kEnumerableProperty, keys: kEnumerableProperty }) module.exports = { CacheStorage } /***/ }), /***/ 109: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = { kConstruct: (__nccwpck_require__(6443).kConstruct) } /***/ }), /***/ 6798: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const { URLSerializer } = __nccwpck_require__(1900) const { isValidHeaderName } = __nccwpck_require__(3168) /** * @see https://url.spec.whatwg.org/#concept-url-equals * @param {URL} A * @param {URL} B * @param {boolean | undefined} excludeFragment * @returns {boolean} */ function urlEquals (A, B, excludeFragment = false) { const serializedA = URLSerializer(A, excludeFragment) const serializedB = URLSerializer(B, excludeFragment) return serializedA === serializedB } /** * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 * @param {string} header */ function getFieldValues (header) { assert(header !== null) const values = [] for (let value of header.split(',')) { value = value.trim() if (isValidHeaderName(value)) { values.push(value) } } return values } module.exports = { urlEquals, getFieldValues } /***/ }), /***/ 1276: /***/ ((module) => { // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size const maxAttributeValueSize = 1024 // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size const maxNameValuePairSize = 4096 module.exports = { maxAttributeValueSize, maxNameValuePairSize } /***/ }), /***/ 9061: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { parseSetCookie } = __nccwpck_require__(1978) const { stringify } = __nccwpck_require__(7797) const { webidl } = __nccwpck_require__(5893) const { Headers } = __nccwpck_require__(660) /** * @typedef {Object} Cookie * @property {string} name * @property {string} value * @property {Date|number|undefined} expires * @property {number|undefined} maxAge * @property {string|undefined} domain * @property {string|undefined} path * @property {boolean|undefined} secure * @property {boolean|undefined} httpOnly * @property {'Strict'|'Lax'|'None'} sameSite * @property {string[]} unparsed */ /** * @param {Headers} headers * @returns {Record} */ function getCookies (headers) { webidl.argumentLengthCheck(arguments, 1, 'getCookies') webidl.brandCheck(headers, Headers, { strict: false }) const cookie = headers.get('cookie') const out = {} if (!cookie) { return out } for (const piece of cookie.split(';')) { const [name, ...value] = piece.split('=') out[name.trim()] = value.join('=') } return out } /** * @param {Headers} headers * @param {string} name * @param {{ path?: string, domain?: string }|undefined} attributes * @returns {void} */ function deleteCookie (headers, name, attributes) { webidl.brandCheck(headers, Headers, { strict: false }) const prefix = 'deleteCookie' webidl.argumentLengthCheck(arguments, 2, prefix) name = webidl.converters.DOMString(name, prefix, 'name') attributes = webidl.converters.DeleteCookieAttributes(attributes) // Matches behavior of // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 setCookie(headers, { name, value: '', expires: new Date(0), ...attributes }) } /** * @param {Headers} headers * @returns {Cookie[]} */ function getSetCookies (headers) { webidl.argumentLengthCheck(arguments, 1, 'getSetCookies') webidl.brandCheck(headers, Headers, { strict: false }) const cookies = headers.getSetCookie() if (!cookies) { return [] } return cookies.map((pair) => parseSetCookie(pair)) } /** * @param {Headers} headers * @param {Cookie} cookie * @returns {void} */ function setCookie (headers, cookie) { webidl.argumentLengthCheck(arguments, 2, 'setCookie') webidl.brandCheck(headers, Headers, { strict: false }) cookie = webidl.converters.Cookie(cookie) const str = stringify(cookie) if (str) { headers.append('Set-Cookie', str) } } webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: () => null } ]) webidl.converters.Cookie = webidl.dictionaryConverter([ { converter: webidl.converters.DOMString, key: 'name' }, { converter: webidl.converters.DOMString, key: 'value' }, { converter: webidl.nullableConverter((value) => { if (typeof value === 'number') { return webidl.converters['unsigned long long'](value) } return new Date(value) }), key: 'expires', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters['long long']), key: 'maxAge', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'domain', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.DOMString), key: 'path', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'secure', defaultValue: () => null }, { converter: webidl.nullableConverter(webidl.converters.boolean), key: 'httpOnly', defaultValue: () => null }, { converter: webidl.converters.USVString, key: 'sameSite', allowedValues: ['Strict', 'Lax', 'None'] }, { converter: webidl.sequenceConverter(webidl.converters.DOMString), key: 'unparsed', defaultValue: () => new Array(0) } ]) module.exports = { getCookies, deleteCookie, getSetCookies, setCookie } /***/ }), /***/ 1978: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(1276) const { isCTLExcludingHtab } = __nccwpck_require__(7797) const { collectASequenceOfCodePointsFast } = __nccwpck_require__(1900) const assert = __nccwpck_require__(4589) /** * @description Parses the field-value attributes of a set-cookie header string. * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} header * @returns if the header is invalid, null will be returned */ function parseSetCookie (header) { // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F // character (CTL characters excluding HTAB): Abort these steps and // ignore the set-cookie-string entirely. if (isCTLExcludingHtab(header)) { return null } let nameValuePair = '' let unparsedAttributes = '' let name = '' let value = '' // 2. If the set-cookie-string contains a %x3B (";") character: if (header.includes(';')) { // 1. The name-value-pair string consists of the characters up to, // but not including, the first %x3B (";"), and the unparsed- // attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question). const position = { position: 0 } nameValuePair = collectASequenceOfCodePointsFast(';', header, position) unparsedAttributes = header.slice(position.position) } else { // Otherwise: // 1. The name-value-pair string consists of all the characters // contained in the set-cookie-string, and the unparsed- // attributes is the empty string. nameValuePair = header } // 3. If the name-value-pair string lacks a %x3D ("=") character, then // the name string is empty, and the value string is the value of // name-value-pair. if (!nameValuePair.includes('=')) { value = nameValuePair } else { // Otherwise, the name string consists of the characters up to, but // not including, the first %x3D ("=") character, and the (possibly // empty) value string consists of the characters after the first // %x3D ("=") character. const position = { position: 0 } name = collectASequenceOfCodePointsFast( '=', nameValuePair, position ) value = nameValuePair.slice(position.position + 1) } // 4. Remove any leading or trailing WSP characters from the name // string and the value string. name = name.trim() value = value.trim() // 5. If the sum of the lengths of the name string and the value string // is more than 4096 octets, abort these steps and ignore the set- // cookie-string entirely. if (name.length + value.length > maxNameValuePairSize) { return null } // 6. The cookie-name is the name string, and the cookie-value is the // value string. return { name, value, ...parseUnparsedAttributes(unparsedAttributes) } } /** * Parses the remaining attributes of a set-cookie header * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 * @param {string} unparsedAttributes * @param {[Object.]={}} cookieAttributeList */ function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { // 1. If the unparsed-attributes string is empty, skip the rest of // these steps. if (unparsedAttributes.length === 0) { return cookieAttributeList } // 2. Discard the first character of the unparsed-attributes (which // will be a %x3B (";") character). assert(unparsedAttributes[0] === ';') unparsedAttributes = unparsedAttributes.slice(1) let cookieAv = '' // 3. If the remaining unparsed-attributes contains a %x3B (";") // character: if (unparsedAttributes.includes(';')) { // 1. Consume the characters of the unparsed-attributes up to, but // not including, the first %x3B (";") character. cookieAv = collectASequenceOfCodePointsFast( ';', unparsedAttributes, { position: 0 } ) unparsedAttributes = unparsedAttributes.slice(cookieAv.length) } else { // Otherwise: // 1. Consume the remainder of the unparsed-attributes. cookieAv = unparsedAttributes unparsedAttributes = '' } // Let the cookie-av string be the characters consumed in this step. let attributeName = '' let attributeValue = '' // 4. If the cookie-av string contains a %x3D ("=") character: if (cookieAv.includes('=')) { // 1. The (possibly empty) attribute-name string consists of the // characters up to, but not including, the first %x3D ("=") // character, and the (possibly empty) attribute-value string // consists of the characters after the first %x3D ("=") // character. const position = { position: 0 } attributeName = collectASequenceOfCodePointsFast( '=', cookieAv, position ) attributeValue = cookieAv.slice(position.position + 1) } else { // Otherwise: // 1. The attribute-name string consists of the entire cookie-av // string, and the attribute-value string is empty. attributeName = cookieAv } // 5. Remove any leading or trailing WSP characters from the attribute- // name string and the attribute-value string. attributeName = attributeName.trim() attributeValue = attributeValue.trim() // 6. If the attribute-value is longer than 1024 octets, ignore the // cookie-av string and return to Step 1 of this algorithm. if (attributeValue.length > maxAttributeValueSize) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 7. Process the attribute-name and attribute-value according to the // requirements in the following subsections. (Notice that // attributes with unrecognized attribute-names are ignored.) const attributeNameLowercase = attributeName.toLowerCase() // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 // If the attribute-name case-insensitively matches the string // "Expires", the user agent MUST process the cookie-av as follows. if (attributeNameLowercase === 'expires') { // 1. Let the expiry-time be the result of parsing the attribute-value // as cookie-date (see Section 5.1.1). const expiryTime = new Date(attributeValue) // 2. If the attribute-value failed to parse as a cookie date, ignore // the cookie-av. cookieAttributeList.expires = expiryTime } else if (attributeNameLowercase === 'max-age') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 // If the attribute-name case-insensitively matches the string "Max- // Age", the user agent MUST process the cookie-av as follows. // 1. If the first character of the attribute-value is not a DIGIT or a // "-" character, ignore the cookie-av. const charCode = attributeValue.charCodeAt(0) if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 2. If the remainder of attribute-value contains a non-DIGIT // character, ignore the cookie-av. if (!/^\d+$/.test(attributeValue)) { return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } // 3. Let delta-seconds be the attribute-value converted to an integer. const deltaSeconds = Number(attributeValue) // 4. Let cookie-age-limit be the maximum age of the cookie (which // SHOULD be 400 days or less, see Section 4.1.2.2). // 5. Set delta-seconds to the smaller of its present value and cookie- // age-limit. // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) // 6. If delta-seconds is less than or equal to zero (0), let expiry- // time be the earliest representable date and time. Otherwise, let // the expiry-time be the current date and time plus delta-seconds // seconds. // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds // 7. Append an attribute to the cookie-attribute-list with an // attribute-name of Max-Age and an attribute-value of expiry-time. cookieAttributeList.maxAge = deltaSeconds } else if (attributeNameLowercase === 'domain') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 // If the attribute-name case-insensitively matches the string "Domain", // the user agent MUST process the cookie-av as follows. // 1. Let cookie-domain be the attribute-value. let cookieDomain = attributeValue // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be // cookie-domain without its leading %x2E ("."). if (cookieDomain[0] === '.') { cookieDomain = cookieDomain.slice(1) } // 3. Convert the cookie-domain to lower case. cookieDomain = cookieDomain.toLowerCase() // 4. Append an attribute to the cookie-attribute-list with an // attribute-name of Domain and an attribute-value of cookie-domain. cookieAttributeList.domain = cookieDomain } else if (attributeNameLowercase === 'path') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 // If the attribute-name case-insensitively matches the string "Path", // the user agent MUST process the cookie-av as follows. // 1. If the attribute-value is empty or if the first character of the // attribute-value is not %x2F ("/"): let cookiePath = '' if (attributeValue.length === 0 || attributeValue[0] !== '/') { // 1. Let cookie-path be the default-path. cookiePath = '/' } else { // Otherwise: // 1. Let cookie-path be the attribute-value. cookiePath = attributeValue } // 2. Append an attribute to the cookie-attribute-list with an // attribute-name of Path and an attribute-value of cookie-path. cookieAttributeList.path = cookiePath } else if (attributeNameLowercase === 'secure') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 // If the attribute-name case-insensitively matches the string "Secure", // the user agent MUST append an attribute to the cookie-attribute-list // with an attribute-name of Secure and an empty attribute-value. cookieAttributeList.secure = true } else if (attributeNameLowercase === 'httponly') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 // If the attribute-name case-insensitively matches the string // "HttpOnly", the user agent MUST append an attribute to the cookie- // attribute-list with an attribute-name of HttpOnly and an empty // attribute-value. cookieAttributeList.httpOnly = true } else if (attributeNameLowercase === 'samesite') { // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 // If the attribute-name case-insensitively matches the string // "SameSite", the user agent MUST process the cookie-av as follows: const attributeValueLowercase = attributeValue.toLowerCase() // 1. If cookie-av's attribute-value is a case-insensitive match for // "None", append an attribute to the cookie-attribute-list with an // attribute-name of "SameSite" and an attribute-value of "None". if (attributeValueLowercase === 'none') { cookieAttributeList.sameSite = 'None' } else if (attributeValueLowercase === 'strict') { // 2. If cookie-av's attribute-value is a case-insensitive match for // "Strict", append an attribute to the cookie-attribute-list with // an attribute-name of "SameSite" and an attribute-value of // "Strict". cookieAttributeList.sameSite = 'Strict' } else if (attributeValueLowercase === 'lax') { // 3. If cookie-av's attribute-value is a case-insensitive match for // "Lax", append an attribute to the cookie-attribute-list with an // attribute-name of "SameSite" and an attribute-value of "Lax". cookieAttributeList.sameSite = 'Lax' } } else { cookieAttributeList.unparsed ??= [] cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } // 8. Return to Step 1 of this algorithm. return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } module.exports = { parseSetCookie, parseUnparsedAttributes } /***/ }), /***/ 7797: /***/ ((module) => { /** * @param {string} value * @returns {boolean} */ function isCTLExcludingHtab (value) { for (let i = 0; i < value.length; ++i) { const code = value.charCodeAt(i) if ( (code >= 0x00 && code <= 0x08) || (code >= 0x0A && code <= 0x1F) || code === 0x7F ) { return true } } return false } /** CHAR = token = 1* separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT * @param {string} name */ function validateCookieName (name) { for (let i = 0; i < name.length; ++i) { const code = name.charCodeAt(i) if ( code < 0x21 || // exclude CTLs (0-31), SP and HT code > 0x7E || // exclude non-ascii and DEL code === 0x22 || // " code === 0x28 || // ( code === 0x29 || // ) code === 0x3C || // < code === 0x3E || // > code === 0x40 || // @ code === 0x2C || // , code === 0x3B || // ; code === 0x3A || // : code === 0x5C || // \ code === 0x2F || // / code === 0x5B || // [ code === 0x5D || // ] code === 0x3F || // ? code === 0x3D || // = code === 0x7B || // { code === 0x7D // } ) { throw new Error('Invalid cookie name') } } } /** cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E ; US-ASCII characters excluding CTLs, ; whitespace DQUOTE, comma, semicolon, ; and backslash * @param {string} value */ function validateCookieValue (value) { let len = value.length let i = 0 // if the value is wrapped in DQUOTE if (value[0] === '"') { if (len === 1 || value[len - 1] !== '"') { throw new Error('Invalid cookie value') } --len ++i } while (i < len) { const code = value.charCodeAt(i++) if ( code < 0x21 || // exclude CTLs (0-31) code > 0x7E || // non-ascii and DEL (127) code === 0x22 || // " code === 0x2C || // , code === 0x3B || // ; code === 0x5C // \ ) { throw new Error('Invalid cookie value') } } } /** * path-value = * @param {string} path */ function validateCookiePath (path) { for (let i = 0; i < path.length; ++i) { const code = path.charCodeAt(i) if ( code < 0x20 || // exclude CTLs (0-31) code === 0x7F || // DEL code === 0x3B // ; ) { throw new Error('Invalid cookie path') } } } /** * I have no idea why these values aren't allowed to be honest, * but Deno tests these. - Khafra * @param {string} domain */ function validateCookieDomain (domain) { if ( domain.startsWith('-') || domain.endsWith('.') || domain.endsWith('-') ) { throw new Error('Invalid cookie domain') } } const IMFDays = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] const IMFMonths = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] const IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0')) /** * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 * @param {number|Date} date IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT ; fixed length/zone/capitalization subset of the format ; see Section 3.3 of [RFC5322] day-name = %x4D.6F.6E ; "Mon", case-sensitive / %x54.75.65 ; "Tue", case-sensitive / %x57.65.64 ; "Wed", case-sensitive / %x54.68.75 ; "Thu", case-sensitive / %x46.72.69 ; "Fri", case-sensitive / %x53.61.74 ; "Sat", case-sensitive / %x53.75.6E ; "Sun", case-sensitive date1 = day SP month SP year ; e.g., 02 Jun 1982 day = 2DIGIT month = %x4A.61.6E ; "Jan", case-sensitive / %x46.65.62 ; "Feb", case-sensitive / %x4D.61.72 ; "Mar", case-sensitive / %x41.70.72 ; "Apr", case-sensitive / %x4D.61.79 ; "May", case-sensitive / %x4A.75.6E ; "Jun", case-sensitive / %x4A.75.6C ; "Jul", case-sensitive / %x41.75.67 ; "Aug", case-sensitive / %x53.65.70 ; "Sep", case-sensitive / %x4F.63.74 ; "Oct", case-sensitive / %x4E.6F.76 ; "Nov", case-sensitive / %x44.65.63 ; "Dec", case-sensitive year = 4DIGIT GMT = %x47.4D.54 ; "GMT", case-sensitive time-of-day = hour ":" minute ":" second ; 00:00:00 - 23:59:60 (leap second) hour = 2DIGIT minute = 2DIGIT second = 2DIGIT */ function toIMFDate (date) { if (typeof date === 'number') { date = new Date(date) } return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT` } /** max-age-av = "Max-Age=" non-zero-digit *DIGIT ; In practice, both expires-av and max-age-av ; are limited to dates representable by the ; user agent. * @param {number} maxAge */ function validateCookieMaxAge (maxAge) { if (maxAge < 0) { throw new Error('Invalid cookie max-age') } } /** * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 * @param {import('./index').Cookie} cookie */ function stringify (cookie) { if (cookie.name.length === 0) { return null } validateCookieName(cookie.name) validateCookieValue(cookie.value) const out = [`${cookie.name}=${cookie.value}`] // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 if (cookie.name.startsWith('__Secure-')) { cookie.secure = true } if (cookie.name.startsWith('__Host-')) { cookie.secure = true cookie.domain = null cookie.path = '/' } if (cookie.secure) { out.push('Secure') } if (cookie.httpOnly) { out.push('HttpOnly') } if (typeof cookie.maxAge === 'number') { validateCookieMaxAge(cookie.maxAge) out.push(`Max-Age=${cookie.maxAge}`) } if (cookie.domain) { validateCookieDomain(cookie.domain) out.push(`Domain=${cookie.domain}`) } if (cookie.path) { validateCookiePath(cookie.path) out.push(`Path=${cookie.path}`) } if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { out.push(`Expires=${toIMFDate(cookie.expires)}`) } if (cookie.sameSite) { out.push(`SameSite=${cookie.sameSite}`) } for (const part of cookie.unparsed) { if (!part.includes('=')) { throw new Error('Invalid unparsed') } const [key, ...value] = part.split('=') out.push(`${key.trim()}=${value.join('=')}`) } return out.join('; ') } module.exports = { isCTLExcludingHtab, validateCookieName, validateCookiePath, validateCookieValue, toIMFDate, stringify } /***/ }), /***/ 4031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Transform } = __nccwpck_require__(7075) const { isASCIINumber, isValidLastEventId } = __nccwpck_require__(4811) /** * @type {number[]} BOM */ const BOM = [0xEF, 0xBB, 0xBF] /** * @type {10} LF */ const LF = 0x0A /** * @type {13} CR */ const CR = 0x0D /** * @type {58} COLON */ const COLON = 0x3A /** * @type {32} SPACE */ const SPACE = 0x20 /** * @typedef {object} EventSourceStreamEvent * @type {object} * @property {string} [event] The event type. * @property {string} [data] The data of the message. * @property {string} [id] A unique ID for the event. * @property {string} [retry] The reconnection time, in milliseconds. */ /** * @typedef eventSourceSettings * @type {object} * @property {string} lastEventId The last event ID received from the server. * @property {string} origin The origin of the event source. * @property {number} reconnectionTime The reconnection time, in milliseconds. */ class EventSourceStream extends Transform { /** * @type {eventSourceSettings} */ state = null /** * Leading byte-order-mark check. * @type {boolean} */ checkBOM = true /** * @type {boolean} */ crlfCheck = false /** * @type {boolean} */ eventEndCheck = false /** * @type {Buffer} */ buffer = null pos = 0 event = { data: undefined, event: undefined, id: undefined, retry: undefined } /** * @param {object} options * @param {eventSourceSettings} options.eventSourceSettings * @param {Function} [options.push] */ constructor (options = {}) { // Enable object mode as EventSourceStream emits objects of shape // EventSourceStreamEvent options.readableObjectMode = true super(options) this.state = options.eventSourceSettings || {} if (options.push) { this.push = options.push } } /** * @param {Buffer} chunk * @param {string} _encoding * @param {Function} callback * @returns {void} */ _transform (chunk, _encoding, callback) { if (chunk.length === 0) { callback() return } // Cache the chunk in the buffer, as the data might not be complete while // processing it // TODO: Investigate if there is a more performant way to handle // incoming chunks // see: https://github.com/nodejs/undici/issues/2630 if (this.buffer) { this.buffer = Buffer.concat([this.buffer, chunk]) } else { this.buffer = chunk } // Strip leading byte-order-mark if we opened the stream and started // the processing of the incoming data if (this.checkBOM) { switch (this.buffer.length) { case 1: // Check if the first byte is the same as the first byte of the BOM if (this.buffer[0] === BOM[0]) { // If it is, we need to wait for more data callback() return } // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false // The buffer only contains one byte so we need to wait for more data callback() return case 2: // Check if the first two bytes are the same as the first two bytes // of the BOM if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] ) { // If it is, we need to wait for more data, because the third byte // is needed to determine if it is the BOM or not callback() return } // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false break case 3: // Check if the first three bytes are the same as the first three // bytes of the BOM if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2] ) { // If it is, we can drop the buffered data, as it is only the BOM this.buffer = Buffer.alloc(0) // Set the checkBOM flag to false as we don't need to check for the // BOM anymore this.checkBOM = false // Await more data callback() return } // If it is not the BOM, we can start processing the data this.checkBOM = false break default: // The buffer is longer than 3 bytes, so we can drop the BOM if it is // present if ( this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2] ) { // Remove the BOM from the buffer this.buffer = this.buffer.subarray(3) } // Set the checkBOM flag to false as we don't need to check for the this.checkBOM = false break } } while (this.pos < this.buffer.length) { // If the previous line ended with an end-of-line, we need to check // if the next character is also an end-of-line. if (this.eventEndCheck) { // If the the current character is an end-of-line, then the event // is finished and we can process it // If the previous line ended with a carriage return, we need to // check if the current character is a line feed and remove it // from the buffer. if (this.crlfCheck) { // If the current character is a line feed, we can remove it // from the buffer and reset the crlfCheck flag if (this.buffer[this.pos] === LF) { this.buffer = this.buffer.subarray(this.pos + 1) this.pos = 0 this.crlfCheck = false // It is possible that the line feed is not the end of the // event. We need to check if the next character is an // end-of-line character to determine if the event is // finished. We simply continue the loop to check the next // character. // As we removed the line feed from the buffer and set the // crlfCheck flag to false, we basically don't make any // distinction between a line feed and a carriage return. continue } this.crlfCheck = false } if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed so we can remove it from the // buffer if (this.buffer[this.pos] === CR) { this.crlfCheck = true } this.buffer = this.buffer.subarray(this.pos + 1) this.pos = 0 if ( this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) { this.processEvent(this.event) } this.clearEvent() continue } // If the current character is not an end-of-line, then the event // is not finished and we have to reset the eventEndCheck flag this.eventEndCheck = false continue } // If the current character is an end-of-line, we can process the // line if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) { // If the current character is a carriage return, we need to // set the crlfCheck flag to true, as we need to check if the // next character is a line feed if (this.buffer[this.pos] === CR) { this.crlfCheck = true } // In any case, we can process the line as we reached an // end-of-line character this.parseLine(this.buffer.subarray(0, this.pos), this.event) // Remove the processed line from the buffer this.buffer = this.buffer.subarray(this.pos + 1) // Reset the position as we removed the processed line from the buffer this.pos = 0 // A line was processed and this could be the end of the event. We need // to check if the next line is empty to determine if the event is // finished. this.eventEndCheck = true continue } this.pos++ } callback() } /** * @param {Buffer} line * @param {EventStreamEvent} event */ parseLine (line, event) { // If the line is empty (a blank line) // Dispatch the event, as defined below. // This will be handled in the _transform method if (line.length === 0) { return } // If the line starts with a U+003A COLON character (:) // Ignore the line. const colonPosition = line.indexOf(COLON) if (colonPosition === 0) { return } let field = '' let value = '' // If the line contains a U+003A COLON character (:) if (colonPosition !== -1) { // Collect the characters on the line before the first U+003A COLON // character (:), and let field be that string. // TODO: Investigate if there is a more performant way to extract the // field // see: https://github.com/nodejs/undici/issues/2630 field = line.subarray(0, colonPosition).toString('utf8') // Collect the characters on the line after the first U+003A COLON // character (:), and let value be that string. // If value starts with a U+0020 SPACE character, remove it from value. let valueStart = colonPosition + 1 if (line[valueStart] === SPACE) { ++valueStart } // TODO: Investigate if there is a more performant way to extract the // value // see: https://github.com/nodejs/undici/issues/2630 value = line.subarray(valueStart).toString('utf8') // Otherwise, the string is not empty but does not contain a U+003A COLON // character (:) } else { // Process the field using the steps described below, using the whole // line as the field name, and the empty string as the field value. field = line.toString('utf8') value = '' } // Modify the event with the field name and value. The value is also // decoded as UTF-8 switch (field) { case 'data': if (event[field] === undefined) { event[field] = value } else { event[field] += `\n${value}` } break case 'retry': if (isASCIINumber(value)) { event[field] = value } break case 'id': if (isValidLastEventId(value)) { event[field] = value } break case 'event': if (value.length > 0) { event[field] = value } break } } /** * @param {EventSourceStreamEvent} event */ processEvent (event) { if (event.retry && isASCIINumber(event.retry)) { this.state.reconnectionTime = parseInt(event.retry, 10) } if (event.id && isValidLastEventId(event.id)) { this.state.lastEventId = event.id } // only dispatch event, when data is provided if (event.data !== undefined) { this.push({ type: event.event || 'message', options: { data: event.data, lastEventId: this.state.lastEventId, origin: this.state.origin } }) } } clearEvent () { this.event = { data: undefined, event: undefined, id: undefined, retry: undefined } } } module.exports = { EventSourceStream } /***/ }), /***/ 1238: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { pipeline } = __nccwpck_require__(7075) const { fetching } = __nccwpck_require__(4398) const { makeRequest } = __nccwpck_require__(9967) const { webidl } = __nccwpck_require__(5893) const { EventSourceStream } = __nccwpck_require__(4031) const { parseMIMEType } = __nccwpck_require__(1900) const { createFastMessageEvent } = __nccwpck_require__(5188) const { isNetworkError } = __nccwpck_require__(9051) const { delay } = __nccwpck_require__(4811) const { kEnumerableProperty } = __nccwpck_require__(3440) const { environmentSettingsObject } = __nccwpck_require__(3168) let experimentalWarned = false /** * A reconnection time, in milliseconds. This must initially be an implementation-defined value, * probably in the region of a few seconds. * * In Comparison: * - Chrome uses 3000ms. * - Deno uses 5000ms. * * @type {3000} */ const defaultReconnectionTime = 3000 /** * The readyState attribute represents the state of the connection. * @enum * @readonly * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev */ /** * The connection has not yet been established, or it was closed and the user * agent is reconnecting. * @type {0} */ const CONNECTING = 0 /** * The user agent has an open connection and is dispatching events as it * receives them. * @type {1} */ const OPEN = 1 /** * The connection is not open, and the user agent is not trying to reconnect. * @type {2} */ const CLOSED = 2 /** * Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin". * @type {'anonymous'} */ const ANONYMOUS = 'anonymous' /** * Requests for the element will have their mode set to "cors" and their credentials mode set to "include". * @type {'use-credentials'} */ const USE_CREDENTIALS = 'use-credentials' /** * The EventSource interface is used to receive server-sent events. It * connects to a server over HTTP and receives events in text/event-stream * format without closing the connection. * @extends {EventTarget} * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events * @api public */ class EventSource extends EventTarget { #events = { open: null, error: null, message: null } #url = null #withCredentials = false #readyState = CONNECTING #request = null #controller = null #dispatcher /** * @type {import('./eventsource-stream').eventSourceSettings} */ #state /** * Creates a new EventSource object. * @param {string} url * @param {EventSourceInit} [eventSourceInitDict] * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface */ constructor (url, eventSourceInitDict = {}) { // 1. Let ev be a new EventSource object. super() webidl.util.markAsUncloneable(this) const prefix = 'EventSource constructor' webidl.argumentLengthCheck(arguments, 1, prefix) if (!experimentalWarned) { experimentalWarned = true process.emitWarning('EventSource is experimental, expect them to change at any time.', { code: 'UNDICI-ES' }) } url = webidl.converters.USVString(url, prefix, 'url') eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict') this.#dispatcher = eventSourceInitDict.dispatcher this.#state = { lastEventId: '', reconnectionTime: defaultReconnectionTime } // 2. Let settings be ev's relevant settings object. // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object const settings = environmentSettingsObject let urlRecord try { // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings. urlRecord = new URL(url, settings.settingsObject.baseUrl) this.#state.origin = urlRecord.origin } catch (e) { // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException. throw new DOMException(e, 'SyntaxError') } // 5. Set ev's url to urlRecord. this.#url = urlRecord.href // 6. Let corsAttributeState be Anonymous. let corsAttributeState = ANONYMOUS // 7. If the value of eventSourceInitDict's withCredentials member is true, // then set corsAttributeState to Use Credentials and set ev's // withCredentials attribute to true. if (eventSourceInitDict.withCredentials) { corsAttributeState = USE_CREDENTIALS this.#withCredentials = true } // 8. Let request be the result of creating a potential-CORS request given // urlRecord, the empty string, and corsAttributeState. const initRequest = { redirect: 'follow', keepalive: true, // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes mode: 'cors', credentials: corsAttributeState === 'anonymous' ? 'same-origin' : 'omit', referrer: 'no-referrer' } // 9. Set request's client to settings. initRequest.client = environmentSettingsObject.settingsObject // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list. initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]] // 11. Set request's cache mode to "no-store". initRequest.cache = 'no-store' // 12. Set request's initiator type to "other". initRequest.initiator = 'other' initRequest.urlList = [new URL(this.#url)] // 13. Set ev's request to request. this.#request = makeRequest(initRequest) this.#connect() } /** * Returns the state of this EventSource object's connection. It can have the * values described below. * @returns {0|1|2} * @readonly */ get readyState () { return this.#readyState } /** * Returns the URL providing the event stream. * @readonly * @returns {string} */ get url () { return this.#url } /** * Returns a boolean indicating whether the EventSource object was * instantiated with CORS credentials set (true), or not (false, the default). */ get withCredentials () { return this.#withCredentials } #connect () { if (this.#readyState === CLOSED) return this.#readyState = CONNECTING const fetchParams = { request: this.#request, dispatcher: this.#dispatcher } // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection. const processEventSourceEndOfBody = (response) => { if (isNetworkError(response)) { this.dispatchEvent(new Event('error')) this.close() } this.#reconnect() } // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody... fetchParams.processResponseEndOfBody = processEventSourceEndOfBody // and processResponse set to the following steps given response res: fetchParams.processResponse = (response) => { // 1. If res is an aborted network error, then fail the connection. if (isNetworkError(response)) { // 1. When a user agent is to fail the connection, the user agent // must queue a task which, if the readyState attribute is set to a // value other than CLOSED, sets the readyState attribute to CLOSED // and fires an event named error at the EventSource object. Once the // user agent has failed the connection, it does not attempt to // reconnect. if (response.aborted) { this.close() this.dispatchEvent(new Event('error')) return // 2. Otherwise, if res is a network error, then reestablish the // connection, unless the user agent knows that to be futile, in // which case the user agent may fail the connection. } else { this.#reconnect() return } } // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` // is not `text/event-stream`, then fail the connection. const contentType = response.headersList.get('content-type', true) const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure' const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream' if ( response.status !== 200 || contentTypeValid === false ) { this.close() this.dispatchEvent(new Event('error')) return } // 4. Otherwise, announce the connection and interpret res's body // line by line. // When a user agent is to announce the connection, the user agent // must queue a task which, if the readyState attribute is set to a // value other than CLOSED, sets the readyState attribute to OPEN // and fires an event named open at the EventSource object. // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model this.#readyState = OPEN this.dispatchEvent(new Event('open')) // If redirected to a different origin, set the origin to the new origin. this.#state.origin = response.urlList[response.urlList.length - 1].origin const eventSourceStream = new EventSourceStream({ eventSourceSettings: this.#state, push: (event) => { this.dispatchEvent(createFastMessageEvent( event.type, event.options )) } }) pipeline(response.body.stream, eventSourceStream, (error) => { if ( error?.aborted === false ) { this.close() this.dispatchEvent(new Event('error')) } }) } this.#controller = fetching(fetchParams) } /** * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model * @returns {Promise} */ async #reconnect () { // When a user agent is to reestablish the connection, the user agent must // run the following steps. These steps are run in parallel, not as part of // a task. (The tasks that it queues, of course, are run like normal tasks // and not themselves in parallel.) // 1. Queue a task to run the following steps: // 1. If the readyState attribute is set to CLOSED, abort the task. if (this.#readyState === CLOSED) return // 2. Set the readyState attribute to CONNECTING. this.#readyState = CONNECTING // 3. Fire an event named error at the EventSource object. this.dispatchEvent(new Event('error')) // 2. Wait a delay equal to the reconnection time of the event source. await delay(this.#state.reconnectionTime) // 5. Queue a task to run the following steps: // 1. If the EventSource object's readyState attribute is not set to // CONNECTING, then return. if (this.#readyState !== CONNECTING) return // 2. Let request be the EventSource object's request. // 3. If the EventSource object's last event ID string is not the empty // string, then: // 1. Let lastEventIDValue be the EventSource object's last event ID // string, encoded as UTF-8. // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header // list. if (this.#state.lastEventId.length) { this.#request.headersList.set('last-event-id', this.#state.lastEventId, true) } // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section. this.#connect() } /** * Closes the connection, if any, and sets the readyState attribute to * CLOSED. */ close () { webidl.brandCheck(this, EventSource) if (this.#readyState === CLOSED) return this.#readyState = CLOSED this.#controller.abort() this.#request = null } get onopen () { return this.#events.open } set onopen (fn) { if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onmessage () { return this.#events.message } set onmessage (fn) { if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get onerror () { return this.#events.error } set onerror (fn) { if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } } const constantsPropertyDescriptors = { CONNECTING: { __proto__: null, configurable: false, enumerable: true, value: CONNECTING, writable: false }, OPEN: { __proto__: null, configurable: false, enumerable: true, value: OPEN, writable: false }, CLOSED: { __proto__: null, configurable: false, enumerable: true, value: CLOSED, writable: false } } Object.defineProperties(EventSource, constantsPropertyDescriptors) Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors) Object.defineProperties(EventSource.prototype, { close: kEnumerableProperty, onerror: kEnumerableProperty, onmessage: kEnumerableProperty, onopen: kEnumerableProperty, readyState: kEnumerableProperty, url: kEnumerableProperty, withCredentials: kEnumerableProperty }) webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([ { key: 'withCredentials', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'dispatcher', // undici only converter: webidl.converters.any } ]) module.exports = { EventSource, defaultReconnectionTime } /***/ }), /***/ 4811: /***/ ((module) => { /** * Checks if the given value is a valid LastEventId. * @param {string} value * @returns {boolean} */ function isValidLastEventId (value) { // LastEventId should not contain U+0000 NULL return value.indexOf('\u0000') === -1 } /** * Checks if the given value is a base 10 digit. * @param {string} value * @returns {boolean} */ function isASCIINumber (value) { if (value.length === 0) return false for (let i = 0; i < value.length; i++) { if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false } return true } // https://github.com/nodejs/undici/issues/2664 function delay (ms) { return new Promise((resolve) => { setTimeout(resolve, ms).unref() }) } module.exports = { isValidLastEventId, isASCIINumber, delay } /***/ }), /***/ 4492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const util = __nccwpck_require__(3440) const { ReadableStreamFrom, isBlobLike, isReadableStreamLike, readableStreamClose, createDeferredPromise, fullyReadBody, extractMimeType, utf8DecodeBytes } = __nccwpck_require__(3168) const { FormData } = __nccwpck_require__(5910) const { kState } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) const { Blob } = __nccwpck_require__(4573) const assert = __nccwpck_require__(4589) const { isErrored, isDisturbed } = __nccwpck_require__(7075) const { isArrayBuffer } = __nccwpck_require__(3429) const { serializeAMimeType } = __nccwpck_require__(1900) const { multipartFormDataParser } = __nccwpck_require__(116) let random try { const crypto = __nccwpck_require__(7598) random = (max) => crypto.randomInt(0, max) } catch { random = (max) => Math.floor(Math.random(max)) } const textEncoder = new TextEncoder() function noop () {} const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0 let streamRegistry if (hasFinalizationRegistry) { streamRegistry = new FinalizationRegistry((weakRef) => { const stream = weakRef.deref() if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) { stream.cancel('Response object has been garbage collected').catch(noop) } }) } // https://fetch.spec.whatwg.org/#concept-bodyinit-extract function extractBody (object, keepalive = false) { // 1. Let stream be null. let stream = null // 2. If object is a ReadableStream object, then set stream to object. if (object instanceof ReadableStream) { stream = object } else if (isBlobLike(object)) { // 3. Otherwise, if object is a Blob object, set stream to the // result of running object’s get stream. stream = object.stream() } else { // 4. Otherwise, set stream to a new ReadableStream object, and set // up stream with byte reading support. stream = new ReadableStream({ async pull (controller) { const buffer = typeof source === 'string' ? textEncoder.encode(source) : source if (buffer.byteLength) { controller.enqueue(buffer) } queueMicrotask(() => readableStreamClose(controller)) }, start () {}, type: 'bytes' }) } // 5. Assert: stream is a ReadableStream object. assert(isReadableStreamLike(stream)) // 6. Let action be null. let action = null // 7. Let source be null. let source = null // 8. Let length be null. let length = null // 9. Let type be null. let type = null // 10. Switch on object: if (typeof object === 'string') { // Set source to the UTF-8 encoding of object. // Note: setting source to a Uint8Array here breaks some mocking assumptions. source = object // Set type to `text/plain;charset=UTF-8`. type = 'text/plain;charset=UTF-8' } else if (object instanceof URLSearchParams) { // URLSearchParams // spec says to run application/x-www-form-urlencoded on body.list // this is implemented in Node.js as apart of an URLSearchParams instance toString method // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. source = object.toString() // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. type = 'application/x-www-form-urlencoded;charset=UTF-8' } else if (isArrayBuffer(object)) { // BufferSource/ArrayBuffer // Set source to a copy of the bytes held by object. source = new Uint8Array(object.slice()) } else if (ArrayBuffer.isView(object)) { // BufferSource/ArrayBufferView // Set source to a copy of the bytes held by object. source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) } else if (util.isFormDataLike(object)) { const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` const prefix = `--${boundary}\r\nContent-Disposition: form-data` /*! formdata-polyfill. MIT License. Jimmy Wärting */ const escape = (str) => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') // Set action to this step: run the multipart/form-data // encoding algorithm, with object’s entry list and UTF-8. // - This ensures that the body is immutable and can't be changed afterwords // - That the content-length is calculated in advance. // - And that all parts are pre-encoded and ready to be sent. const blobParts = [] const rn = new Uint8Array([13, 10]) // '\r\n' length = 0 let hasUnknownSizeValue = false for (const [name, value] of object) { if (typeof value === 'string') { const chunk = textEncoder.encode(prefix + `; name="${escape(normalizeLinefeeds(name))}"` + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) blobParts.push(chunk) length += chunk.byteLength } else { const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + `Content-Type: ${ value.type || 'application/octet-stream' }\r\n\r\n`) blobParts.push(chunk, value, rn) if (typeof value.size === 'number') { length += chunk.byteLength + value.size + rn.byteLength } else { hasUnknownSizeValue = true } } } // CRLF is appended to the body to function with legacy servers and match other implementations. // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030 // https://github.com/form-data/form-data/issues/63 const chunk = textEncoder.encode(`--${boundary}--\r\n`) blobParts.push(chunk) length += chunk.byteLength if (hasUnknownSizeValue) { length = null } // Set source to object. source = object action = async function * () { for (const part of blobParts) { if (part.stream) { yield * part.stream() } else { yield part } } } // Set type to `multipart/form-data; boundary=`, // followed by the multipart/form-data boundary string generated // by the multipart/form-data encoding algorithm. type = `multipart/form-data; boundary=${boundary}` } else if (isBlobLike(object)) { // Blob // Set source to object. source = object // Set length to object’s size. length = object.size // If object’s type attribute is not the empty byte sequence, set // type to its value. if (object.type) { type = object.type } } else if (typeof object[Symbol.asyncIterator] === 'function') { // If keepalive is true, then throw a TypeError. if (keepalive) { throw new TypeError('keepalive') } // If object is disturbed or locked, then throw a TypeError. if (util.isDisturbed(object) || object.locked) { throw new TypeError( 'Response body object should not be disturbed or locked' ) } stream = object instanceof ReadableStream ? object : ReadableStreamFrom(object) } // 11. If source is a byte sequence, then set action to a // step that returns source and length to source’s length. if (typeof source === 'string' || util.isBuffer(source)) { length = Buffer.byteLength(source) } // 12. If action is non-null, then run these steps in in parallel: if (action != null) { // Run action. let iterator stream = new ReadableStream({ async start () { iterator = action(object)[Symbol.asyncIterator]() }, async pull (controller) { const { value, done } = await iterator.next() if (done) { // When running action is done, close stream. queueMicrotask(() => { controller.close() controller.byobRequest?.respond(0) }) } else { // Whenever one or more bytes are available and stream is not errored, // enqueue a Uint8Array wrapping an ArrayBuffer containing the available // bytes into stream. if (!isErrored(stream)) { const buffer = new Uint8Array(value) if (buffer.byteLength) { controller.enqueue(buffer) } } } return controller.desiredSize > 0 }, async cancel (reason) { await iterator.return() }, type: 'bytes' }) } // 13. Let body be a body whose stream is stream, source is source, // and length is length. const body = { stream, source, length } // 14. Return (body, type). return [body, type] } // https://fetch.spec.whatwg.org/#bodyinit-safely-extract function safelyExtractBody (object, keepalive = false) { // To safely extract a body and a `Content-Type` value from // a byte sequence or BodyInit object object, run these steps: // 1. If object is a ReadableStream object, then: if (object instanceof ReadableStream) { // Assert: object is neither disturbed nor locked. // istanbul ignore next assert(!util.isDisturbed(object), 'The body has already been consumed.') // istanbul ignore next assert(!object.locked, 'The stream is locked.') } // 2. Return the results of extracting object. return extractBody(object, keepalive) } function cloneBody (instance, body) { // To clone a body body, run these steps: // https://fetch.spec.whatwg.org/#concept-body-clone // 1. Let « out1, out2 » be the result of teeing body’s stream. const [out1, out2] = body.stream.tee() // 2. Set body’s stream to out1. body.stream = out1 // 3. Return a body whose stream is out2 and other members are copied from body. return { stream: out2, length: body.length, source: body.source } } function throwIfAborted (state) { if (state.aborted) { throw new DOMException('The operation was aborted.', 'AbortError') } } function bodyMixinMethods (instance) { const methods = { blob () { // The blob() method steps are to return the result of // running consume body with this and the following step // given a byte sequence bytes: return a Blob whose // contents are bytes and whose type attribute is this’s // MIME type. return consumeBody(this, (bytes) => { let mimeType = bodyMimeType(this) if (mimeType === null) { mimeType = '' } else if (mimeType) { mimeType = serializeAMimeType(mimeType) } // Return a Blob whose contents are bytes and type attribute // is mimeType. return new Blob([bytes], { type: mimeType }) }, instance) }, arrayBuffer () { // The arrayBuffer() method steps are to return the result // of running consume body with this and the following step // given a byte sequence bytes: return a new ArrayBuffer // whose contents are bytes. return consumeBody(this, (bytes) => { return new Uint8Array(bytes).buffer }, instance) }, text () { // The text() method steps are to return the result of running // consume body with this and UTF-8 decode. return consumeBody(this, utf8DecodeBytes, instance) }, json () { // The json() method steps are to return the result of running // consume body with this and parse JSON from bytes. return consumeBody(this, parseJSONFromBytes, instance) }, formData () { // The formData() method steps are to return the result of running // consume body with this and the following step given a byte sequence bytes: return consumeBody(this, (value) => { // 1. Let mimeType be the result of get the MIME type with this. const mimeType = bodyMimeType(this) // 2. If mimeType is non-null, then switch on mimeType’s essence and run // the corresponding steps: if (mimeType !== null) { switch (mimeType.essence) { case 'multipart/form-data': { // 1. ... [long step] const parsed = multipartFormDataParser(value, mimeType) // 2. If that fails for some reason, then throw a TypeError. if (parsed === 'failure') { throw new TypeError('Failed to parse body as FormData.') } // 3. Return a new FormData object, appending each entry, // resulting from the parsing operation, to its entry list. const fd = new FormData() fd[kState] = parsed return fd } case 'application/x-www-form-urlencoded': { // 1. Let entries be the result of parsing bytes. const entries = new URLSearchParams(value.toString()) // 2. If entries is failure, then throw a TypeError. // 3. Return a new FormData object whose entry list is entries. const fd = new FormData() for (const [name, value] of entries) { fd.append(name, value) } return fd } } } // 3. Throw a TypeError. throw new TypeError( 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".' ) }, instance) }, bytes () { // The bytes() method steps are to return the result of running consume body // with this and the following step given a byte sequence bytes: return the // result of creating a Uint8Array from bytes in this’s relevant realm. return consumeBody(this, (bytes) => { return new Uint8Array(bytes) }, instance) } } return methods } function mixinBody (prototype) { Object.assign(prototype.prototype, bodyMixinMethods(prototype)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-consume-body * @param {Response|Request} object * @param {(value: unknown) => unknown} convertBytesToJSValue * @param {Response|Request} instance */ async function consumeBody (object, convertBytesToJSValue, instance) { webidl.brandCheck(object, instance) // 1. If object is unusable, then return a promise rejected // with a TypeError. if (bodyUnusable(object)) { throw new TypeError('Body is unusable: Body has already been read') } throwIfAborted(object[kState]) // 2. Let promise be a new promise. const promise = createDeferredPromise() // 3. Let errorSteps given error be to reject promise with error. const errorSteps = (error) => promise.reject(error) // 4. Let successSteps given a byte sequence data be to resolve // promise with the result of running convertBytesToJSValue // with data. If that threw an exception, then run errorSteps // with that exception. const successSteps = (data) => { try { promise.resolve(convertBytesToJSValue(data)) } catch (e) { errorSteps(e) } } // 5. If object’s body is null, then run successSteps with an // empty byte sequence. if (object[kState].body == null) { successSteps(Buffer.allocUnsafe(0)) return promise.promise } // 6. Otherwise, fully read object’s body given successSteps, // errorSteps, and object’s relevant global object. await fullyReadBody(object[kState].body, successSteps, errorSteps) // 7. Return promise. return promise.promise } // https://fetch.spec.whatwg.org/#body-unusable function bodyUnusable (object) { const body = object[kState].body // An object including the Body interface mixin is // said to be unusable if its body is non-null and // its body’s stream is disturbed or locked. return body != null && (body.stream.locked || util.isDisturbed(body.stream)) } /** * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value * @param {Uint8Array} bytes */ function parseJSONFromBytes (bytes) { return JSON.parse(utf8DecodeBytes(bytes)) } /** * @see https://fetch.spec.whatwg.org/#concept-body-mime-type * @param {import('./response').Response|import('./request').Request} requestOrResponse */ function bodyMimeType (requestOrResponse) { // 1. Let headers be null. // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list. // 3. Otherwise, set headers to requestOrResponse’s response’s header list. /** @type {import('./headers').HeadersList} */ const headers = requestOrResponse[kState].headersList // 4. Let mimeType be the result of extracting a MIME type from headers. const mimeType = extractMimeType(headers) // 5. If mimeType is failure, then return null. if (mimeType === 'failure') { return null } // 6. Return mimeType. return mimeType } module.exports = { extractBody, safelyExtractBody, cloneBody, mixinBody, streamRegistry, hasFinalizationRegistry, bodyUnusable } /***/ }), /***/ 4495: /***/ ((module) => { const corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST']) const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) const nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304]) const redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308]) const redirectStatusSet = new Set(redirectStatus) /** * @see https://fetch.spec.whatwg.org/#block-bad-port */ const badPorts = /** @type {const} */ ([ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679', '6697', '10080' ]) const badPortsSet = new Set(badPorts) /** * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies */ const referrerPolicy = /** @type {const} */ ([ '', 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url' ]) const referrerPolicySet = new Set(referrerPolicy) const requestRedirect = /** @type {const} */ (['follow', 'manual', 'error']) const safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE']) const safeMethodsSet = new Set(safeMethods) const requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors']) const requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include']) const requestCache = /** @type {const} */ ([ 'default', 'no-store', 'reload', 'no-cache', 'force-cache', 'only-if-cached' ]) /** * @see https://fetch.spec.whatwg.org/#request-body-header-name */ const requestBodyHeader = /** @type {const} */ ([ 'content-encoding', 'content-language', 'content-location', 'content-type', // See https://github.com/nodejs/undici/issues/2021 // 'Content-Length' is a forbidden header name, which is typically // removed in the Headers implementation. However, undici doesn't // filter out headers, so we add it here. 'content-length' ]) /** * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex */ const requestDuplex = /** @type {const} */ ([ 'half' ]) /** * @see http://fetch.spec.whatwg.org/#forbidden-method */ const forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK']) const forbiddenMethodsSet = new Set(forbiddenMethods) const subresource = /** @type {const} */ ([ 'audio', 'audioworklet', 'font', 'image', 'manifest', 'paintworklet', 'script', 'style', 'track', 'video', 'xslt', '' ]) const subresourceSet = new Set(subresource) module.exports = { subresource, forbiddenMethods, requestBodyHeader, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, redirectStatus, corsSafeListedMethods, nullBodyStatus, safeMethods, badPorts, requestDuplex, subresourceSet, badPortsSet, redirectStatusSet, corsSafeListedMethodsSet, safeMethodsSet, forbiddenMethodsSet, referrerPolicySet } /***/ }), /***/ 1900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const assert = __nccwpck_require__(4589) const encoder = new TextEncoder() /** * @see https://mimesniff.spec.whatwg.org/#http-token-code-point */ const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\-.^_|~A-Za-z0-9]+$/ const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/ // eslint-disable-line const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line /** * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point */ const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/ // eslint-disable-line // https://fetch.spec.whatwg.org/#data-url-processor /** @param {URL} dataURL */ function dataURLProcessor (dataURL) { // 1. Assert: dataURL’s scheme is "data". assert(dataURL.protocol === 'data:') // 2. Let input be the result of running the URL // serializer on dataURL with exclude fragment // set to true. let input = URLSerializer(dataURL, true) // 3. Remove the leading "data:" string from input. input = input.slice(5) // 4. Let position point at the start of input. const position = { position: 0 } // 5. Let mimeType be the result of collecting a // sequence of code points that are not equal // to U+002C (,), given position. let mimeType = collectASequenceOfCodePointsFast( ',', input, position ) // 6. Strip leading and trailing ASCII whitespace // from mimeType. // Undici implementation note: we need to store the // length because if the mimetype has spaces removed, // the wrong amount will be sliced from the input in // step #9 const mimeTypeLength = mimeType.length mimeType = removeASCIIWhitespace(mimeType, true, true) // 7. If position is past the end of input, then // return failure if (position.position >= input.length) { return 'failure' } // 8. Advance position by 1. position.position++ // 9. Let encodedBody be the remainder of input. const encodedBody = input.slice(mimeTypeLength + 1) // 10. Let body be the percent-decoding of encodedBody. let body = stringPercentDecode(encodedBody) // 11. If mimeType ends with U+003B (;), followed by // zero or more U+0020 SPACE, followed by an ASCII // case-insensitive match for "base64", then: if (/;(\u0020){0,}base64$/i.test(mimeType)) { // 1. Let stringBody be the isomorphic decode of body. const stringBody = isomorphicDecode(body) // 2. Set body to the forgiving-base64 decode of // stringBody. body = forgivingBase64(stringBody) // 3. If body is failure, then return failure. if (body === 'failure') { return 'failure' } // 4. Remove the last 6 code points from mimeType. mimeType = mimeType.slice(0, -6) // 5. Remove trailing U+0020 SPACE code points from mimeType, // if any. mimeType = mimeType.replace(/(\u0020)+$/, '') // 6. Remove the last U+003B (;) code point from mimeType. mimeType = mimeType.slice(0, -1) } // 12. If mimeType starts with U+003B (;), then prepend // "text/plain" to mimeType. if (mimeType.startsWith(';')) { mimeType = 'text/plain' + mimeType } // 13. Let mimeTypeRecord be the result of parsing // mimeType. let mimeTypeRecord = parseMIMEType(mimeType) // 14. If mimeTypeRecord is failure, then set // mimeTypeRecord to text/plain;charset=US-ASCII. if (mimeTypeRecord === 'failure') { mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') } // 15. Return a new data: URL struct whose MIME // type is mimeTypeRecord and body is body. // https://fetch.spec.whatwg.org/#data-url-struct return { mimeType: mimeTypeRecord, body } } // https://url.spec.whatwg.org/#concept-url-serializer /** * @param {URL} url * @param {boolean} excludeFragment */ function URLSerializer (url, excludeFragment = false) { if (!excludeFragment) { return url.href } const href = url.href const hashLength = url.hash.length const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength) if (!hashLength && href.endsWith('#')) { return serialized.slice(0, -1) } return serialized } // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points /** * @param {(char: string) => boolean} condition * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePoints (condition, input, position) { // 1. Let result be the empty string. let result = '' // 2. While position doesn’t point past the end of input and the // code point at position within input meets the condition condition: while (position.position < input.length && condition(input[position.position])) { // 1. Append that code point to the end of result. result += input[position.position] // 2. Advance position by 1. position.position++ } // 3. Return result. return result } /** * A faster collectASequenceOfCodePoints that only works when comparing a single character. * @param {string} char * @param {string} input * @param {{ position: number }} position */ function collectASequenceOfCodePointsFast (char, input, position) { const idx = input.indexOf(char, position.position) const start = position.position if (idx === -1) { position.position = input.length return input.slice(start) } position.position = idx return input.slice(start, position.position) } // https://url.spec.whatwg.org/#string-percent-decode /** @param {string} input */ function stringPercentDecode (input) { // 1. Let bytes be the UTF-8 encoding of input. const bytes = encoder.encode(input) // 2. Return the percent-decoding of bytes. return percentDecode(bytes) } /** * @param {number} byte */ function isHexCharByte (byte) { // 0-9 A-F a-f return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66) } /** * @param {number} byte */ function hexByteToNumber (byte) { return ( // 0-9 byte >= 0x30 && byte <= 0x39 ? (byte - 48) // Convert to uppercase // ((byte & 0xDF) - 65) + 10 : ((byte & 0xDF) - 55) ) } // https://url.spec.whatwg.org/#percent-decode /** @param {Uint8Array} input */ function percentDecode (input) { const length = input.length // 1. Let output be an empty byte sequence. /** @type {Uint8Array} */ const output = new Uint8Array(length) let j = 0 // 2. For each byte byte in input: for (let i = 0; i < length; ++i) { const byte = input[i] // 1. If byte is not 0x25 (%), then append byte to output. if (byte !== 0x25) { output[j++] = byte // 2. Otherwise, if byte is 0x25 (%) and the next two bytes // after byte in input are not in the ranges // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), // and 0x61 (a) to 0x66 (f), all inclusive, append byte // to output. } else if ( byte === 0x25 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2])) ) { output[j++] = 0x25 // 3. Otherwise: } else { // 1. Let bytePoint be the two bytes after byte in input, // decoded, and then interpreted as hexadecimal number. // 2. Append a byte whose value is bytePoint to output. output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2]) // 3. Skip the next two bytes in input. i += 2 } } // 3. Return output. return length === j ? output : output.subarray(0, j) } // https://mimesniff.spec.whatwg.org/#parse-a-mime-type /** @param {string} input */ function parseMIMEType (input) { // 1. Remove any leading and trailing HTTP whitespace // from input. input = removeHTTPWhitespace(input, true, true) // 2. Let position be a position variable for input, // initially pointing at the start of input. const position = { position: 0 } // 3. Let type be the result of collecting a sequence // of code points that are not U+002F (/) from // input, given position. const type = collectASequenceOfCodePointsFast( '/', input, position ) // 4. If type is the empty string or does not solely // contain HTTP token code points, then return failure. // https://mimesniff.spec.whatwg.org/#http-token-code-point if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { return 'failure' } // 5. If position is past the end of input, then return // failure if (position.position > input.length) { return 'failure' } // 6. Advance position by 1. (This skips past U+002F (/).) position.position++ // 7. Let subtype be the result of collecting a sequence of // code points that are not U+003B (;) from input, given // position. let subtype = collectASequenceOfCodePointsFast( ';', input, position ) // 8. Remove any trailing HTTP whitespace from subtype. subtype = removeHTTPWhitespace(subtype, false, true) // 9. If subtype is the empty string or does not solely // contain HTTP token code points, then return failure. if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { return 'failure' } const typeLowercase = type.toLowerCase() const subtypeLowercase = subtype.toLowerCase() // 10. Let mimeType be a new MIME type record whose type // is type, in ASCII lowercase, and subtype is subtype, // in ASCII lowercase. // https://mimesniff.spec.whatwg.org/#mime-type const mimeType = { type: typeLowercase, subtype: subtypeLowercase, /** @type {Map} */ parameters: new Map(), // https://mimesniff.spec.whatwg.org/#mime-type-essence essence: `${typeLowercase}/${subtypeLowercase}` } // 11. While position is not past the end of input: while (position.position < input.length) { // 1. Advance position by 1. (This skips past U+003B (;).) position.position++ // 2. Collect a sequence of code points that are HTTP // whitespace from input given position. collectASequenceOfCodePoints( // https://fetch.spec.whatwg.org/#http-whitespace char => HTTP_WHITESPACE_REGEX.test(char), input, position ) // 3. Let parameterName be the result of collecting a // sequence of code points that are not U+003B (;) // or U+003D (=) from input, given position. let parameterName = collectASequenceOfCodePoints( (char) => char !== ';' && char !== '=', input, position ) // 4. Set parameterName to parameterName, in ASCII // lowercase. parameterName = parameterName.toLowerCase() // 5. If position is not past the end of input, then: if (position.position < input.length) { // 1. If the code point at position within input is // U+003B (;), then continue. if (input[position.position] === ';') { continue } // 2. Advance position by 1. (This skips past U+003D (=).) position.position++ } // 6. If position is past the end of input, then break. if (position.position > input.length) { break } // 7. Let parameterValue be null. let parameterValue = null // 8. If the code point at position within input is // U+0022 ("), then: if (input[position.position] === '"') { // 1. Set parameterValue to the result of collecting // an HTTP quoted string from input, given position // and the extract-value flag. parameterValue = collectAnHTTPQuotedString(input, position, true) // 2. Collect a sequence of code points that are not // U+003B (;) from input, given position. collectASequenceOfCodePointsFast( ';', input, position ) // 9. Otherwise: } else { // 1. Set parameterValue to the result of collecting // a sequence of code points that are not U+003B (;) // from input, given position. parameterValue = collectASequenceOfCodePointsFast( ';', input, position ) // 2. Remove any trailing HTTP whitespace from parameterValue. parameterValue = removeHTTPWhitespace(parameterValue, false, true) // 3. If parameterValue is the empty string, then continue. if (parameterValue.length === 0) { continue } } // 10. If all of the following are true // - parameterName is not the empty string // - parameterName solely contains HTTP token code points // - parameterValue solely contains HTTP quoted-string token code points // - mimeType’s parameters[parameterName] does not exist // then set mimeType’s parameters[parameterName] to parameterValue. if ( parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName) ) { mimeType.parameters.set(parameterName, parameterValue) } } // 12. Return mimeType. return mimeType } // https://infra.spec.whatwg.org/#forgiving-base64-decode /** @param {string} data */ function forgivingBase64 (data) { // 1. Remove all ASCII whitespace from data. data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line let dataLength = data.length // 2. If data’s code point length divides by 4 leaving // no remainder, then: if (dataLength % 4 === 0) { // 1. If data ends with one or two U+003D (=) code points, // then remove them from data. if (data.charCodeAt(dataLength - 1) === 0x003D) { --dataLength if (data.charCodeAt(dataLength - 1) === 0x003D) { --dataLength } } } // 3. If data’s code point length divides by 4 leaving // a remainder of 1, then return failure. if (dataLength % 4 === 1) { return 'failure' } // 4. If data contains a code point that is not one of // U+002B (+) // U+002F (/) // ASCII alphanumeric // then return failure. if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) { return 'failure' } const buffer = Buffer.from(data, 'base64') return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) } // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string /** * @param {string} input * @param {{ position: number }} position * @param {boolean?} extractValue */ function collectAnHTTPQuotedString (input, position, extractValue) { // 1. Let positionStart be position. const positionStart = position.position // 2. Let value be the empty string. let value = '' // 3. Assert: the code point at position within input // is U+0022 ("). assert(input[position.position] === '"') // 4. Advance position by 1. position.position++ // 5. While true: while (true) { // 1. Append the result of collecting a sequence of code points // that are not U+0022 (") or U+005C (\) from input, given // position, to value. value += collectASequenceOfCodePoints( (char) => char !== '"' && char !== '\\', input, position ) // 2. If position is past the end of input, then break. if (position.position >= input.length) { break } // 3. Let quoteOrBackslash be the code point at position within // input. const quoteOrBackslash = input[position.position] // 4. Advance position by 1. position.position++ // 5. If quoteOrBackslash is U+005C (\), then: if (quoteOrBackslash === '\\') { // 1. If position is past the end of input, then append // U+005C (\) to value and break. if (position.position >= input.length) { value += '\\' break } // 2. Append the code point at position within input to value. value += input[position.position] // 3. Advance position by 1. position.position++ // 6. Otherwise: } else { // 1. Assert: quoteOrBackslash is U+0022 ("). assert(quoteOrBackslash === '"') // 2. Break. break } } // 6. If the extract-value flag is set, then return value. if (extractValue) { return value } // 7. Return the code points from positionStart to position, // inclusive, within input. return input.slice(positionStart, position.position) } /** * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type */ function serializeAMimeType (mimeType) { assert(mimeType !== 'failure') const { parameters, essence } = mimeType // 1. Let serialization be the concatenation of mimeType’s // type, U+002F (/), and mimeType’s subtype. let serialization = essence // 2. For each name → value of mimeType’s parameters: for (let [name, value] of parameters.entries()) { // 1. Append U+003B (;) to serialization. serialization += ';' // 2. Append name to serialization. serialization += name // 3. Append U+003D (=) to serialization. serialization += '=' // 4. If value does not solely contain HTTP token code // points or value is the empty string, then: if (!HTTP_TOKEN_CODEPOINTS.test(value)) { // 1. Precede each occurrence of U+0022 (") or // U+005C (\) in value with U+005C (\). value = value.replace(/(\\|")/g, '\\$1') // 2. Prepend U+0022 (") to value. value = '"' + value // 3. Append U+0022 (") to value. value += '"' } // 5. Append value to serialization. serialization += value } // 3. Return serialization. return serialization } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {number} char */ function isHTTPWhiteSpace (char) { // "\r\n\t " return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020 } /** * @see https://fetch.spec.whatwg.org/#http-whitespace * @param {string} str * @param {boolean} [leading=true] * @param {boolean} [trailing=true] */ function removeHTTPWhitespace (str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isHTTPWhiteSpace) } /** * @see https://infra.spec.whatwg.org/#ascii-whitespace * @param {number} char */ function isASCIIWhitespace (char) { // "\r\n\t\f " return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020 } /** * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace * @param {string} str * @param {boolean} [leading=true] * @param {boolean} [trailing=true] */ function removeASCIIWhitespace (str, leading = true, trailing = true) { return removeChars(str, leading, trailing, isASCIIWhitespace) } /** * @param {string} str * @param {boolean} leading * @param {boolean} trailing * @param {(charCode: number) => boolean} predicate * @returns */ function removeChars (str, leading, trailing, predicate) { let lead = 0 let trail = str.length - 1 if (leading) { while (lead < str.length && predicate(str.charCodeAt(lead))) lead++ } if (trailing) { while (trail > 0 && predicate(str.charCodeAt(trail))) trail-- } return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1) } /** * @see https://infra.spec.whatwg.org/#isomorphic-decode * @param {Uint8Array} input * @returns {string} */ function isomorphicDecode (input) { // 1. To isomorphic decode a byte sequence input, return a string whose code point // length is equal to input’s length and whose code points have the same values // as the values of input’s bytes, in the same order. const length = input.length if ((2 << 15) - 1 > length) { return String.fromCharCode.apply(null, input) } let result = ''; let i = 0 let addition = (2 << 15) - 1 while (i < length) { if (i + addition > length) { addition = length - i } result += String.fromCharCode.apply(null, input.subarray(i, i += addition)) } return result } /** * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type * @param {Exclude, 'failure'>} mimeType */ function minimizeSupportedMimeType (mimeType) { switch (mimeType.essence) { case 'application/ecmascript': case 'application/javascript': case 'application/x-ecmascript': case 'application/x-javascript': case 'text/ecmascript': case 'text/javascript': case 'text/javascript1.0': case 'text/javascript1.1': case 'text/javascript1.2': case 'text/javascript1.3': case 'text/javascript1.4': case 'text/javascript1.5': case 'text/jscript': case 'text/livescript': case 'text/x-ecmascript': case 'text/x-javascript': // 1. If mimeType is a JavaScript MIME type, then return "text/javascript". return 'text/javascript' case 'application/json': case 'text/json': // 2. If mimeType is a JSON MIME type, then return "application/json". return 'application/json' case 'image/svg+xml': // 3. If mimeType’s essence is "image/svg+xml", then return "image/svg+xml". return 'image/svg+xml' case 'text/xml': case 'application/xml': // 4. If mimeType is an XML MIME type, then return "application/xml". return 'application/xml' } // 2. If mimeType is a JSON MIME type, then return "application/json". if (mimeType.subtype.endsWith('+json')) { return 'application/json' } // 4. If mimeType is an XML MIME type, then return "application/xml". if (mimeType.subtype.endsWith('+xml')) { return 'application/xml' } // 5. If mimeType is supported by the user agent, then return mimeType’s essence. // Technically, node doesn't support any mimetypes. // 6. Return the empty string. return '' } module.exports = { dataURLProcessor, URLSerializer, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, stringPercentDecode, parseMIMEType, collectAnHTTPQuotedString, serializeAMimeType, removeChars, removeHTTPWhitespace, minimizeSupportedMimeType, HTTP_TOKEN_CODEPOINTS, isomorphicDecode } /***/ }), /***/ 6653: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kConnected, kSize } = __nccwpck_require__(6443) class CompatWeakRef { constructor (value) { this.value = value } deref () { return this.value[kConnected] === 0 && this.value[kSize] === 0 ? undefined : this.value } } class CompatFinalizer { constructor (finalizer) { this.finalizer = finalizer } register (dispatcher, key) { if (dispatcher.on) { dispatcher.on('disconnect', () => { if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { this.finalizer(key) } }) } } unregister (key) {} } module.exports = function () { // FIXME: remove workaround when the Node bug is backported to v18 // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) { process._rawDebug('Using compatibility WeakRef and FinalizationRegistry') return { WeakRef: CompatWeakRef, FinalizationRegistry: CompatFinalizer } } return { WeakRef, FinalizationRegistry } } /***/ }), /***/ 7114: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Blob, File } = __nccwpck_require__(4573) const { kState } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) // TODO(@KhafraDev): remove class FileLike { constructor (blobLike, fileName, options = {}) { // TODO: argument idl type check // The File constructor is invoked with two or three parameters, depending // on whether the optional dictionary parameter is used. When the File() // constructor is invoked, user agents must run the following steps: // 1. Let bytes be the result of processing blob parts given fileBits and // options. // 2. Let n be the fileName argument to the constructor. const n = fileName // 3. Process FilePropertyBag dictionary argument by running the following // substeps: // 1. If the type member is provided and is not the empty string, let t // be set to the type dictionary member. If t contains any characters // outside the range U+0020 to U+007E, then set t to the empty string // and return from these substeps. // TODO const t = options.type // 2. Convert every character in t to ASCII lowercase. // TODO // 3. If the lastModified member is provided, let d be set to the // lastModified dictionary member. If it is not provided, set d to the // current date and time represented as the number of milliseconds since // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). const d = options.lastModified ?? Date.now() // 4. Return a new File object F such that: // F refers to the bytes byte sequence. // F.size is set to the number of total bytes in bytes. // F.name is set to n. // F.type is set to t. // F.lastModified is set to d. this[kState] = { blobLike, name: n, type: t, lastModified: d } } stream (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.stream(...args) } arrayBuffer (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.arrayBuffer(...args) } slice (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.slice(...args) } text (...args) { webidl.brandCheck(this, FileLike) return this[kState].blobLike.text(...args) } get size () { webidl.brandCheck(this, FileLike) return this[kState].blobLike.size } get type () { webidl.brandCheck(this, FileLike) return this[kState].blobLike.type } get name () { webidl.brandCheck(this, FileLike) return this[kState].name } get lastModified () { webidl.brandCheck(this, FileLike) return this[kState].lastModified } get [Symbol.toStringTag] () { return 'File' } } webidl.converters.Blob = webidl.interfaceConverter(Blob) // If this function is moved to ./util.js, some tools (such as // rollup) will warn about circular dependencies. See: // https://github.com/nodejs/undici/issues/1629 function isFileLike (object) { return ( (object instanceof File) || ( object && (typeof object.stream === 'function' || typeof object.arrayBuffer === 'function') && object[Symbol.toStringTag] === 'File' ) ) } module.exports = { FileLike, isFileLike } /***/ }), /***/ 116: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { isUSVString, bufferToLowerCasedHeaderName } = __nccwpck_require__(3440) const { utf8DecodeBytes } = __nccwpck_require__(3168) const { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = __nccwpck_require__(1900) const { isFileLike } = __nccwpck_require__(7114) const { makeEntry } = __nccwpck_require__(5910) const assert = __nccwpck_require__(4589) const { File: NodeFile } = __nccwpck_require__(4573) const File = globalThis.File ?? NodeFile const formDataNameBuffer = Buffer.from('form-data; name="') const filenameBuffer = Buffer.from('; filename') const dd = Buffer.from('--') const ddcrlf = Buffer.from('--\r\n') /** * @param {string} chars */ function isAsciiString (chars) { for (let i = 0; i < chars.length; ++i) { if ((chars.charCodeAt(i) & ~0x7F) !== 0) { return false } } return true } /** * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary * @param {string} boundary */ function validateBoundary (boundary) { const length = boundary.length // - its length is greater or equal to 27 and lesser or equal to 70, and if (length < 27 || length > 70) { return false } // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('), // 0x2D (-) or 0x5F (_). for (let i = 0; i < length; ++i) { const cp = boundary.charCodeAt(i) if (!( (cp >= 0x30 && cp <= 0x39) || (cp >= 0x41 && cp <= 0x5a) || (cp >= 0x61 && cp <= 0x7a) || cp === 0x27 || cp === 0x2d || cp === 0x5f )) { return false } } return true } /** * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser * @param {Buffer} input * @param {ReturnType} mimeType */ function multipartFormDataParser (input, mimeType) { // 1. Assert: mimeType’s essence is "multipart/form-data". assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data') const boundaryString = mimeType.parameters.get('boundary') // 2. If mimeType’s parameters["boundary"] does not exist, return failure. // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s // parameters["boundary"]. if (boundaryString === undefined) { return 'failure' } const boundary = Buffer.from(`--${boundaryString}`, 'utf8') // 3. Let entry list be an empty entry list. const entryList = [] // 4. Let position be a pointer to a byte in input, initially pointing at // the first byte. const position = { position: 0 } // Note: undici addition, allows leading and trailing CRLFs. while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { position.position += 2 } let trailing = input.length while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) { trailing -= 2 } if (trailing !== input.length) { input = input.subarray(0, trailing) } // 5. While true: while (true) { // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D // (`--`) followed by boundary, advance position by 2 + the length of // boundary. Otherwise, return failure. // Note: boundary is padded with 2 dashes already, no need to add 2. if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) { position.position += boundary.length } else { return 'failure' } // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A // (`--` followed by CR LF) followed by the end of input, return entry list. // Note: a body does NOT need to end with CRLF. It can end with --. if ( (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) || (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position)) ) { return entryList } // 5.3. If position does not point to a sequence of bytes starting with 0x0D // 0x0A (CR LF), return failure. if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { return 'failure' } // 5.4. Advance position by 2. (This skips past the newline.) position.position += 2 // 5.5. Let name, filename and contentType be the result of parsing // multipart/form-data headers on input and position, if the result // is not failure. Otherwise, return failure. const result = parseMultipartFormDataHeaders(input, position) if (result === 'failure') { return 'failure' } let { name, filename, contentType, encoding } = result // 5.6. Advance position by 2. (This skips past the empty line that marks // the end of the headers.) position.position += 2 // 5.7. Let body be the empty byte sequence. let body // 5.8. Body loop: While position is not past the end of input: // TODO: the steps here are completely wrong { const boundaryIndex = input.indexOf(boundary.subarray(2), position.position) if (boundaryIndex === -1) { return 'failure' } body = input.subarray(position.position, boundaryIndex - 4) position.position += body.length // Note: position must be advanced by the body's length before being // decoded, otherwise the parsing will fail. if (encoding === 'base64') { body = Buffer.from(body.toString(), 'base64') } } // 5.9. If position does not point to a sequence of bytes starting with // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2. if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) { return 'failure' } else { position.position += 2 } // 5.10. If filename is not null: let value if (filename !== null) { // 5.10.1. If contentType is null, set contentType to "text/plain". contentType ??= 'text/plain' // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string. // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead. // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`. if (!isAsciiString(contentType)) { contentType = '' } // 5.10.3. Let value be a new File object with name filename, type contentType, and body body. value = new File([body], filename, { type: contentType }) } else { // 5.11. Otherwise: // 5.11.1. Let value be the UTF-8 decoding without BOM of body. value = utf8DecodeBytes(Buffer.from(body)) } // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object. assert(isUSVString(name)) assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value)) // 5.13. Create an entry with name and value, and append it to entry list. entryList.push(makeEntry(name, value, filename)) } } /** * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers * @param {Buffer} input * @param {{ position: number }} position */ function parseMultipartFormDataHeaders (input, position) { // 1. Let name, filename and contentType be null. let name = null let filename = null let contentType = null let encoding = null // 2. While true: while (true) { // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF): if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) { // 2.1.1. If name is null, return failure. if (name === null) { return 'failure' } // 2.1.2. Return name, filename and contentType. return { name, filename, contentType, encoding } } // 2.2. Let header name be the result of collecting a sequence of bytes that are // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position. let headerName = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a, input, position ) // 2.3. Remove any HTTP tab or space bytes from the start or end of header name. headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20) // 2.4. If header name does not match the field-name token production, return failure. if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) { return 'failure' } // 2.5. If the byte at position is not 0x3A (:), return failure. if (input[position.position] !== 0x3a) { return 'failure' } // 2.6. Advance position by 1. position.position++ // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position. // (Do nothing with those bytes.) collectASequenceOfBytes( (char) => char === 0x20 || char === 0x09, input, position ) // 2.8. Byte-lowercase header name and switch on the result: switch (bufferToLowerCasedHeaderName(headerName)) { case 'content-disposition': { // 1. Set name and filename to null. name = filename = null // 2. If position does not point to a sequence of bytes starting with // `form-data; name="`, return failure. if (!bufferStartsWith(input, formDataNameBuffer, position)) { return 'failure' } // 3. Advance position so it points at the byte after the next 0x22 (") // byte (the one in the sequence of bytes matched above). position.position += 17 // 4. Set name to the result of parsing a multipart/form-data name given // input and position, if the result is not failure. Otherwise, return // failure. name = parseMultipartFormDataName(input, position) if (name === null) { return 'failure' } // 5. If position points to a sequence of bytes starting with `; filename="`: if (bufferStartsWith(input, filenameBuffer, position)) { // Note: undici also handles filename* let check = position.position + filenameBuffer.length if (input[check] === 0x2a) { position.position += 1 check += 1 } if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // =" return 'failure' } // 1. Advance position so it points at the byte after the next 0x22 (") byte // (the one in the sequence of bytes matched above). position.position += 12 // 2. Set filename to the result of parsing a multipart/form-data name given // input and position, if the result is not failure. Otherwise, return failure. filename = parseMultipartFormDataName(input, position) if (filename === null) { return 'failure' } } break } case 'content-type': { // 1. Let header value be the result of collecting a sequence of bytes that are // not 0x0A (LF) or 0x0D (CR), given position. let headerValue = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) // 2. Remove any HTTP tab or space bytes from the end of header value. headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) // 3. Set contentType to the isomorphic decoding of header value. contentType = isomorphicDecode(headerValue) break } case 'content-transfer-encoding': { let headerValue = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20) encoding = isomorphicDecode(headerValue) break } default: { // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position. // (Do nothing with those bytes.) collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d, input, position ) } } // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A // (CR LF), return failure. Otherwise, advance position by 2 (past the newline). if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) { return 'failure' } else { position.position += 2 } } } /** * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name * @param {Buffer} input * @param {{ position: number }} position */ function parseMultipartFormDataName (input, position) { // 1. Assert: The byte at (position - 1) is 0x22 ("). assert(input[position.position - 1] === 0x22) // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 ("), given position. /** @type {string | Buffer} */ let name = collectASequenceOfBytes( (char) => char !== 0x0a && char !== 0x0d && char !== 0x22, input, position ) // 3. If the byte at position is not 0x22 ("), return failure. Otherwise, advance position by 1. if (input[position.position] !== 0x22) { return null // name could be 'failure' } else { position.position++ } // 4. Replace any occurrence of the following subsequences in name with the given byte: // - `%0A`: 0x0A (LF) // - `%0D`: 0x0D (CR) // - `%22`: 0x22 (") name = new TextDecoder().decode(name) .replace(/%0A/ig, '\n') .replace(/%0D/ig, '\r') .replace(/%22/g, '"') // 5. Return the UTF-8 decoding without BOM of name. return name } /** * @param {(char: number) => boolean} condition * @param {Buffer} input * @param {{ position: number }} position */ function collectASequenceOfBytes (condition, input, position) { let start = position.position while (start < input.length && condition(input[start])) { ++start } return input.subarray(position.position, (position.position = start)) } /** * @param {Buffer} buf * @param {boolean} leading * @param {boolean} trailing * @param {(charCode: number) => boolean} predicate * @returns {Buffer} */ function removeChars (buf, leading, trailing, predicate) { let lead = 0 let trail = buf.length - 1 if (leading) { while (lead < buf.length && predicate(buf[lead])) lead++ } if (trailing) { while (trail > 0 && predicate(buf[trail])) trail-- } return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1) } /** * Checks if {@param buffer} starts with {@param start} * @param {Buffer} buffer * @param {Buffer} start * @param {{ position: number }} position */ function bufferStartsWith (buffer, start, position) { if (buffer.length < start.length) { return false } for (let i = 0; i < start.length; i++) { if (start[i] !== buffer[position.position + i]) { return false } } return true } module.exports = { multipartFormDataParser, validateBoundary } /***/ }), /***/ 5910: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { isBlobLike, iteratorMixin } = __nccwpck_require__(3168) const { kState } = __nccwpck_require__(3627) const { kEnumerableProperty } = __nccwpck_require__(3440) const { FileLike, isFileLike } = __nccwpck_require__(7114) const { webidl } = __nccwpck_require__(5893) const { File: NativeFile } = __nccwpck_require__(4573) const nodeUtil = __nccwpck_require__(7975) /** @type {globalThis['File']} */ const File = globalThis.File ?? NativeFile // https://xhr.spec.whatwg.org/#formdata class FormData { constructor (form) { webidl.util.markAsUncloneable(this) if (form !== undefined) { throw webidl.errors.conversionFailed({ prefix: 'FormData constructor', argument: 'Argument 1', types: ['undefined'] }) } this[kState] = [] } append (name, value, filename = undefined) { webidl.brandCheck(this, FormData) const prefix = 'FormData.append' webidl.argumentLengthCheck(arguments, 2, prefix) if (arguments.length === 3 && !isBlobLike(value)) { throw new TypeError( "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" ) } // 1. Let value be value if given; otherwise blobValue. name = webidl.converters.USVString(name, prefix, 'name') value = isBlobLike(value) ? webidl.converters.Blob(value, prefix, 'value', { strict: false }) : webidl.converters.USVString(value, prefix, 'value') filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, 'filename') : undefined // 2. Let entry be the result of creating an entry with // name, value, and filename if given. const entry = makeEntry(name, value, filename) // 3. Append entry to this’s entry list. this[kState].push(entry) } delete (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.delete' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // The delete(name) method steps are to remove all entries whose name // is name from this’s entry list. this[kState] = this[kState].filter(entry => entry.name !== name) } get (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.get' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // 1. If there is no entry whose name is name in this’s entry list, // then return null. const idx = this[kState].findIndex((entry) => entry.name === name) if (idx === -1) { return null } // 2. Return the value of the first entry whose name is name from // this’s entry list. return this[kState][idx].value } getAll (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.getAll' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // 1. If there is no entry whose name is name in this’s entry list, // then return the empty list. // 2. Return the values of all entries whose name is name, in order, // from this’s entry list. return this[kState] .filter((entry) => entry.name === name) .map((entry) => entry.value) } has (name) { webidl.brandCheck(this, FormData) const prefix = 'FormData.has' webidl.argumentLengthCheck(arguments, 1, prefix) name = webidl.converters.USVString(name, prefix, 'name') // The has(name) method steps are to return true if there is an entry // whose name is name in this’s entry list; otherwise false. return this[kState].findIndex((entry) => entry.name === name) !== -1 } set (name, value, filename = undefined) { webidl.brandCheck(this, FormData) const prefix = 'FormData.set' webidl.argumentLengthCheck(arguments, 2, prefix) if (arguments.length === 3 && !isBlobLike(value)) { throw new TypeError( "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" ) } // The set(name, value) and set(name, blobValue, filename) method steps // are: // 1. Let value be value if given; otherwise blobValue. name = webidl.converters.USVString(name, prefix, 'name') value = isBlobLike(value) ? webidl.converters.Blob(value, prefix, 'name', { strict: false }) : webidl.converters.USVString(value, prefix, 'name') filename = arguments.length === 3 ? webidl.converters.USVString(filename, prefix, 'name') : undefined // 2. Let entry be the result of creating an entry with name, value, and // filename if given. const entry = makeEntry(name, value, filename) // 3. If there are entries in this’s entry list whose name is name, then // replace the first such entry with entry and remove the others. const idx = this[kState].findIndex((entry) => entry.name === name) if (idx !== -1) { this[kState] = [ ...this[kState].slice(0, idx), entry, ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) ] } else { // 4. Otherwise, append entry to this’s entry list. this[kState].push(entry) } } [nodeUtil.inspect.custom] (depth, options) { const state = this[kState].reduce((a, b) => { if (a[b.name]) { if (Array.isArray(a[b.name])) { a[b.name].push(b.value) } else { a[b.name] = [a[b.name], b.value] } } else { a[b.name] = b.value } return a }, { __proto__: null }) options.depth ??= depth options.colors ??= true const output = nodeUtil.formatWithOptions(options, state) // remove [Object null prototype] return `FormData ${output.slice(output.indexOf(']') + 2)}` } } iteratorMixin('FormData', FormData, kState, 'name', 'value') Object.defineProperties(FormData.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, getAll: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, [Symbol.toStringTag]: { value: 'FormData', configurable: true } }) /** * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry * @param {string} name * @param {string|Blob} value * @param {?string} filename * @returns */ function makeEntry (name, value, filename) { // 1. Set name to the result of converting name into a scalar value string. // Note: This operation was done by the webidl converter USVString. // 2. If value is a string, then set value to the result of converting // value into a scalar value string. if (typeof value === 'string') { // Note: This operation was done by the webidl converter USVString. } else { // 3. Otherwise: // 1. If value is not a File object, then set value to a new File object, // representing the same bytes, whose name attribute value is "blob" if (!isFileLike(value)) { value = value instanceof Blob ? new File([value], 'blob', { type: value.type }) : new FileLike(value, 'blob', { type: value.type }) } // 2. If filename is given, then set value to a new File object, // representing the same bytes, whose name attribute is filename. if (filename !== undefined) { /** @type {FilePropertyBag} */ const options = { type: value.type, lastModified: value.lastModified } value = value instanceof NativeFile ? new File([value], filename, options) : new FileLike(value, filename, options) } } // 4. Return an entry whose name is name and whose value is value. return { name, value } } module.exports = { FormData, makeEntry } /***/ }), /***/ 1059: /***/ ((module) => { // In case of breaking changes, increase the version // number to avoid conflicts. const globalOrigin = Symbol.for('undici.globalOrigin.1') function getGlobalOrigin () { return globalThis[globalOrigin] } function setGlobalOrigin (newOrigin) { if (newOrigin === undefined) { Object.defineProperty(globalThis, globalOrigin, { value: undefined, writable: true, enumerable: false, configurable: false }) return } const parsedURL = new URL(newOrigin) if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) } Object.defineProperty(globalThis, globalOrigin, { value: parsedURL, writable: true, enumerable: false, configurable: false }) } module.exports = { getGlobalOrigin, setGlobalOrigin } /***/ }), /***/ 660: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // https://github.com/Ethan-Arrowood/undici-fetch const { kConstruct } = __nccwpck_require__(6443) const { kEnumerableProperty } = __nccwpck_require__(3440) const { iteratorMixin, isValidHeaderName, isValidHeaderValue } = __nccwpck_require__(3168) const { webidl } = __nccwpck_require__(5893) const assert = __nccwpck_require__(4589) const util = __nccwpck_require__(7975) const kHeadersMap = Symbol('headers map') const kHeadersSortedMap = Symbol('headers map sorted') /** * @param {number} code */ function isHTTPWhiteSpaceCharCode (code) { return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 } /** * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize * @param {string} potentialValue */ function headerValueNormalize (potentialValue) { // To normalize a byte sequence potentialValue, remove // any leading and trailing HTTP whitespace bytes from // potentialValue. let i = 0; let j = potentialValue.length while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) } function fill (headers, object) { // To fill a Headers object headers with a given object object, run these steps: // 1. If object is a sequence, then for each header in object: // Note: webidl conversion to array has already been done. if (Array.isArray(object)) { for (let i = 0; i < object.length; ++i) { const header = object[i] // 1. If header does not contain exactly two items, then throw a TypeError. if (header.length !== 2) { throw webidl.errors.exception({ header: 'Headers constructor', message: `expected name/value pair to be length 2, found ${header.length}.` }) } // 2. Append (header’s first item, header’s second item) to headers. appendHeader(headers, header[0], header[1]) } } else if (typeof object === 'object' && object !== null) { // Note: null should throw // 2. Otherwise, object is a record, then for each key → value in object, // append (key, value) to headers const keys = Object.keys(object) for (let i = 0; i < keys.length; ++i) { appendHeader(headers, keys[i], object[keys[i]]) } } else { throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } } /** * @see https://fetch.spec.whatwg.org/#concept-headers-append */ function appendHeader (headers, name, value) { // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.append', value, type: 'header value' }) } // 3. If headers’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if headers’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if headers’s guard is "request-no-cors": // TODO // Note: undici does not implement forbidden header names if (getHeadersGuard(headers) === 'immutable') { throw new TypeError('immutable') } // 6. Otherwise, if headers’s guard is "response" and name is a // forbidden response-header name, return. // 7. Append (name, value) to headers’s header list. return getHeadersList(headers).append(name, value, false) // 8. If headers’s guard is "request-no-cors", then remove // privileged no-CORS request headers from headers } function compareHeaderName (a, b) { return a[0] < b[0] ? -1 : 1 } class HeadersList { /** @type {[string, string][]|null} */ cookies = null constructor (init) { if (init instanceof HeadersList) { this[kHeadersMap] = new Map(init[kHeadersMap]) this[kHeadersSortedMap] = init[kHeadersSortedMap] this.cookies = init.cookies === null ? null : [...init.cookies] } else { this[kHeadersMap] = new Map(init) this[kHeadersSortedMap] = null } } /** * @see https://fetch.spec.whatwg.org/#header-list-contains * @param {string} name * @param {boolean} isLowerCase */ contains (name, isLowerCase) { // A header list list contains a header name name if list // contains a header whose name is a byte-case-insensitive // match for name. return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase()) } clear () { this[kHeadersMap].clear() this[kHeadersSortedMap] = null this.cookies = null } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-append * @param {string} name * @param {string} value * @param {boolean} isLowerCase */ append (name, value, isLowerCase) { this[kHeadersSortedMap] = null // 1. If list contains name, then set name to the first such // header’s name. const lowercaseName = isLowerCase ? name : name.toLowerCase() const exists = this[kHeadersMap].get(lowercaseName) // 2. Append (name, value) to list. if (exists) { const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' this[kHeadersMap].set(lowercaseName, { name: exists.name, value: `${exists.value}${delimiter}${value}` }) } else { this[kHeadersMap].set(lowercaseName, { name, value }) } if (lowercaseName === 'set-cookie') { (this.cookies ??= []).push(value) } } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-set * @param {string} name * @param {string} value * @param {boolean} isLowerCase */ set (name, value, isLowerCase) { this[kHeadersSortedMap] = null const lowercaseName = isLowerCase ? name : name.toLowerCase() if (lowercaseName === 'set-cookie') { this.cookies = [value] } // 1. If list contains name, then set the value of // the first such header to value and remove the // others. // 2. Otherwise, append header (name, value) to list. this[kHeadersMap].set(lowercaseName, { name, value }) } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-delete * @param {string} name * @param {boolean} isLowerCase */ delete (name, isLowerCase) { this[kHeadersSortedMap] = null if (!isLowerCase) name = name.toLowerCase() if (name === 'set-cookie') { this.cookies = null } this[kHeadersMap].delete(name) } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-get * @param {string} name * @param {boolean} isLowerCase * @returns {string | null} */ get (name, isLowerCase) { // 1. If list does not contain name, then return null. // 2. Return the values of all headers in list whose name // is a byte-case-insensitive match for name, // separated from each other by 0x2C 0x20, in order. return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null } * [Symbol.iterator] () { // use the lowercased name for (const { 0: name, 1: { value } } of this[kHeadersMap]) { yield [name, value] } } get entries () { const headers = {} if (this[kHeadersMap].size !== 0) { for (const { name, value } of this[kHeadersMap].values()) { headers[name] = value } } return headers } rawValues () { return this[kHeadersMap].values() } get entriesList () { const headers = [] if (this[kHeadersMap].size !== 0) { for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) { if (lowerName === 'set-cookie') { for (const cookie of this.cookies) { headers.push([name, cookie]) } } else { headers.push([name, value]) } } } return headers } // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set toSortedArray () { const size = this[kHeadersMap].size const array = new Array(size) // In most cases, you will use the fast-path. // fast-path: Use binary insertion sort for small arrays. if (size <= 32) { if (size === 0) { // If empty, it is an empty array. To avoid the first index assignment. return array } // Improve performance by unrolling loop and avoiding double-loop. // Double-loop-less version of the binary insertion sort. const iterator = this[kHeadersMap][Symbol.iterator]() const firstValue = iterator.next().value // set [name, value] to first index. array[0] = [firstValue[0], firstValue[1].value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(firstValue[1].value !== null) for ( let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i < size; ++i ) { // get next value value = iterator.next().value // set [name, value] to current index. x = array[i] = [value[0], value[1].value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(x[1] !== null) left = 0 right = i // binary search while (left < right) { // middle index pivot = left + ((right - left) >> 1) // compare header name if (array[pivot][0] <= x[0]) { left = pivot + 1 } else { right = pivot } } if (i !== pivot) { j = i while (j > left) { array[j] = array[--j] } array[left] = x } } /* c8 ignore next 4 */ if (!iterator.next().done) { // This is for debugging and will never be called. throw new TypeError('Unreachable') } return array } else { // This case would be a rare occurrence. // slow-path: fallback let i = 0 for (const { 0: name, 1: { value } } of this[kHeadersMap]) { array[i++] = [name, value] // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine // 3.2.2. Assert: value is non-null. assert(value !== null) } return array.sort(compareHeaderName) } } } // https://fetch.spec.whatwg.org/#headers-class class Headers { #guard #headersList constructor (init = undefined) { webidl.util.markAsUncloneable(this) if (init === kConstruct) { return } this.#headersList = new HeadersList() // The new Headers(init) constructor steps are: // 1. Set this’s guard to "none". this.#guard = 'none' // 2. If init is given, then fill this with init. if (init !== undefined) { init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init') fill(this, init) } } // https://fetch.spec.whatwg.org/#dom-headers-append append (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, 'Headers.append') const prefix = 'Headers.append' name = webidl.converters.ByteString(name, prefix, 'name') value = webidl.converters.ByteString(value, prefix, 'value') return appendHeader(this, name, value) } // https://fetch.spec.whatwg.org/#dom-headers-delete delete (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.delete') const prefix = 'Headers.delete' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix: 'Headers.delete', value: name, type: 'header name' }) } // 2. If this’s guard is "immutable", then throw a TypeError. // 3. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 4. Otherwise, if this’s guard is "request-no-cors", name // is not a no-CORS-safelisted request-header name, and // name is not a privileged no-CORS request-header name, // return. // 5. Otherwise, if this’s guard is "response" and name is // a forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this.#guard === 'immutable') { throw new TypeError('immutable') } // 6. If this’s header list does not contain name, then // return. if (!this.#headersList.contains(name, false)) { return } // 7. Delete name from this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this. this.#headersList.delete(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-get get (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.get') const prefix = 'Headers.get' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } // 2. Return the result of getting name from this’s header // list. return this.#headersList.get(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-has has (name) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 1, 'Headers.has') const prefix = 'Headers.has' name = webidl.converters.ByteString(name, prefix, 'name') // 1. If name is not a header name, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } // 2. Return true if this’s header list contains name; // otherwise false. return this.#headersList.contains(name, false) } // https://fetch.spec.whatwg.org/#dom-headers-set set (name, value) { webidl.brandCheck(this, Headers) webidl.argumentLengthCheck(arguments, 2, 'Headers.set') const prefix = 'Headers.set' name = webidl.converters.ByteString(name, prefix, 'name') value = webidl.converters.ByteString(value, prefix, 'value') // 1. Normalize value. value = headerValueNormalize(value) // 2. If name is not a header name or value is not a // header value, then throw a TypeError. if (!isValidHeaderName(name)) { throw webidl.errors.invalidArgument({ prefix, value: name, type: 'header name' }) } else if (!isValidHeaderValue(value)) { throw webidl.errors.invalidArgument({ prefix, value, type: 'header value' }) } // 3. If this’s guard is "immutable", then throw a TypeError. // 4. Otherwise, if this’s guard is "request" and name is a // forbidden header name, return. // 5. Otherwise, if this’s guard is "request-no-cors" and // name/value is not a no-CORS-safelisted request-header, // return. // 6. Otherwise, if this’s guard is "response" and name is a // forbidden response-header name, return. // Note: undici does not implement forbidden header names if (this.#guard === 'immutable') { throw new TypeError('immutable') } // 7. Set (name, value) in this’s header list. // 8. If this’s guard is "request-no-cors", then remove // privileged no-CORS request headers from this this.#headersList.set(name, value, false) } // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie getSetCookie () { webidl.brandCheck(this, Headers) // 1. If this’s header list does not contain `Set-Cookie`, then return « ». // 2. Return the values of all headers in this’s header list whose name is // a byte-case-insensitive match for `Set-Cookie`, in order. const list = this.#headersList.cookies if (list) { return [...list] } return [] } // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine get [kHeadersSortedMap] () { if (this.#headersList[kHeadersSortedMap]) { return this.#headersList[kHeadersSortedMap] } // 1. Let headers be an empty list of headers with the key being the name // and value the value. const headers = [] // 2. Let names be the result of convert header names to a sorted-lowercase // set with all the names of the headers in list. const names = this.#headersList.toSortedArray() const cookies = this.#headersList.cookies // fast-path if (cookies === null || cookies.length === 1) { // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray` return (this.#headersList[kHeadersSortedMap] = names) } // 3. For each name of names: for (let i = 0; i < names.length; ++i) { const { 0: name, 1: value } = names[i] // 1. If name is `set-cookie`, then: if (name === 'set-cookie') { // 1. Let values be a list of all values of headers in list whose name // is a byte-case-insensitive match for name, in order. // 2. For each value of values: // 1. Append (name, value) to headers. for (let j = 0; j < cookies.length; ++j) { headers.push([name, cookies[j]]) } } else { // 2. Otherwise: // 1. Let value be the result of getting name from list. // 2. Assert: value is non-null. // Note: This operation was done by `HeadersList#toSortedArray`. // 3. Append (name, value) to headers. headers.push([name, value]) } } // 4. Return headers. return (this.#headersList[kHeadersSortedMap] = headers) } [util.inspect.custom] (depth, options) { options.depth ??= depth return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}` } static getHeadersGuard (o) { return o.#guard } static setHeadersGuard (o, guard) { o.#guard = guard } static getHeadersList (o) { return o.#headersList } static setHeadersList (o, list) { o.#headersList = list } } const { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers Reflect.deleteProperty(Headers, 'getHeadersGuard') Reflect.deleteProperty(Headers, 'setHeadersGuard') Reflect.deleteProperty(Headers, 'getHeadersList') Reflect.deleteProperty(Headers, 'setHeadersList') iteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1) Object.defineProperties(Headers.prototype, { append: kEnumerableProperty, delete: kEnumerableProperty, get: kEnumerableProperty, has: kEnumerableProperty, set: kEnumerableProperty, getSetCookie: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Headers', configurable: true }, [util.inspect.custom]: { enumerable: false } }) webidl.converters.HeadersInit = function (V, prefix, argument) { if (webidl.util.Type(V) === 'Object') { const iterator = Reflect.get(V, Symbol.iterator) // A work-around to ensure we send the properly-cased Headers when V is a Headers object. // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please. if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object try { return getHeadersList(V).entriesList } catch { // fall-through } } if (typeof iterator === 'function') { return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V)) } return webidl.converters['record'](V, prefix, argument) } throw webidl.errors.conversionFailed({ prefix: 'Headers constructor', argument: 'Argument 1', types: ['sequence>', 'record'] }) } module.exports = { fill, // for test. compareHeaderName, Headers, HeadersList, getHeadersGuard, setHeadersGuard, setHeadersList, getHeadersList } /***/ }), /***/ 4398: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // https://github.com/Ethan-Arrowood/undici-fetch const { makeNetworkError, makeAppropriateNetworkError, filterResponse, makeResponse, fromInnerResponse } = __nccwpck_require__(9051) const { HeadersList } = __nccwpck_require__(660) const { Request, cloneRequest } = __nccwpck_require__(9967) const zlib = __nccwpck_require__(8522) const { bytesMatch, makePolicyContainer, clonePolicyContainer, requestBadPort, TAOCheck, appendRequestOriginHeader, responseLocationURL, requestCurrentURL, setRequestReferrerPolicyOnRedirect, tryUpgradeRequestToAPotentiallyTrustworthyURL, createOpaqueTimingInfo, appendFetchMetadata, corsCheck, crossOriginResourcePolicyCheck, determineRequestsReferrer, coarsenedSharedCurrentTime, createDeferredPromise, isBlobLike, sameOrigin, isCancelled, isAborted, isErrorLike, fullyReadBody, readableStreamClose, isomorphicEncode, urlIsLocal, urlIsHttpHttpsScheme, urlHasHttpsScheme, clampAndCoarsenConnectionTimingInfo, simpleRangeHeaderValue, buildContentRange, createInflate, extractMimeType } = __nccwpck_require__(3168) const { kState, kDispatcher } = __nccwpck_require__(3627) const assert = __nccwpck_require__(4589) const { safelyExtractBody, extractBody } = __nccwpck_require__(4492) const { redirectStatusSet, nullBodyStatus, safeMethodsSet, requestBodyHeader, subresourceSet } = __nccwpck_require__(4495) const EE = __nccwpck_require__(8474) const { Readable, pipeline, finished } = __nccwpck_require__(7075) const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = __nccwpck_require__(3440) const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = __nccwpck_require__(1900) const { getGlobalDispatcher } = __nccwpck_require__(2581) const { webidl } = __nccwpck_require__(5893) const { STATUS_CODES } = __nccwpck_require__(7067) const GET_OR_HEAD = ['GET', 'HEAD'] const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' ? 'node' : 'undici' /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL class Fetch extends EE { constructor (dispatcher) { super() this.dispatcher = dispatcher this.connection = null this.dump = false this.state = 'ongoing' } terminate (reason) { if (this.state !== 'ongoing') { return } this.state = 'terminated' this.connection?.destroy(reason) this.emit('terminated', reason) } // https://fetch.spec.whatwg.org/#fetch-controller-abort abort (error) { if (this.state !== 'ongoing') { return } // 1. Set controller’s state to "aborted". this.state = 'aborted' // 2. Let fallbackError be an "AbortError" DOMException. // 3. Set error to fallbackError if it is not given. if (!error) { error = new DOMException('The operation was aborted.', 'AbortError') } // 4. Let serializedError be StructuredSerialize(error). // If that threw an exception, catch it, and let // serializedError be StructuredSerialize(fallbackError). // 5. Set controller’s serialized abort reason to serializedError. this.serializedAbortReason = error this.connection?.destroy(error) this.emit('terminated', error) } } function handleFetchDone (response) { finalizeAndReportTiming(response, 'fetch') } // https://fetch.spec.whatwg.org/#fetch-method function fetch (input, init = undefined) { webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch') // 1. Let p be a new promise. let p = createDeferredPromise() // 2. Let requestObject be the result of invoking the initial value of // Request as constructor with input and init as arguments. If this throws // an exception, reject p with it and return p. let requestObject try { requestObject = new Request(input, init) } catch (e) { p.reject(e) return p.promise } // 3. Let request be requestObject’s request. const request = requestObject[kState] // 4. If requestObject’s signal’s aborted flag is set, then: if (requestObject.signal.aborted) { // 1. Abort the fetch() call with p, request, null, and // requestObject’s signal’s abort reason. abortFetch(p, request, null, requestObject.signal.reason) // 2. Return p. return p.promise } // 5. Let globalObject be request’s client’s global object. const globalObject = request.client.globalObject // 6. If globalObject is a ServiceWorkerGlobalScope object, then set // request’s service-workers mode to "none". if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { request.serviceWorkers = 'none' } // 7. Let responseObject be null. let responseObject = null // 8. Let relevantRealm be this’s relevant Realm. // 9. Let locallyAborted be false. let locallyAborted = false // 10. Let controller be null. let controller = null // 11. Add the following abort steps to requestObject’s signal: addAbortListener( requestObject.signal, () => { // 1. Set locallyAborted to true. locallyAborted = true // 2. Assert: controller is non-null. assert(controller != null) // 3. Abort controller with requestObject’s signal’s abort reason. controller.abort(requestObject.signal.reason) const realResponse = responseObject?.deref() // 4. Abort the fetch() call with p, request, responseObject, // and requestObject’s signal’s abort reason. abortFetch(p, request, realResponse, requestObject.signal.reason) } ) // 12. Let handleFetchDone given response response be to finalize and // report timing with response, globalObject, and "fetch". // see function handleFetchDone // 13. Set controller to the result of calling fetch given request, // with processResponseEndOfBody set to handleFetchDone, and processResponse // given response being these substeps: const processResponse = (response) => { // 1. If locallyAborted is true, terminate these substeps. if (locallyAborted) { return } // 2. If response’s aborted flag is set, then: if (response.aborted) { // 1. Let deserializedError be the result of deserialize a serialized // abort reason given controller’s serialized abort reason and // relevantRealm. // 2. Abort the fetch() call with p, request, responseObject, and // deserializedError. abortFetch(p, request, responseObject, controller.serializedAbortReason) return } // 3. If response is a network error, then reject p with a TypeError // and terminate these substeps. if (response.type === 'error') { p.reject(new TypeError('fetch failed', { cause: response.error })) return } // 4. Set responseObject to the result of creating a Response object, // given response, "immutable", and relevantRealm. responseObject = new WeakRef(fromInnerResponse(response, 'immutable')) // 5. Resolve p with responseObject. p.resolve(responseObject.deref()) p = null } controller = fetching({ request, processResponseEndOfBody: handleFetchDone, processResponse, dispatcher: requestObject[kDispatcher] // undici }) // 14. Return p. return p.promise } // https://fetch.spec.whatwg.org/#finalize-and-report-timing function finalizeAndReportTiming (response, initiatorType = 'other') { // 1. If response is an aborted network error, then return. if (response.type === 'error' && response.aborted) { return } // 2. If response’s URL list is null or empty, then return. if (!response.urlList?.length) { return } // 3. Let originalURL be response’s URL list[0]. const originalURL = response.urlList[0] // 4. Let timingInfo be response’s timing info. let timingInfo = response.timingInfo // 5. Let cacheState be response’s cache state. let cacheState = response.cacheState // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. if (!urlIsHttpHttpsScheme(originalURL)) { return } // 7. If timingInfo is null, then return. if (timingInfo === null) { return } // 8. If response’s timing allow passed flag is not set, then: if (!response.timingAllowPassed) { // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. timingInfo = createOpaqueTimingInfo({ startTime: timingInfo.startTime }) // 2. Set cacheState to the empty string. cacheState = '' } // 9. Set timingInfo’s end time to the coarsened shared current time // given global’s relevant settings object’s cross-origin isolated // capability. // TODO: given global’s relevant settings object’s cross-origin isolated // capability? timingInfo.endTime = coarsenedSharedCurrentTime() // 10. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 11. Mark resource timing for timingInfo, originalURL, initiatorType, // global, and cacheState. markResourceTiming( timingInfo, originalURL.href, initiatorType, globalThis, cacheState ) } // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing const markResourceTiming = performance.markResourceTiming // https://fetch.spec.whatwg.org/#abort-fetch function abortFetch (p, request, responseObject, error) { // 1. Reject promise with error. if (p) { // We might have already resolved the promise at this stage p.reject(error) } // 2. If request’s body is not null and is readable, then cancel request’s // body with error. if (request.body != null && isReadable(request.body?.stream)) { request.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } // 3. If responseObject is null, then return. if (responseObject == null) { return } // 4. Let response be responseObject’s response. const response = responseObject[kState] // 5. If response’s body is not null and is readable, then error response’s // body with error. if (response.body != null && isReadable(response.body?.stream)) { response.body.stream.cancel(error).catch((err) => { if (err.code === 'ERR_INVALID_STATE') { // Node bug? return } throw err }) } } // https://fetch.spec.whatwg.org/#fetching function fetching ({ request, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseEndOfBody, processResponseConsumeBody, useParallelQueue = false, dispatcher = getGlobalDispatcher() // undici }) { // Ensure that the dispatcher is set accordingly assert(dispatcher) // 1. Let taskDestination be null. let taskDestination = null // 2. Let crossOriginIsolatedCapability be false. let crossOriginIsolatedCapability = false // 3. If request’s client is non-null, then: if (request.client != null) { // 1. Set taskDestination to request’s client’s global object. taskDestination = request.client.globalObject // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin // isolated capability. crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability } // 4. If useParallelQueue is true, then set taskDestination to the result of // starting a new parallel queue. // TODO // 5. Let timingInfo be a new fetch timing info whose start time and // post-redirect start time are the coarsened shared current time given // crossOriginIsolatedCapability. const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) const timingInfo = createOpaqueTimingInfo({ startTime: currentTime }) // 6. Let fetchParams be a new fetch params whose // request is request, // timing info is timingInfo, // process request body chunk length is processRequestBodyChunkLength, // process request end-of-body is processRequestEndOfBody, // process response is processResponse, // process response consume body is processResponseConsumeBody, // process response end-of-body is processResponseEndOfBody, // task destination is taskDestination, // and cross-origin isolated capability is crossOriginIsolatedCapability. const fetchParams = { controller: new Fetch(dispatcher), request, timingInfo, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseConsumeBody, processResponseEndOfBody, taskDestination, crossOriginIsolatedCapability } // 7. If request’s body is a byte sequence, then set request’s body to // request’s body as a body. // NOTE: Since fetching is only called from fetch, body should already be // extracted. assert(!request.body || request.body.stream) // 8. If request’s window is "client", then set request’s window to request’s // client, if request’s client’s global object is a Window object; otherwise // "no-window". if (request.window === 'client') { // TODO: What if request.client is null? request.window = request.client?.globalObject?.constructor?.name === 'Window' ? request.client : 'no-window' } // 9. If request’s origin is "client", then set request’s origin to request’s // client’s origin. if (request.origin === 'client') { request.origin = request.client.origin } // 10. If all of the following conditions are true: // TODO // 11. If request’s policy container is "client", then: if (request.policyContainer === 'client') { // 1. If request’s client is non-null, then set request’s policy // container to a clone of request’s client’s policy container. [HTML] if (request.client != null) { request.policyContainer = clonePolicyContainer( request.client.policyContainer ) } else { // 2. Otherwise, set request’s policy container to a new policy // container. request.policyContainer = makePolicyContainer() } } // 12. If request’s header list does not contain `Accept`, then: if (!request.headersList.contains('accept', true)) { // 1. Let value be `*/*`. const value = '*/*' // 2. A user agent should set value to the first matching statement, if // any, switching on request’s destination: // "document" // "frame" // "iframe" // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` // "image" // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` // "style" // `text/css,*/*;q=0.1` // TODO // 3. Append `Accept`/value to request’s header list. request.headersList.append('accept', value, true) } // 13. If request’s header list does not contain `Accept-Language`, then // user agents should append `Accept-Language`/an appropriate value to // request’s header list. if (!request.headersList.contains('accept-language', true)) { request.headersList.append('accept-language', '*', true) } // 14. If request’s priority is null, then use request’s initiator and // destination appropriately in setting request’s priority to a // user-agent-defined object. if (request.priority === null) { // TODO } // 15. If request is a subresource request, then: if (subresourceSet.has(request.destination)) { // TODO } // 16. Run main fetch given fetchParams. mainFetch(fetchParams) .catch(err => { fetchParams.controller.terminate(err) }) // 17. Return fetchParam's controller return fetchParams.controller } // https://fetch.spec.whatwg.org/#concept-main-fetch async function mainFetch (fetchParams, recursive = false) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. If request’s local-URLs-only flag is set and request’s current URL is // not local, then set response to a network error. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { response = makeNetworkError('local URLs only') } // 4. Run report Content Security Policy violations for request. // TODO // 5. Upgrade request to a potentially trustworthy URL, if appropriate. tryUpgradeRequestToAPotentiallyTrustworthyURL(request) // 6. If should request be blocked due to a bad port, should fetching request // be blocked as mixed content, or should request be blocked by Content // Security Policy returns blocked, then set response to a network error. if (requestBadPort(request) === 'blocked') { response = makeNetworkError('bad port') } // TODO: should fetching request be blocked as mixed content? // TODO: should request be blocked by Content Security Policy? // 7. If request’s referrer policy is the empty string, then set request’s // referrer policy to request’s policy container’s referrer policy. if (request.referrerPolicy === '') { request.referrerPolicy = request.policyContainer.referrerPolicy } // 8. If request’s referrer is not "no-referrer", then set request’s // referrer to the result of invoking determine request’s referrer. if (request.referrer !== 'no-referrer') { request.referrer = determineRequestsReferrer(request) } // 9. Set request’s current URL’s scheme to "https" if all of the following // conditions are true: // - request’s current URL’s scheme is "http" // - request’s current URL’s host is a domain // - Matching request’s current URL’s host per Known HSTS Host Domain Name // Matching results in either a superdomain match with an asserted // includeSubDomains directive or a congruent match (with or without an // asserted includeSubDomains directive). [HSTS] // TODO // 10. If recursive is false, then run the remaining steps in parallel. // TODO // 11. If response is null, then set response to the result of running // the steps corresponding to the first matching statement: if (response === null) { response = await (async () => { const currentURL = requestCurrentURL(request) if ( // - request’s current URL’s origin is same origin with request’s origin, // and request’s response tainting is "basic" (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || // request’s current URL’s scheme is "data" (currentURL.protocol === 'data:') || // - request’s mode is "navigate" or "websocket" (request.mode === 'navigate' || request.mode === 'websocket') ) { // 1. Set request’s response tainting to "basic". request.responseTainting = 'basic' // 2. Return the result of running scheme fetch given fetchParams. return await schemeFetch(fetchParams) } // request’s mode is "same-origin" if (request.mode === 'same-origin') { // 1. Return a network error. return makeNetworkError('request mode cannot be "same-origin"') } // request’s mode is "no-cors" if (request.mode === 'no-cors') { // 1. If request’s redirect mode is not "follow", then return a network // error. if (request.redirect !== 'follow') { return makeNetworkError( 'redirect mode cannot be "follow" for "no-cors" request' ) } // 2. Set request’s response tainting to "opaque". request.responseTainting = 'opaque' // 3. Return the result of running scheme fetch given fetchParams. return await schemeFetch(fetchParams) } // request’s current URL’s scheme is not an HTTP(S) scheme if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { // Return a network error. return makeNetworkError('URL scheme must be a HTTP(S) scheme') } // - request’s use-CORS-preflight flag is set // - request’s unsafe-request flag is set and either request’s method is // not a CORS-safelisted method or CORS-unsafe request-header names with // request’s header list is not empty // 1. Set request’s response tainting to "cors". // 2. Let corsWithPreflightResponse be the result of running HTTP fetch // given fetchParams and true. // 3. If corsWithPreflightResponse is a network error, then clear cache // entries using request. // 4. Return corsWithPreflightResponse. // TODO // Otherwise // 1. Set request’s response tainting to "cors". request.responseTainting = 'cors' // 2. Return the result of running HTTP fetch given fetchParams. return await httpFetch(fetchParams) })() } // 12. If recursive is true, then return response. if (recursive) { return response } // 13. If response is not a network error and response is not a filtered // response, then: if (response.status !== 0 && !response.internalResponse) { // If request’s response tainting is "cors", then: if (request.responseTainting === 'cors') { // 1. Let headerNames be the result of extracting header list values // given `Access-Control-Expose-Headers` and response’s header list. // TODO // 2. If request’s credentials mode is not "include" and headerNames // contains `*`, then set response’s CORS-exposed header-name list to // all unique header names in response’s header list. // TODO // 3. Otherwise, if headerNames is not null or failure, then set // response’s CORS-exposed header-name list to headerNames. // TODO } // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (request.responseTainting === 'basic') { response = filterResponse(response, 'basic') } else if (request.responseTainting === 'cors') { response = filterResponse(response, 'cors') } else if (request.responseTainting === 'opaque') { response = filterResponse(response, 'opaque') } else { assert(false) } } // 14. Let internalResponse be response, if response is a network error, // and response’s internal response otherwise. let internalResponse = response.status === 0 ? response : response.internalResponse // 15. If internalResponse’s URL list is empty, then set it to a clone of // request’s URL list. if (internalResponse.urlList.length === 0) { internalResponse.urlList.push(...request.urlList) } // 16. If request’s timing allow failed flag is unset, then set // internalResponse’s timing allow passed flag. if (!request.timingAllowFailed) { response.timingAllowPassed = true } // 17. If response is not a network error and any of the following returns // blocked // - should internalResponse to request be blocked as mixed content // - should internalResponse to request be blocked by Content Security Policy // - should internalResponse to request be blocked due to its MIME type // - should internalResponse to request be blocked due to nosniff // TODO // 18. If response’s type is "opaque", internalResponse’s status is 206, // internalResponse’s range-requested flag is set, and request’s header // list does not contain `Range`, then set response and internalResponse // to a network error. if ( response.type === 'opaque' && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains('range', true) ) { response = internalResponse = makeNetworkError() } // 19. If response is not a network error and either request’s method is // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, // set internalResponse’s body to null and disregard any enqueuing toward // it (if any). if ( response.status !== 0 && (request.method === 'HEAD' || request.method === 'CONNECT' || nullBodyStatus.includes(internalResponse.status)) ) { internalResponse.body = null fetchParams.controller.dump = true } // 20. If request’s integrity metadata is not the empty string, then: if (request.integrity) { // 1. Let processBodyError be this step: run fetch finale given fetchParams // and a network error. const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason)) // 2. If request’s response tainting is "opaque", or response’s body is null, // then run processBodyError and abort these steps. if (request.responseTainting === 'opaque' || response.body == null) { processBodyError(response.error) return } // 3. Let processBody given bytes be these steps: const processBody = (bytes) => { // 1. If bytes do not match request’s integrity metadata, // then run processBodyError and abort these steps. [SRI] if (!bytesMatch(bytes, request.integrity)) { processBodyError('integrity mismatch') return } // 2. Set response’s body to bytes as a body. response.body = safelyExtractBody(bytes)[0] // 3. Run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } // 4. Fully read response’s body given processBody and processBodyError. await fullyReadBody(response.body, processBody, processBodyError) } else { // 21. Otherwise, run fetch finale given fetchParams and response. fetchFinale(fetchParams, response) } } // https://fetch.spec.whatwg.org/#concept-scheme-fetch // given a fetch params fetchParams function schemeFetch (fetchParams) { // Note: since the connection is destroyed on redirect, which sets fetchParams to a // cancelled state, we do not want this condition to trigger *unless* there have been // no redirects. See https://github.com/nodejs/undici/issues/1776 // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { return Promise.resolve(makeAppropriateNetworkError(fetchParams)) } // 2. Let request be fetchParams’s request. const { request } = fetchParams const { protocol: scheme } = requestCurrentURL(request) // 3. Switch on request’s current URL’s scheme and run the associated steps: switch (scheme) { case 'about:': { // If request’s current URL’s path is the string "blank", then return a new response // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », // and body is the empty byte sequence as a body. // Otherwise, return a network error. return Promise.resolve(makeNetworkError('about scheme is not supported')) } case 'blob:': { if (!resolveObjectURL) { resolveObjectURL = (__nccwpck_require__(4573).resolveObjectURL) } // 1. Let blobURLEntry be request’s current URL’s blob URL entry. const blobURLEntry = requestCurrentURL(request) // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 // Buffer.resolveObjectURL does not ignore URL queries. if (blobURLEntry.search.length !== 0) { return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) } const blob = resolveObjectURL(blobURLEntry.toString()) // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s // object is not a Blob object, then return a network error. if (request.method !== 'GET' || !isBlobLike(blob)) { return Promise.resolve(makeNetworkError('invalid method')) } // 3. Let blob be blobURLEntry’s object. // Note: done above // 4. Let response be a new response. const response = makeResponse() // 5. Let fullLength be blob’s size. const fullLength = blob.size // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded. const serializedFullLength = isomorphicEncode(`${fullLength}`) // 7. Let type be blob’s type. const type = blob.type // 8. If request’s header list does not contain `Range`: // 9. Otherwise: if (!request.headersList.contains('range', true)) { // 1. Let bodyWithType be the result of safely extracting blob. // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource. // In node, this can only ever be a Blob. Therefore we can safely // use extractBody directly. const bodyWithType = extractBody(blob) // 2. Set response’s status message to `OK`. response.statusText = 'OK' // 3. Set response’s body to bodyWithType’s body. response.body = bodyWithType[0] // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ». response.headersList.set('content-length', serializedFullLength, true) response.headersList.set('content-type', type, true) } else { // 1. Set response’s range-requested flag. response.rangeRequested = true // 2. Let rangeHeader be the result of getting `Range` from request’s header list. const rangeHeader = request.headersList.get('range', true) // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true. const rangeValue = simpleRangeHeaderValue(rangeHeader, true) // 4. If rangeValue is failure, then return a network error. if (rangeValue === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 5. Let (rangeStart, rangeEnd) be rangeValue. let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue // 6. If rangeStart is null: // 7. Otherwise: if (rangeStart === null) { // 1. Set rangeStart to fullLength − rangeEnd. rangeStart = fullLength - rangeEnd // 2. Set rangeEnd to rangeStart + rangeEnd − 1. rangeEnd = rangeStart + rangeEnd - 1 } else { // 1. If rangeStart is greater than or equal to fullLength, then return a network error. if (rangeStart >= fullLength) { return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.')) } // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set // rangeEnd to fullLength − 1. if (rangeEnd === null || rangeEnd >= fullLength) { rangeEnd = fullLength - 1 } } // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, // rangeEnd + 1, and type. const slicedBlob = blob.slice(rangeStart, rangeEnd, type) // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob. // Note: same reason as mentioned above as to why we use extractBody const slicedBodyWithType = extractBody(slicedBlob) // 10. Set response’s body to slicedBodyWithType’s body. response.body = slicedBodyWithType[0] // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded. const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`) // 12. Let contentRange be the result of invoking build a content range given rangeStart, // rangeEnd, and fullLength. const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength) // 13. Set response’s status to 206. response.status = 206 // 14. Set response’s status message to `Partial Content`. response.statusText = 'Partial Content' // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength), // (`Content-Type`, type), (`Content-Range`, contentRange) ». response.headersList.set('content-length', serializedSlicedLength, true) response.headersList.set('content-type', type, true) response.headersList.set('content-range', contentRange, true) } // 10. Return response. return Promise.resolve(response) } case 'data:': { // 1. Let dataURLStruct be the result of running the // data: URL processor on request’s current URL. const currentURL = requestCurrentURL(request) const dataURLStruct = dataURLProcessor(currentURL) // 2. If dataURLStruct is failure, then return a // network error. if (dataURLStruct === 'failure') { return Promise.resolve(makeNetworkError('failed to fetch the data URL')) } // 3. Let mimeType be dataURLStruct’s MIME type, serialized. const mimeType = serializeAMimeType(dataURLStruct.mimeType) // 4. Return a response whose status message is `OK`, // header list is « (`Content-Type`, mimeType) », // and body is dataURLStruct’s body as a body. return Promise.resolve(makeResponse({ statusText: 'OK', headersList: [ ['content-type', { name: 'Content-Type', value: mimeType }] ], body: safelyExtractBody(dataURLStruct.body)[0] })) } case 'file:': { // For now, unfortunate as it is, file URLs are left as an exercise for the reader. // When in doubt, return a network error. return Promise.resolve(makeNetworkError('not implemented... yet...')) } case 'http:': case 'https:': { // Return the result of running HTTP fetch given fetchParams. return httpFetch(fetchParams) .catch((err) => makeNetworkError(err)) } default: { return Promise.resolve(makeNetworkError('unknown scheme')) } } } // https://fetch.spec.whatwg.org/#finalize-response function finalizeResponse (fetchParams, response) { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2, If fetchParams’s process response done is not null, then queue a fetch // task to run fetchParams’s process response done given response, with // fetchParams’s task destination. if (fetchParams.processResponseDone != null) { queueMicrotask(() => fetchParams.processResponseDone(response)) } } // https://fetch.spec.whatwg.org/#fetch-finale function fetchFinale (fetchParams, response) { // 1. Let timingInfo be fetchParams’s timing info. let timingInfo = fetchParams.timingInfo // 2. If response is not a network error and fetchParams’s request’s client is a secure context, // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting // `Server-Timing` from response’s internal response’s header list. // TODO // 3. Let processResponseEndOfBody be the following steps: const processResponseEndOfBody = () => { // 1. Let unsafeEndTime be the unsafe shared current time. const unsafeEndTime = Date.now() // ? // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s // full timing info to fetchParams’s timing info. if (fetchParams.request.destination === 'document') { fetchParams.controller.fullTimingInfo = timingInfo } // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global: fetchParams.controller.reportTimingSteps = () => { // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return. if (fetchParams.request.url.protocol !== 'https:') { return } // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global. timingInfo.endTime = unsafeEndTime // 3. Let cacheState be response’s cache state. let cacheState = response.cacheState // 4. Let bodyInfo be response’s body info. const bodyInfo = response.bodyInfo // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an // opaque timing info for timingInfo and set cacheState to the empty string. if (!response.timingAllowPassed) { timingInfo = createOpaqueTimingInfo(timingInfo) cacheState = '' } // 6. Let responseStatus be 0. let responseStatus = 0 // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false: if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) { // 1. Set responseStatus to response’s status. responseStatus = response.status // 2. Let mimeType be the result of extracting a MIME type from response’s header list. const mimeType = extractMimeType(response.headersList) // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType. if (mimeType !== 'failure') { bodyInfo.contentType = minimizeSupportedMimeType(mimeType) } } // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo, // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo, // and responseStatus. if (fetchParams.request.initiatorType != null) { // TODO: update markresourcetiming markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus) } } // 4. Let processResponseEndOfBodyTask be the following steps: const processResponseEndOfBodyTask = () => { // 1. Set fetchParams’s request’s done flag. fetchParams.request.done = true // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process // response end-of-body given response. if (fetchParams.processResponseEndOfBody != null) { queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) } // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s // global object is fetchParams’s task destination, then run fetchParams’s controller’s report // timing steps given fetchParams’s request’s client’s global object. if (fetchParams.request.initiatorType != null) { fetchParams.controller.reportTimingSteps() } } // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination queueMicrotask(() => processResponseEndOfBodyTask()) } // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s // process response given response, with fetchParams’s task destination. if (fetchParams.processResponse != null) { queueMicrotask(() => { fetchParams.processResponse(response) fetchParams.processResponse = null }) } // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response. const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response) // 6. If internalResponse’s body is null, then run processResponseEndOfBody. // 7. Otherwise: if (internalResponse.body == null) { processResponseEndOfBody() } else { // mcollina: all the following steps of the specs are skipped. // The internal transform stream is not needed. // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541 // 1. Let transformStream be a new TransformStream. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm // set to processResponseEndOfBody. // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream. finished(internalResponse.body.stream, () => { processResponseEndOfBody() }) } } // https://fetch.spec.whatwg.org/#http-fetch async function httpFetch (fetchParams) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let actualResponse be null. let actualResponse = null // 4. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 5. If request’s service-workers mode is "all", then: if (request.serviceWorkers === 'all') { // TODO } // 6. If response is null, then: if (response === null) { // 1. If makeCORSPreflight is true and one of these conditions is true: // TODO // 2. If request’s redirect mode is "follow", then set request’s // service-workers mode to "none". if (request.redirect === 'follow') { request.serviceWorkers = 'none' } // 3. Set response and actualResponse to the result of running // HTTP-network-or-cache fetch given fetchParams. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) // 4. If request’s response tainting is "cors" and a CORS check // for request and response returns failure, then return a network error. if ( request.responseTainting === 'cors' && corsCheck(request, response) === 'failure' ) { return makeNetworkError('cors failure') } // 5. If the TAO check for request and response returns failure, then set // request’s timing allow failed flag. if (TAOCheck(request, response) === 'failure') { request.timingAllowFailed = true } } // 7. If either request’s response tainting or response’s type // is "opaque", and the cross-origin resource policy check with // request’s origin, request’s client, request’s destination, // and actualResponse returns blocked, then return a network error. if ( (request.responseTainting === 'opaque' || response.type === 'opaque') && crossOriginResourcePolicyCheck( request.origin, request.client, request.destination, actualResponse ) === 'blocked' ) { return makeNetworkError('blocked') } // 8. If actualResponse’s status is a redirect status, then: if (redirectStatusSet.has(actualResponse.status)) { // 1. If actualResponse’s status is not 303, request’s body is not null, // and the connection uses HTTP/2, then user agents may, and are even // encouraged to, transmit an RST_STREAM frame. // See, https://github.com/whatwg/fetch/issues/1288 if (request.redirect !== 'manual') { fetchParams.controller.connection.destroy(undefined, false) } // 2. Switch on request’s redirect mode: if (request.redirect === 'error') { // Set response to a network error. response = makeNetworkError('unexpected redirect') } else if (request.redirect === 'manual') { // Set response to an opaque-redirect filtered response whose internal // response is actualResponse. // NOTE(spec): On the web this would return an `opaqueredirect` response, // but that doesn't make sense server side. // See https://github.com/nodejs/undici/issues/1193. response = actualResponse } else if (request.redirect === 'follow') { // Set response to the result of running HTTP-redirect fetch given // fetchParams and response. response = await httpRedirectFetch(fetchParams, response) } else { assert(false) } } // 9. Set response’s timing info to timingInfo. response.timingInfo = timingInfo // 10. Return response. return response } // https://fetch.spec.whatwg.org/#http-redirect-fetch function httpRedirectFetch (fetchParams, response) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let actualResponse be response, if response is not a filtered response, // and response’s internal response otherwise. const actualResponse = response.internalResponse ? response.internalResponse : response // 3. Let locationURL be actualResponse’s location URL given request’s current // URL’s fragment. let locationURL try { locationURL = responseLocationURL( actualResponse, requestCurrentURL(request).hash ) // 4. If locationURL is null, then return response. if (locationURL == null) { return response } } catch (err) { // 5. If locationURL is failure, then return a network error. return Promise.resolve(makeNetworkError(err)) } // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network // error. if (!urlIsHttpHttpsScheme(locationURL)) { return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) } // 7. If request’s redirect count is 20, then return a network error. if (request.redirectCount === 20) { return Promise.resolve(makeNetworkError('redirect count exceeded')) } // 8. Increase request’s redirect count by 1. request.redirectCount += 1 // 9. If request’s mode is "cors", locationURL includes credentials, and // request’s origin is not same origin with locationURL’s origin, then return // a network error. if ( request.mode === 'cors' && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL) ) { return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) } // 10. If request’s response tainting is "cors" and locationURL includes // credentials, then return a network error. if ( request.responseTainting === 'cors' && (locationURL.username || locationURL.password) ) { return Promise.resolve(makeNetworkError( 'URL cannot contain credentials for request mode "cors"' )) } // 11. If actualResponse’s status is not 303, request’s body is non-null, // and request’s body’s source is null, then return a network error. if ( actualResponse.status !== 303 && request.body != null && request.body.source == null ) { return Promise.resolve(makeNetworkError()) } // 12. If one of the following is true // - actualResponse’s status is 301 or 302 and request’s method is `POST` // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` if ( ([301, 302].includes(actualResponse.status) && request.method === 'POST') || (actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) ) { // then: // 1. Set request’s method to `GET` and request’s body to null. request.method = 'GET' request.body = null // 2. For each headerName of request-body-header name, delete headerName from // request’s header list. for (const headerName of requestBodyHeader) { request.headersList.delete(headerName) } } // 13. If request’s current URL’s origin is not same origin with locationURL’s // origin, then for each headerName of CORS non-wildcard request-header name, // delete headerName from request’s header list. if (!sameOrigin(requestCurrentURL(request), locationURL)) { // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name request.headersList.delete('authorization', true) // https://fetch.spec.whatwg.org/#authentication-entries request.headersList.delete('proxy-authorization', true) // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. request.headersList.delete('cookie', true) request.headersList.delete('host', true) } // 14. If request’s body is non-null, then set request’s body to the first return // value of safely extracting request’s body’s source. if (request.body != null) { assert(request.body.source != null) request.body = safelyExtractBody(request.body.source)[0] } // 15. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 16. Set timingInfo’s redirect end time and post-redirect start time to the // coarsened shared current time given fetchParams’s cross-origin isolated // capability. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s // redirect start time to timingInfo’s start time. if (timingInfo.redirectStartTime === 0) { timingInfo.redirectStartTime = timingInfo.startTime } // 18. Append locationURL to request’s URL list. request.urlList.push(locationURL) // 19. Invoke set request’s referrer policy on redirect on request and // actualResponse. setRequestReferrerPolicyOnRedirect(request, actualResponse) // 20. Return the result of running main fetch given fetchParams and true. return mainFetch(fetchParams, true) } // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch async function httpNetworkOrCacheFetch ( fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false ) { // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let httpFetchParams be null. let httpFetchParams = null // 3. Let httpRequest be null. let httpRequest = null // 4. Let response be null. let response = null // 5. Let storedResponse be null. // TODO: cache // 6. Let httpCache be null. const httpCache = null // 7. Let the revalidatingFlag be unset. const revalidatingFlag = false // 8. Run these steps, but abort when the ongoing fetch is terminated: // 1. If request’s window is "no-window" and request’s redirect mode is // "error", then set httpFetchParams to fetchParams and httpRequest to // request. if (request.window === 'no-window' && request.redirect === 'error') { httpFetchParams = fetchParams httpRequest = request } else { // Otherwise: // 1. Set httpRequest to a clone of request. httpRequest = cloneRequest(request) // 2. Set httpFetchParams to a copy of fetchParams. httpFetchParams = { ...fetchParams } // 3. Set httpFetchParams’s request to httpRequest. httpFetchParams.request = httpRequest } // 3. Let includeCredentials be true if one of const includeCredentials = request.credentials === 'include' || (request.credentials === 'same-origin' && request.responseTainting === 'basic') // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s // body is non-null; otherwise null. const contentLength = httpRequest.body ? httpRequest.body.length : null // 5. Let contentLengthHeaderValue be null. let contentLengthHeaderValue = null // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or // `PUT`, then set contentLengthHeaderValue to `0`. if ( httpRequest.body == null && ['POST', 'PUT'].includes(httpRequest.method) ) { contentLengthHeaderValue = '0' } // 7. If contentLength is non-null, then set contentLengthHeaderValue to // contentLength, serialized and isomorphic encoded. if (contentLength != null) { contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) } // 8. If contentLengthHeaderValue is non-null, then append // `Content-Length`/contentLengthHeaderValue to httpRequest’s header // list. if (contentLengthHeaderValue != null) { httpRequest.headersList.append('content-length', contentLengthHeaderValue, true) } // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, // contentLengthHeaderValue) to httpRequest’s header list. // 10. If contentLength is non-null and httpRequest’s keepalive is true, // then: if (contentLength != null && httpRequest.keepalive) { // NOTE: keepalive is a noop outside of browser context. } // 11. If httpRequest’s referrer is a URL, then append // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, // to httpRequest’s header list. if (httpRequest.referrer instanceof URL) { httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true) } // 12. Append a request `Origin` header for httpRequest. appendRequestOriginHeader(httpRequest) // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] appendFetchMetadata(httpRequest) // 14. If httpRequest’s header list does not contain `User-Agent`, then // user agents should append `User-Agent`/default `User-Agent` value to // httpRequest’s header list. if (!httpRequest.headersList.contains('user-agent', true)) { httpRequest.headersList.append('user-agent', defaultUserAgent) } // 15. If httpRequest’s cache mode is "default" and httpRequest’s header // list contains `If-Modified-Since`, `If-None-Match`, // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set // httpRequest’s cache mode to "no-store". if ( httpRequest.cache === 'default' && (httpRequest.headersList.contains('if-modified-since', true) || httpRequest.headersList.contains('if-none-match', true) || httpRequest.headersList.contains('if-unmodified-since', true) || httpRequest.headersList.contains('if-match', true) || httpRequest.headersList.contains('if-range', true)) ) { httpRequest.cache = 'no-store' } // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent // no-cache cache-control header modification flag is unset, and // httpRequest’s header list does not contain `Cache-Control`, then append // `Cache-Control`/`max-age=0` to httpRequest’s header list. if ( httpRequest.cache === 'no-cache' && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains('cache-control', true) ) { httpRequest.headersList.append('cache-control', 'max-age=0', true) } // 17. If httpRequest’s cache mode is "no-store" or "reload", then: if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { // 1. If httpRequest’s header list does not contain `Pragma`, then append // `Pragma`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('pragma', true)) { httpRequest.headersList.append('pragma', 'no-cache', true) } // 2. If httpRequest’s header list does not contain `Cache-Control`, // then append `Cache-Control`/`no-cache` to httpRequest’s header list. if (!httpRequest.headersList.contains('cache-control', true)) { httpRequest.headersList.append('cache-control', 'no-cache', true) } } // 18. If httpRequest’s header list contains `Range`, then append // `Accept-Encoding`/`identity` to httpRequest’s header list. if (httpRequest.headersList.contains('range', true)) { httpRequest.headersList.append('accept-encoding', 'identity', true) } // 19. Modify httpRequest’s header list per HTTP. Do not append a given // header if httpRequest’s header list contains that header’s name. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 if (!httpRequest.headersList.contains('accept-encoding', true)) { if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true) } else { httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true) } } httpRequest.headersList.delete('host', true) // 20. If includeCredentials is true, then: if (includeCredentials) { // 1. If the user agent is not configured to block cookies for httpRequest // (see section 7 of [COOKIES]), then: // TODO: credentials // 2. If httpRequest’s header list does not contain `Authorization`, then: // TODO: credentials } // 21. If there’s a proxy-authentication entry, use it as appropriate. // TODO: proxy-authentication // 22. Set httpCache to the result of determining the HTTP cache // partition, given httpRequest. // TODO: cache // 23. If httpCache is null, then set httpRequest’s cache mode to // "no-store". if (httpCache == null) { httpRequest.cache = 'no-store' } // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", // then: if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') { // TODO: cache } // 9. If aborted, then return the appropriate network error for fetchParams. // TODO // 10. If response is null, then: if (response == null) { // 1. If httpRequest’s cache mode is "only-if-cached", then return a // network error. if (httpRequest.cache === 'only-if-cached') { return makeNetworkError('only if cached') } // 2. Let forwardResponse be the result of running HTTP-network fetch // given httpFetchParams, includeCredentials, and isNewConnectionFetch. const forwardResponse = await httpNetworkFetch( httpFetchParams, includeCredentials, isNewConnectionFetch ) // 3. If httpRequest’s method is unsafe and forwardResponse’s status is // in the range 200 to 399, inclusive, invalidate appropriate stored // responses in httpCache, as per the "Invalidation" chapter of HTTP // Caching, and set storedResponse to null. [HTTP-CACHING] if ( !safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399 ) { // TODO: cache } // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, // then: if (revalidatingFlag && forwardResponse.status === 304) { // TODO: cache } // 5. If response is null, then: if (response == null) { // 1. Set response to forwardResponse. response = forwardResponse // 2. Store httpRequest and forwardResponse in httpCache, as per the // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] // TODO: cache } } // 11. Set response’s URL list to a clone of httpRequest’s URL list. response.urlList = [...httpRequest.urlList] // 12. If httpRequest’s header list contains `Range`, then set response’s // range-requested flag. if (httpRequest.headersList.contains('range', true)) { response.rangeRequested = true } // 13. Set response’s request-includes-credentials to includeCredentials. response.requestIncludesCredentials = includeCredentials // 14. If response’s status is 401, httpRequest’s response tainting is not // "cors", includeCredentials is true, and request’s window is an environment // settings object, then: // TODO // 15. If response’s status is 407, then: if (response.status === 407) { // 1. If request’s window is "no-window", then return a network error. if (request.window === 'no-window') { return makeNetworkError() } // 2. ??? // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 4. Prompt the end user as appropriate in request’s window and store // the result as a proxy-authentication entry. [HTTP-AUTH] // TODO: Invoke some kind of callback? // 5. Set response to the result of running HTTP-network-or-cache fetch given // fetchParams. // TODO return makeNetworkError('proxy authentication required') } // 16. If all of the following are true if ( // response’s status is 421 response.status === 421 && // isNewConnectionFetch is false !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null (request.body == null || request.body.source != null) ) { // then: // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. if (isCancelled(fetchParams)) { return makeAppropriateNetworkError(fetchParams) } // 2. Set response to the result of running HTTP-network-or-cache // fetch given fetchParams, isAuthenticationFetch, and true. // TODO (spec): The spec doesn't specify this but we need to cancel // the active response before we can start a new one. // https://github.com/whatwg/fetch/issues/1293 fetchParams.controller.connection.destroy() response = await httpNetworkOrCacheFetch( fetchParams, isAuthenticationFetch, true ) } // 17. If isAuthenticationFetch is true, then create an authentication entry if (isAuthenticationFetch) { // TODO } // 18. Return response. return response } // https://fetch.spec.whatwg.org/#http-network-fetch async function httpNetworkFetch ( fetchParams, includeCredentials = false, forceNewConnection = false ) { assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) fetchParams.controller.connection = { abort: null, destroyed: false, destroy (err, abort = true) { if (!this.destroyed) { this.destroyed = true if (abort) { this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) } } } } // 1. Let request be fetchParams’s request. const request = fetchParams.request // 2. Let response be null. let response = null // 3. Let timingInfo be fetchParams’s timing info. const timingInfo = fetchParams.timingInfo // 4. Let httpCache be the result of determining the HTTP cache partition, // given request. // TODO: cache const httpCache = null // 5. If httpCache is null, then set request’s cache mode to "no-store". if (httpCache == null) { request.cache = 'no-store' } // 6. Let networkPartitionKey be the result of determining the network // partition key given request. // TODO // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise // "no". const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars // 8. Switch on request’s mode: if (request.mode === 'websocket') { // Let connection be the result of obtaining a WebSocket connection, // given request’s current URL. // TODO } else { // Let connection be the result of obtaining a connection, given // networkPartitionKey, request’s current URL’s origin, // includeCredentials, and forceNewConnection. // TODO } // 9. Run these steps, but abort when the ongoing fetch is terminated: // 1. If connection is failure, then return a network error. // 2. Set timingInfo’s final connection timing info to the result of // calling clamp and coarsen connection timing info with connection’s // timing info, timingInfo’s post-redirect start time, and fetchParams’s // cross-origin isolated capability. // 3. If connection is not an HTTP/2 connection, request’s body is non-null, // and request’s body’s source is null, then append (`Transfer-Encoding`, // `chunked`) to request’s header list. // 4. Set timingInfo’s final network-request start time to the coarsened // shared current time given fetchParams’s cross-origin isolated // capability. // 5. Set response to the result of making an HTTP request over connection // using request with the following caveats: // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] // - If request’s body is non-null, and request’s body’s source is null, // then the user agent may have a buffer of up to 64 kibibytes and store // a part of request’s body in that buffer. If the user agent reads from // request’s body beyond that buffer’s size and the user agent needs to // resend request, then instead return a network error. // - Set timingInfo’s final network-response start time to the coarsened // shared current time given fetchParams’s cross-origin isolated capability, // immediately after the user agent’s HTTP parser receives the first byte // of the response (e.g., frame header bytes for HTTP/2 or response status // line for HTTP/1.x). // - Wait until all the headers are transmitted. // - Any responses whose status is in the range 100 to 199, inclusive, // and is not 101, are to be ignored, except for the purposes of setting // timingInfo’s final network-response start time above. // - If request’s header list contains `Transfer-Encoding`/`chunked` and // response is transferred via HTTP/1.0 or older, then return a network // error. // - If the HTTP request results in a TLS client certificate dialog, then: // 1. If request’s window is an environment settings object, make the // dialog available in request’s window. // 2. Otherwise, return a network error. // To transmit request’s body body, run these steps: let requestBody = null // 1. If body is null and fetchParams’s process request end-of-body is // non-null, then queue a fetch task given fetchParams’s process request // end-of-body and fetchParams’s task destination. if (request.body == null && fetchParams.processRequestEndOfBody) { queueMicrotask(() => fetchParams.processRequestEndOfBody()) } else if (request.body != null) { // 2. Otherwise, if body is non-null: // 1. Let processBodyChunk given bytes be these steps: const processBodyChunk = async function * (bytes) { // 1. If the ongoing fetch is terminated, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. Run this step in parallel: transmit bytes. yield bytes // 3. If fetchParams’s process request body is non-null, then run // fetchParams’s process request body given bytes’s length. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) } // 2. Let processEndOfBody be these steps: const processEndOfBody = () => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If fetchParams’s process request end-of-body is non-null, // then run fetchParams’s process request end-of-body. if (fetchParams.processRequestEndOfBody) { fetchParams.processRequestEndOfBody() } } // 3. Let processBodyError given e be these steps: const processBodyError = (e) => { // 1. If fetchParams is canceled, then abort these steps. if (isCancelled(fetchParams)) { return } // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. if (e.name === 'AbortError') { fetchParams.controller.abort() } else { fetchParams.controller.terminate(e) } } // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, // processBodyError, and fetchParams’s task destination. requestBody = (async function * () { try { for await (const bytes of request.body.stream) { yield * processBodyChunk(bytes) } processEndOfBody() } catch (err) { processBodyError(err) } })() } try { // socket is only provided for websockets const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) if (socket) { response = makeResponse({ status, statusText, headersList, socket }) } else { const iterator = body[Symbol.asyncIterator]() fetchParams.controller.next = () => iterator.next() response = makeResponse({ status, statusText, headersList }) } } catch (err) { // 10. If aborted, then: if (err.name === 'AbortError') { // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. fetchParams.controller.connection.destroy() // 2. Return the appropriate network error for fetchParams. return makeAppropriateNetworkError(fetchParams, err) } return makeNetworkError(err) } // 11. Let pullAlgorithm be an action that resumes the ongoing fetch // if it is suspended. const pullAlgorithm = async () => { await fetchParams.controller.resume() } // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s // controller with reason, given reason. const cancelAlgorithm = (reason) => { // If the aborted fetch was already terminated, then we do not // need to do anything. if (!isCancelled(fetchParams)) { fetchParams.controller.abort(reason) } } // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by // the user agent. // TODO // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. // TODO // 15. Let stream be a new ReadableStream. // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm, // cancelAlgorithm set to cancelAlgorithm. const stream = new ReadableStream( { async start (controller) { fetchParams.controller.controller = controller }, async pull (controller) { await pullAlgorithm(controller) }, async cancel (reason) { await cancelAlgorithm(reason) }, type: 'bytes' } ) // 17. Run these steps, but abort when the ongoing fetch is terminated: // 1. Set response’s body to a new body whose stream is stream. response.body = { stream, source: null, length: null } // 2. If response is not a network error and request’s cache mode is // not "no-store", then update response in httpCache for request. // TODO // 3. If includeCredentials is true and the user agent is not configured // to block cookies for request (see section 7 of [COOKIES]), then run the // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on // the value of each header whose name is a byte-case-insensitive match for // `Set-Cookie` in response’s header list, if any, and request’s current URL. // TODO // 18. If aborted, then: // TODO // 19. Run these steps in parallel: // 1. Run these steps, but abort when fetchParams is canceled: fetchParams.controller.onAborted = onAborted fetchParams.controller.on('terminated', onAborted) fetchParams.controller.resume = async () => { // 1. While true while (true) { // 1-3. See onData... // 4. Set bytes to the result of handling content codings given // codings and bytes. let bytes let isFailure try { const { done, value } = await fetchParams.controller.next() if (isAborted(fetchParams)) { break } bytes = done ? undefined : value } catch (err) { if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { // zlib doesn't like empty streams. bytes = undefined } else { bytes = err // err may be propagated from the result of calling readablestream.cancel, // which might not be an error. https://github.com/nodejs/undici/issues/2009 isFailure = true } } if (bytes === undefined) { // 2. Otherwise, if the bytes transmission for response’s message // body is done normally and stream is readable, then close // stream, finalize response for fetchParams and response, and // abort these in-parallel steps. readableStreamClose(fetchParams.controller.controller) finalizeResponse(fetchParams, response) return } // 5. Increase timingInfo’s decoded body size by bytes’s length. timingInfo.decodedBodySize += bytes?.byteLength ?? 0 // 6. If bytes is failure, then terminate fetchParams’s controller. if (isFailure) { fetchParams.controller.terminate(bytes) return } // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes // into stream. const buffer = new Uint8Array(bytes) if (buffer.byteLength) { fetchParams.controller.controller.enqueue(buffer) } // 8. If stream is errored, then terminate the ongoing fetch. if (isErrored(stream)) { fetchParams.controller.terminate() return } // 9. If stream doesn’t need more data ask the user agent to suspend // the ongoing fetch. if (fetchParams.controller.controller.desiredSize <= 0) { return } } } // 2. If aborted, then: function onAborted (reason) { // 2. If fetchParams is aborted, then: if (isAborted(fetchParams)) { // 1. Set response’s aborted flag. response.aborted = true // 2. If stream is readable, then error stream with the result of // deserialize a serialized abort reason given fetchParams’s // controller’s serialized abort reason and an // implementation-defined realm. if (isReadable(stream)) { fetchParams.controller.controller.error( fetchParams.controller.serializedAbortReason ) } } else { // 3. Otherwise, if stream is readable, error stream with a TypeError. if (isReadable(stream)) { fetchParams.controller.controller.error(new TypeError('terminated', { cause: isErrorLike(reason) ? reason : undefined })) } } // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. fetchParams.controller.connection.destroy() } // 20. Return response. return response function dispatch ({ body }) { const url = requestCurrentURL(request) /** @type {import('../..').Agent} */ const agent = fetchParams.controller.dispatcher return new Promise((resolve, reject) => agent.dispatch( { path: url.pathname + url.search, origin: url.origin, method: request.method, body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body, headers: request.headersList.entries, maxRedirections: 0, upgrade: request.mode === 'websocket' ? 'websocket' : undefined }, { body: null, abort: null, onConnect (abort) { // TODO (fix): Do we need connection here? const { connection } = fetchParams.controller // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen // connection timing info with connection’s timing info, timingInfo’s post-redirect start // time, and fetchParams’s cross-origin isolated capability. // TODO: implement connection timing timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability) if (connection.destroyed) { abort(new DOMException('The operation was aborted.', 'AbortError')) } else { fetchParams.controller.on('terminated', abort) this.abort = connection.abort = abort } // Set timingInfo’s final network-request start time to the coarsened shared current time given // fetchParams’s cross-origin isolated capability. timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) }, onResponseStarted () { // Set timingInfo’s final network-response start time to the coarsened shared current // time given fetchParams’s cross-origin isolated capability, immediately after the // user agent’s HTTP parser receives the first byte of the response (e.g., frame header // bytes for HTTP/2 or response status line for HTTP/1.x). timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) }, onHeaders (status, rawHeaders, resume, statusText) { if (status < 200) { return } let location = '' const headersList = new HeadersList() for (let i = 0; i < rawHeaders.length; i += 2) { headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) } location = headersList.get('location', true) this.body = new Readable({ read: resume }) const decoders = [] const willFollow = location && request.redirect === 'follow' && redirectStatusSet.has(status) // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 const contentEncoding = headersList.get('content-encoding', true) // "All content-coding values are case-insensitive..." /** @type {string[]} */ const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : [] // Limit the number of content-encodings to prevent resource exhaustion. // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206). const maxContentEncodings = 5 if (codings.length > maxContentEncodings) { reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`)) return true } for (let i = codings.length - 1; i >= 0; --i) { const coding = codings[i].trim() // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 if (coding === 'x-gzip' || coding === 'gzip') { decoders.push(zlib.createGunzip({ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'deflate') { decoders.push(createInflate({ flush: zlib.constants.Z_SYNC_FLUSH, finishFlush: zlib.constants.Z_SYNC_FLUSH })) } else if (coding === 'br') { decoders.push(zlib.createBrotliDecompress({ flush: zlib.constants.BROTLI_OPERATION_FLUSH, finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH })) } else { decoders.length = 0 break } } } const onError = this.onError.bind(this) resolve({ status, statusText, headersList, body: decoders.length ? pipeline(this.body, ...decoders, (err) => { if (err) { this.onError(err) } }).on('error', onError) : this.body.on('error', onError) }) return true }, onData (chunk) { if (fetchParams.controller.dump) { return } // 1. If one or more bytes have been transmitted from response’s // message body, then: // 1. Let bytes be the transmitted bytes. const bytes = chunk // 2. Let codings be the result of extracting header list values // given `Content-Encoding` and response’s header list. // See pullAlgorithm. // 3. Increase timingInfo’s encoded body size by bytes’s length. timingInfo.encodedBodySize += bytes.byteLength // 4. See pullAlgorithm... return this.body.push(bytes) }, onComplete () { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } if (fetchParams.controller.onAborted) { fetchParams.controller.off('terminated', fetchParams.controller.onAborted) } fetchParams.controller.ended = true this.body.push(null) }, onError (error) { if (this.abort) { fetchParams.controller.off('terminated', this.abort) } this.body?.destroy(error) fetchParams.controller.terminate(error) reject(error) }, onUpgrade (status, rawHeaders, socket) { if (status !== 101) { return } const headersList = new HeadersList() for (let i = 0; i < rawHeaders.length; i += 2) { headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true) } resolve({ status, statusText: STATUS_CODES[status], headersList, socket }) return true } } )) } } module.exports = { fetch, Fetch, fetching, finalizeAndReportTiming } /***/ }), /***/ 9967: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* globals AbortController */ const { extractBody, mixinBody, cloneBody, bodyUnusable } = __nccwpck_require__(4492) const { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = __nccwpck_require__(660) const { FinalizationRegistry } = __nccwpck_require__(6653)() const util = __nccwpck_require__(3440) const nodeUtil = __nccwpck_require__(7975) const { isValidHTTPToken, sameOrigin, environmentSettingsObject } = __nccwpck_require__(3168) const { forbiddenMethodsSet, corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, requestDuplex } = __nccwpck_require__(4495) const { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util const { kHeaders, kSignal, kState, kDispatcher } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) const { URLSerializer } = __nccwpck_require__(1900) const { kConstruct } = __nccwpck_require__(6443) const assert = __nccwpck_require__(4589) const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(8474) const kAbortController = Symbol('abortController') const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { signal.removeEventListener('abort', abort) }) const dependentControllerMap = new WeakMap() function buildAbort (acRef) { return abort function abort () { const ac = acRef.deref() if (ac !== undefined) { // Currently, there is a problem with FinalizationRegistry. // https://github.com/nodejs/node/issues/49344 // https://github.com/nodejs/node/issues/47748 // In the case of abort, the first step is to unregister from it. // If the controller can refer to it, it is still registered. // It will be removed in the future. requestFinalizer.unregister(abort) // Unsubscribe a listener. // FinalizationRegistry will no longer be called, so this must be done. this.removeEventListener('abort', abort) ac.abort(this.reason) const controllerList = dependentControllerMap.get(ac.signal) if (controllerList !== undefined) { if (controllerList.size !== 0) { for (const ref of controllerList) { const ctrl = ref.deref() if (ctrl !== undefined) { ctrl.abort(this.reason) } } controllerList.clear() } dependentControllerMap.delete(ac.signal) } } } } let patchMethodWarning = false // https://fetch.spec.whatwg.org/#request-class class Request { // https://fetch.spec.whatwg.org/#dom-request constructor (input, init = {}) { webidl.util.markAsUncloneable(this) if (input === kConstruct) { return } const prefix = 'Request constructor' webidl.argumentLengthCheck(arguments, 1, prefix) input = webidl.converters.RequestInfo(input, prefix, 'input') init = webidl.converters.RequestInit(init, prefix, 'init') // 1. Let request be null. let request = null // 2. Let fallbackMode be null. let fallbackMode = null // 3. Let baseURL be this’s relevant settings object’s API base URL. const baseUrl = environmentSettingsObject.settingsObject.baseUrl // 4. Let signal be null. let signal = null // 5. If input is a string, then: if (typeof input === 'string') { this[kDispatcher] = init.dispatcher // 1. Let parsedURL be the result of parsing input with baseURL. // 2. If parsedURL is failure, then throw a TypeError. let parsedURL try { parsedURL = new URL(input, baseUrl) } catch (err) { throw new TypeError('Failed to parse URL from ' + input, { cause: err }) } // 3. If parsedURL includes credentials, then throw a TypeError. if (parsedURL.username || parsedURL.password) { throw new TypeError( 'Request cannot be constructed from a URL that includes credentials: ' + input ) } // 4. Set request to a new request whose URL is parsedURL. request = makeRequest({ urlList: [parsedURL] }) // 5. Set fallbackMode to "cors". fallbackMode = 'cors' } else { this[kDispatcher] = init.dispatcher || input[kDispatcher] // 6. Otherwise: // 7. Assert: input is a Request object. assert(input instanceof Request) // 8. Set request to input’s request. request = input[kState] // 9. Set signal to input’s signal. signal = input[kSignal] } // 7. Let origin be this’s relevant settings object’s origin. const origin = environmentSettingsObject.settingsObject.origin // 8. Let window be "client". let window = 'client' // 9. If request’s window is an environment settings object and its origin // is same origin with origin, then set window to request’s window. if ( request.window?.constructor?.name === 'EnvironmentSettingsObject' && sameOrigin(request.window, origin) ) { window = request.window } // 10. If init["window"] exists and is non-null, then throw a TypeError. if (init.window != null) { throw new TypeError(`'window' option '${window}' must be null`) } // 11. If init["window"] exists, then set window to "no-window". if ('window' in init) { window = 'no-window' } // 12. Set request to a new request with the following properties: request = makeRequest({ // URL request’s URL. // undici implementation note: this is set as the first item in request's urlList in makeRequest // method request’s method. method: request.method, // header list A copy of request’s header list. // undici implementation note: headersList is cloned in makeRequest headersList: request.headersList, // unsafe-request flag Set. unsafeRequest: request.unsafeRequest, // client This’s relevant settings object. client: environmentSettingsObject.settingsObject, // window window. window, // priority request’s priority. priority: request.priority, // origin request’s origin. The propagation of the origin is only significant for navigation requests // being handled by a service worker. In this scenario a request can have an origin that is different // from the current client. origin: request.origin, // referrer request’s referrer. referrer: request.referrer, // referrer policy request’s referrer policy. referrerPolicy: request.referrerPolicy, // mode request’s mode. mode: request.mode, // credentials mode request’s credentials mode. credentials: request.credentials, // cache mode request’s cache mode. cache: request.cache, // redirect mode request’s redirect mode. redirect: request.redirect, // integrity metadata request’s integrity metadata. integrity: request.integrity, // keepalive request’s keepalive. keepalive: request.keepalive, // reload-navigation flag request’s reload-navigation flag. reloadNavigation: request.reloadNavigation, // history-navigation flag request’s history-navigation flag. historyNavigation: request.historyNavigation, // URL list A clone of request’s URL list. urlList: [...request.urlList] }) const initHasKey = Object.keys(init).length !== 0 // 13. If init is not empty, then: if (initHasKey) { // 1. If request’s mode is "navigate", then set it to "same-origin". if (request.mode === 'navigate') { request.mode = 'same-origin' } // 2. Unset request’s reload-navigation flag. request.reloadNavigation = false // 3. Unset request’s history-navigation flag. request.historyNavigation = false // 4. Set request’s origin to "client". request.origin = 'client' // 5. Set request’s referrer to "client" request.referrer = 'client' // 6. Set request’s referrer policy to the empty string. request.referrerPolicy = '' // 7. Set request’s URL to request’s current URL. request.url = request.urlList[request.urlList.length - 1] // 8. Set request’s URL list to « request’s URL ». request.urlList = [request.url] } // 14. If init["referrer"] exists, then: if (init.referrer !== undefined) { // 1. Let referrer be init["referrer"]. const referrer = init.referrer // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". if (referrer === '') { request.referrer = 'no-referrer' } else { // 1. Let parsedReferrer be the result of parsing referrer with // baseURL. // 2. If parsedReferrer is failure, then throw a TypeError. let parsedReferrer try { parsedReferrer = new URL(referrer, baseUrl) } catch (err) { throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) } // 3. If one of the following is true // - parsedReferrer’s scheme is "about" and path is the string "client" // - parsedReferrer’s origin is not same origin with origin // then set request’s referrer to "client". if ( (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) ) { request.referrer = 'client' } else { // 4. Otherwise, set request’s referrer to parsedReferrer. request.referrer = parsedReferrer } } } // 15. If init["referrerPolicy"] exists, then set request’s referrer policy // to it. if (init.referrerPolicy !== undefined) { request.referrerPolicy = init.referrerPolicy } // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. let mode if (init.mode !== undefined) { mode = init.mode } else { mode = fallbackMode } // 17. If mode is "navigate", then throw a TypeError. if (mode === 'navigate') { throw webidl.errors.exception({ header: 'Request constructor', message: 'invalid request mode navigate.' }) } // 18. If mode is non-null, set request’s mode to mode. if (mode != null) { request.mode = mode } // 19. If init["credentials"] exists, then set request’s credentials mode // to it. if (init.credentials !== undefined) { request.credentials = init.credentials } // 18. If init["cache"] exists, then set request’s cache mode to it. if (init.cache !== undefined) { request.cache = init.cache } // 21. If request’s cache mode is "only-if-cached" and request’s mode is // not "same-origin", then throw a TypeError. if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { throw new TypeError( "'only-if-cached' can be set only with 'same-origin' mode" ) } // 22. If init["redirect"] exists, then set request’s redirect mode to it. if (init.redirect !== undefined) { request.redirect = init.redirect } // 23. If init["integrity"] exists, then set request’s integrity metadata to it. if (init.integrity != null) { request.integrity = String(init.integrity) } // 24. If init["keepalive"] exists, then set request’s keepalive to it. if (init.keepalive !== undefined) { request.keepalive = Boolean(init.keepalive) } // 25. If init["method"] exists, then: if (init.method !== undefined) { // 1. Let method be init["method"]. let method = init.method const mayBeNormalized = normalizedMethodRecords[method] if (mayBeNormalized !== undefined) { // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones request.method = mayBeNormalized } else { // 2. If method is not a method or method is a forbidden method, then // throw a TypeError. if (!isValidHTTPToken(method)) { throw new TypeError(`'${method}' is not a valid HTTP method.`) } const upperCase = method.toUpperCase() if (forbiddenMethodsSet.has(upperCase)) { throw new TypeError(`'${method}' HTTP method is unsupported.`) } // 3. Normalize method. // https://fetch.spec.whatwg.org/#concept-method-normalize // Note: must be in uppercase method = normalizedMethodRecordsBase[upperCase] ?? method // 4. Set request’s method to method. request.method = method } if (!patchMethodWarning && request.method === 'patch') { process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', { code: 'UNDICI-FETCH-patch' }) patchMethodWarning = true } } // 26. If init["signal"] exists, then set signal to it. if (init.signal !== undefined) { signal = init.signal } // 27. Set this’s request to request. this[kState] = request // 28. Set this’s signal to a new AbortSignal object with this’s relevant // Realm. // TODO: could this be simplified with AbortSignal.any // (https://dom.spec.whatwg.org/#dom-abortsignal-any) const ac = new AbortController() this[kSignal] = ac.signal // 29. If signal is not null, then make this’s signal follow signal. if (signal != null) { if ( !signal || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function' ) { throw new TypeError( "Failed to construct 'Request': member signal is not of type AbortSignal." ) } if (signal.aborted) { ac.abort(signal.reason) } else { // Keep a strong ref to ac while request object // is alive. This is needed to prevent AbortController // from being prematurely garbage collected. // See, https://github.com/nodejs/undici/issues/1926. this[kAbortController] = ac const acRef = new WeakRef(ac) const abort = buildAbort(acRef) // Third-party AbortControllers may not work with these. // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. try { // If the max amount of listeners is equal to the default, increase it // This is only available in node >= v19.9.0 if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { setMaxListeners(1500, signal) } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { setMaxListeners(1500, signal) } } catch {} util.addAbortListener(signal, abort) // The third argument must be a registry key to be unregistered. // Without it, you cannot unregister. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry // abort is used as the unregister key. (because it is unique) requestFinalizer.register(ac, { signal, abort }, abort) } } // 30. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is request’s header list and guard is // "request". this[kHeaders] = new Headers(kConstruct) setHeadersList(this[kHeaders], request.headersList) setHeadersGuard(this[kHeaders], 'request') // 31. If this’s request’s mode is "no-cors", then: if (mode === 'no-cors') { // 1. If this’s request’s method is not a CORS-safelisted method, // then throw a TypeError. if (!corsSafeListedMethodsSet.has(request.method)) { throw new TypeError( `'${request.method} is unsupported in no-cors mode.` ) } // 2. Set this’s headers’s guard to "request-no-cors". setHeadersGuard(this[kHeaders], 'request-no-cors') } // 32. If init is not empty, then: if (initHasKey) { /** @type {HeadersList} */ const headersList = getHeadersList(this[kHeaders]) // 1. Let headers be a copy of this’s headers and its associated header // list. // 2. If init["headers"] exists, then set headers to init["headers"]. const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) // 3. Empty this’s headers’s header list. headersList.clear() // 4. If headers is a Headers object, then for each header in its header // list, append header’s name/header’s value to this’s headers. if (headers instanceof HeadersList) { for (const { name, value } of headers.rawValues()) { headersList.append(name, value, false) } // Note: Copy the `set-cookie` meta-data. headersList.cookies = headers.cookies } else { // 5. Otherwise, fill this’s headers with headers. fillHeaders(this[kHeaders], headers) } } // 33. Let inputBody be input’s request’s body if input is a Request // object; otherwise null. const inputBody = input instanceof Request ? input[kState].body : null // 34. If either init["body"] exists and is non-null or inputBody is // non-null, and request’s method is `GET` or `HEAD`, then throw a // TypeError. if ( (init.body != null || inputBody != null) && (request.method === 'GET' || request.method === 'HEAD') ) { throw new TypeError('Request with GET/HEAD method cannot have body.') } // 35. Let initBody be null. let initBody = null // 36. If init["body"] exists and is non-null, then: if (init.body != null) { // 1. Let Content-Type be null. // 2. Set initBody and Content-Type to the result of extracting // init["body"], with keepalive set to request’s keepalive. const [extractedBody, contentType] = extractBody( init.body, request.keepalive ) initBody = extractedBody // 3, If Content-Type is non-null and this’s headers’s header list does // not contain `Content-Type`, then append `Content-Type`/Content-Type to // this’s headers. if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) { this[kHeaders].append('content-type', contentType) } } // 37. Let inputOrInitBody be initBody if it is non-null; otherwise // inputBody. const inputOrInitBody = initBody ?? inputBody // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is // null, then: if (inputOrInitBody != null && inputOrInitBody.source == null) { // 1. If initBody is non-null and init["duplex"] does not exist, // then throw a TypeError. if (initBody != null && init.duplex == null) { throw new TypeError('RequestInit: duplex option is required when sending a body.') } // 2. If this’s request’s mode is neither "same-origin" nor "cors", // then throw a TypeError. if (request.mode !== 'same-origin' && request.mode !== 'cors') { throw new TypeError( 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' ) } // 3. Set this’s request’s use-CORS-preflight flag. request.useCORSPreflightFlag = true } // 39. Let finalBody be inputOrInitBody. let finalBody = inputOrInitBody // 40. If initBody is null and inputBody is non-null, then: if (initBody == null && inputBody != null) { // 1. If input is unusable, then throw a TypeError. if (bodyUnusable(input)) { throw new TypeError( 'Cannot construct a Request with a Request object that has already been used.' ) } // 2. Set finalBody to the result of creating a proxy for inputBody. // https://streams.spec.whatwg.org/#readablestream-create-a-proxy const identityTransform = new TransformStream() inputBody.stream.pipeThrough(identityTransform) finalBody = { source: inputBody.source, length: inputBody.length, stream: identityTransform.readable } } // 41. Set this’s request’s body to finalBody. this[kState].body = finalBody } // Returns request’s HTTP method, which is "GET" by default. get method () { webidl.brandCheck(this, Request) // The method getter steps are to return this’s request’s method. return this[kState].method } // Returns the URL of request as a string. get url () { webidl.brandCheck(this, Request) // The url getter steps are to return this’s request’s URL, serialized. return URLSerializer(this[kState].url) } // Returns a Headers object consisting of the headers associated with request. // Note that headers added in the network layer by the user agent will not // be accounted for in this object, e.g., the "Host" header. get headers () { webidl.brandCheck(this, Request) // The headers getter steps are to return this’s headers. return this[kHeaders] } // Returns the kind of resource requested by request, e.g., "document" // or "script". get destination () { webidl.brandCheck(this, Request) // The destination getter are to return this’s request’s destination. return this[kState].destination } // Returns the referrer of request. Its value can be a same-origin URL if // explicitly set in init, the empty string to indicate no referrer, and // "about:client" when defaulting to the global’s default. This is used // during fetching to determine the value of the `Referer` header of the // request being made. get referrer () { webidl.brandCheck(this, Request) // 1. If this’s request’s referrer is "no-referrer", then return the // empty string. if (this[kState].referrer === 'no-referrer') { return '' } // 2. If this’s request’s referrer is "client", then return // "about:client". if (this[kState].referrer === 'client') { return 'about:client' } // Return this’s request’s referrer, serialized. return this[kState].referrer.toString() } // Returns the referrer policy associated with request. // This is used during fetching to compute the value of the request’s // referrer. get referrerPolicy () { webidl.brandCheck(this, Request) // The referrerPolicy getter steps are to return this’s request’s referrer policy. return this[kState].referrerPolicy } // Returns the mode associated with request, which is a string indicating // whether the request will use CORS, or will be restricted to same-origin // URLs. get mode () { webidl.brandCheck(this, Request) // The mode getter steps are to return this’s request’s mode. return this[kState].mode } // Returns the credentials mode associated with request, // which is a string indicating whether credentials will be sent with the // request always, never, or only when sent to a same-origin URL. get credentials () { // The credentials getter steps are to return this’s request’s credentials mode. return this[kState].credentials } // Returns the cache mode associated with request, // which is a string indicating how the request will // interact with the browser’s cache when fetching. get cache () { webidl.brandCheck(this, Request) // The cache getter steps are to return this’s request’s cache mode. return this[kState].cache } // Returns the redirect mode associated with request, // which is a string indicating how redirects for the // request will be handled during fetching. A request // will follow redirects by default. get redirect () { webidl.brandCheck(this, Request) // The redirect getter steps are to return this’s request’s redirect mode. return this[kState].redirect } // Returns request’s subresource integrity metadata, which is a // cryptographic hash of the resource being fetched. Its value // consists of multiple hashes separated by whitespace. [SRI] get integrity () { webidl.brandCheck(this, Request) // The integrity getter steps are to return this’s request’s integrity // metadata. return this[kState].integrity } // Returns a boolean indicating whether or not request can outlive the // global in which it was created. get keepalive () { webidl.brandCheck(this, Request) // The keepalive getter steps are to return this’s request’s keepalive. return this[kState].keepalive } // Returns a boolean indicating whether or not request is for a reload // navigation. get isReloadNavigation () { webidl.brandCheck(this, Request) // The isReloadNavigation getter steps are to return true if this’s // request’s reload-navigation flag is set; otherwise false. return this[kState].reloadNavigation } // Returns a boolean indicating whether or not request is for a history // navigation (a.k.a. back-forward navigation). get isHistoryNavigation () { webidl.brandCheck(this, Request) // The isHistoryNavigation getter steps are to return true if this’s request’s // history-navigation flag is set; otherwise false. return this[kState].historyNavigation } // Returns the signal associated with request, which is an AbortSignal // object indicating whether or not request has been aborted, and its // abort event handler. get signal () { webidl.brandCheck(this, Request) // The signal getter steps are to return this’s signal. return this[kSignal] } get body () { webidl.brandCheck(this, Request) return this[kState].body ? this[kState].body.stream : null } get bodyUsed () { webidl.brandCheck(this, Request) return !!this[kState].body && util.isDisturbed(this[kState].body.stream) } get duplex () { webidl.brandCheck(this, Request) return 'half' } // Returns a clone of request. clone () { webidl.brandCheck(this, Request) // 1. If this is unusable, then throw a TypeError. if (bodyUnusable(this)) { throw new TypeError('unusable') } // 2. Let clonedRequest be the result of cloning this’s request. const clonedRequest = cloneRequest(this[kState]) // 3. Let clonedRequestObject be the result of creating a Request object, // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. // 4. Make clonedRequestObject’s signal follow this’s signal. const ac = new AbortController() if (this.signal.aborted) { ac.abort(this.signal.reason) } else { let list = dependentControllerMap.get(this.signal) if (list === undefined) { list = new Set() dependentControllerMap.set(this.signal, list) } const acRef = new WeakRef(ac) list.add(acRef) util.addAbortListener( ac.signal, buildAbort(acRef) ) } // 4. Return clonedRequestObject. return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders])) } [nodeUtil.inspect.custom] (depth, options) { if (options.depth === null) { options.depth = 2 } options.colors ??= true const properties = { method: this.method, url: this.url, headers: this.headers, destination: this.destination, referrer: this.referrer, referrerPolicy: this.referrerPolicy, mode: this.mode, credentials: this.credentials, cache: this.cache, redirect: this.redirect, integrity: this.integrity, keepalive: this.keepalive, isReloadNavigation: this.isReloadNavigation, isHistoryNavigation: this.isHistoryNavigation, signal: this.signal } return `Request ${nodeUtil.formatWithOptions(options, properties)}` } } mixinBody(Request) // https://fetch.spec.whatwg.org/#requests function makeRequest (init) { return { method: init.method ?? 'GET', localURLsOnly: init.localURLsOnly ?? false, unsafeRequest: init.unsafeRequest ?? false, body: init.body ?? null, client: init.client ?? null, reservedClient: init.reservedClient ?? null, replacesClientId: init.replacesClientId ?? '', window: init.window ?? 'client', keepalive: init.keepalive ?? false, serviceWorkers: init.serviceWorkers ?? 'all', initiator: init.initiator ?? '', destination: init.destination ?? '', priority: init.priority ?? null, origin: init.origin ?? 'client', policyContainer: init.policyContainer ?? 'client', referrer: init.referrer ?? 'client', referrerPolicy: init.referrerPolicy ?? '', mode: init.mode ?? 'no-cors', useCORSPreflightFlag: init.useCORSPreflightFlag ?? false, credentials: init.credentials ?? 'same-origin', useCredentials: init.useCredentials ?? false, cache: init.cache ?? 'default', redirect: init.redirect ?? 'follow', integrity: init.integrity ?? '', cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '', parserMetadata: init.parserMetadata ?? '', reloadNavigation: init.reloadNavigation ?? false, historyNavigation: init.historyNavigation ?? false, userActivation: init.userActivation ?? false, taintedOrigin: init.taintedOrigin ?? false, redirectCount: init.redirectCount ?? 0, responseTainting: init.responseTainting ?? 'basic', preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false, done: init.done ?? false, timingAllowFailed: init.timingAllowFailed ?? false, urlList: init.urlList, url: init.urlList[0], headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList() } } // https://fetch.spec.whatwg.org/#concept-request-clone function cloneRequest (request) { // To clone a request request, run these steps: // 1. Let newRequest be a copy of request, except for its body. const newRequest = makeRequest({ ...request, body: null }) // 2. If request’s body is non-null, set newRequest’s body to the // result of cloning request’s body. if (request.body != null) { newRequest.body = cloneBody(newRequest, request.body) } // 3. Return newRequest. return newRequest } /** * @see https://fetch.spec.whatwg.org/#request-create * @param {any} innerRequest * @param {AbortSignal} signal * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard * @returns {Request} */ function fromInnerRequest (innerRequest, signal, guard) { const request = new Request(kConstruct) request[kState] = innerRequest request[kSignal] = signal request[kHeaders] = new Headers(kConstruct) setHeadersList(request[kHeaders], innerRequest.headersList) setHeadersGuard(request[kHeaders], guard) return request } Object.defineProperties(Request.prototype, { method: kEnumerableProperty, url: kEnumerableProperty, headers: kEnumerableProperty, redirect: kEnumerableProperty, clone: kEnumerableProperty, signal: kEnumerableProperty, duplex: kEnumerableProperty, destination: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, isHistoryNavigation: kEnumerableProperty, isReloadNavigation: kEnumerableProperty, keepalive: kEnumerableProperty, integrity: kEnumerableProperty, cache: kEnumerableProperty, credentials: kEnumerableProperty, attribute: kEnumerableProperty, referrerPolicy: kEnumerableProperty, referrer: kEnumerableProperty, mode: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Request', configurable: true } }) webidl.converters.Request = webidl.interfaceConverter( Request ) // https://fetch.spec.whatwg.org/#requestinfo webidl.converters.RequestInfo = function (V, prefix, argument) { if (typeof V === 'string') { return webidl.converters.USVString(V, prefix, argument) } if (V instanceof Request) { return webidl.converters.Request(V, prefix, argument) } return webidl.converters.USVString(V, prefix, argument) } webidl.converters.AbortSignal = webidl.interfaceConverter( AbortSignal ) // https://fetch.spec.whatwg.org/#requestinit webidl.converters.RequestInit = webidl.dictionaryConverter([ { key: 'method', converter: webidl.converters.ByteString }, { key: 'headers', converter: webidl.converters.HeadersInit }, { key: 'body', converter: webidl.nullableConverter( webidl.converters.BodyInit ) }, { key: 'referrer', converter: webidl.converters.USVString }, { key: 'referrerPolicy', converter: webidl.converters.DOMString, // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy allowedValues: referrerPolicy }, { key: 'mode', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#concept-request-mode allowedValues: requestMode }, { key: 'credentials', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcredentials allowedValues: requestCredentials }, { key: 'cache', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestcache allowedValues: requestCache }, { key: 'redirect', converter: webidl.converters.DOMString, // https://fetch.spec.whatwg.org/#requestredirect allowedValues: requestRedirect }, { key: 'integrity', converter: webidl.converters.DOMString }, { key: 'keepalive', converter: webidl.converters.boolean }, { key: 'signal', converter: webidl.nullableConverter( (signal) => webidl.converters.AbortSignal( signal, 'RequestInit', 'signal', { strict: false } ) ) }, { key: 'window', converter: webidl.converters.any }, { key: 'duplex', converter: webidl.converters.DOMString, allowedValues: requestDuplex }, { key: 'dispatcher', // undici specific option converter: webidl.converters.any } ]) module.exports = { Request, makeRequest, fromInnerRequest, cloneRequest } /***/ }), /***/ 9051: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = __nccwpck_require__(660) const { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = __nccwpck_require__(4492) const util = __nccwpck_require__(3440) const nodeUtil = __nccwpck_require__(7975) const { kEnumerableProperty } = util const { isValidReasonPhrase, isCancelled, isAborted, isBlobLike, serializeJavascriptValueToJSONString, isErrorLike, isomorphicEncode, environmentSettingsObject: relevantRealm } = __nccwpck_require__(3168) const { redirectStatusSet, nullBodyStatus } = __nccwpck_require__(4495) const { kState, kHeaders } = __nccwpck_require__(3627) const { webidl } = __nccwpck_require__(5893) const { FormData } = __nccwpck_require__(5910) const { URLSerializer } = __nccwpck_require__(1900) const { kConstruct } = __nccwpck_require__(6443) const assert = __nccwpck_require__(4589) const { types } = __nccwpck_require__(7975) const textEncoder = new TextEncoder('utf-8') // https://fetch.spec.whatwg.org/#response-class class Response { // Creates network error Response. static error () { // The static error() method steps are to return the result of creating a // Response object, given a new network error, "immutable", and this’s // relevant Realm. const responseObject = fromInnerResponse(makeNetworkError(), 'immutable') return responseObject } // https://fetch.spec.whatwg.org/#dom-response-json static json (data, init = {}) { webidl.argumentLengthCheck(arguments, 1, 'Response.json') if (init !== null) { init = webidl.converters.ResponseInit(init) } // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. const bytes = textEncoder.encode( serializeJavascriptValueToJSONString(data) ) // 2. Let body be the result of extracting bytes. const body = extractBody(bytes) // 3. Let responseObject be the result of creating a Response object, given a new response, // "response", and this’s relevant Realm. const responseObject = fromInnerResponse(makeResponse({}), 'response') // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) // 5. Return responseObject. return responseObject } // Creates a redirect Response that redirects to url with status status. static redirect (url, status = 302) { webidl.argumentLengthCheck(arguments, 1, 'Response.redirect') url = webidl.converters.USVString(url) status = webidl.converters['unsigned short'](status) // 1. Let parsedURL be the result of parsing url with current settings // object’s API base URL. // 2. If parsedURL is failure, then throw a TypeError. // TODO: base-URL? let parsedURL try { parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl) } catch (err) { throw new TypeError(`Failed to parse URL from ${url}`, { cause: err }) } // 3. If status is not a redirect status, then throw a RangeError. if (!redirectStatusSet.has(status)) { throw new RangeError(`Invalid status code ${status}`) } // 4. Let responseObject be the result of creating a Response object, // given a new response, "immutable", and this’s relevant Realm. const responseObject = fromInnerResponse(makeResponse({}), 'immutable') // 5. Set responseObject’s response’s status to status. responseObject[kState].status = status // 6. Let value be parsedURL, serialized and isomorphic encoded. const value = isomorphicEncode(URLSerializer(parsedURL)) // 7. Append `Location`/value to responseObject’s response’s header list. responseObject[kState].headersList.append('location', value, true) // 8. Return responseObject. return responseObject } // https://fetch.spec.whatwg.org/#dom-response constructor (body = null, init = {}) { webidl.util.markAsUncloneable(this) if (body === kConstruct) { return } if (body !== null) { body = webidl.converters.BodyInit(body) } init = webidl.converters.ResponseInit(init) // 1. Set this’s response to a new response. this[kState] = makeResponse({}) // 2. Set this’s headers to a new Headers object with this’s relevant // Realm, whose header list is this’s response’s header list and guard // is "response". this[kHeaders] = new Headers(kConstruct) setHeadersGuard(this[kHeaders], 'response') setHeadersList(this[kHeaders], this[kState].headersList) // 3. Let bodyWithType be null. let bodyWithType = null // 4. If body is non-null, then set bodyWithType to the result of extracting body. if (body != null) { const [extractedBody, type] = extractBody(body) bodyWithType = { body: extractedBody, type } } // 5. Perform initialize a response given this, init, and bodyWithType. initializeResponse(this, init, bodyWithType) } // Returns response’s type, e.g., "cors". get type () { webidl.brandCheck(this, Response) // The type getter steps are to return this’s response’s type. return this[kState].type } // Returns response’s URL, if it has one; otherwise the empty string. get url () { webidl.brandCheck(this, Response) const urlList = this[kState].urlList // The url getter steps are to return the empty string if this’s // response’s URL is null; otherwise this’s response’s URL, // serialized with exclude fragment set to true. const url = urlList[urlList.length - 1] ?? null if (url === null) { return '' } return URLSerializer(url, true) } // Returns whether response was obtained through a redirect. get redirected () { webidl.brandCheck(this, Response) // The redirected getter steps are to return true if this’s response’s URL // list has more than one item; otherwise false. return this[kState].urlList.length > 1 } // Returns response’s status. get status () { webidl.brandCheck(this, Response) // The status getter steps are to return this’s response’s status. return this[kState].status } // Returns whether response’s status is an ok status. get ok () { webidl.brandCheck(this, Response) // The ok getter steps are to return true if this’s response’s status is an // ok status; otherwise false. return this[kState].status >= 200 && this[kState].status <= 299 } // Returns response’s status message. get statusText () { webidl.brandCheck(this, Response) // The statusText getter steps are to return this’s response’s status // message. return this[kState].statusText } // Returns response’s headers as Headers. get headers () { webidl.brandCheck(this, Response) // The headers getter steps are to return this’s headers. return this[kHeaders] } get body () { webidl.brandCheck(this, Response) return this[kState].body ? this[kState].body.stream : null } get bodyUsed () { webidl.brandCheck(this, Response) return !!this[kState].body && util.isDisturbed(this[kState].body.stream) } // Returns a clone of response. clone () { webidl.brandCheck(this, Response) // 1. If this is unusable, then throw a TypeError. if (bodyUnusable(this)) { throw webidl.errors.exception({ header: 'Response.clone', message: 'Body has already been consumed.' }) } // 2. Let clonedResponse be the result of cloning this’s response. const clonedResponse = cloneResponse(this[kState]) // Note: To re-register because of a new stream. if (hasFinalizationRegistry && this[kState].body?.stream) { streamRegistry.register(this, new WeakRef(this[kState].body.stream)) } // 3. Return the result of creating a Response object, given // clonedResponse, this’s headers’s guard, and this’s relevant Realm. return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders])) } [nodeUtil.inspect.custom] (depth, options) { if (options.depth === null) { options.depth = 2 } options.colors ??= true const properties = { status: this.status, statusText: this.statusText, headers: this.headers, body: this.body, bodyUsed: this.bodyUsed, ok: this.ok, redirected: this.redirected, type: this.type, url: this.url } return `Response ${nodeUtil.formatWithOptions(options, properties)}` } } mixinBody(Response) Object.defineProperties(Response.prototype, { type: kEnumerableProperty, url: kEnumerableProperty, status: kEnumerableProperty, ok: kEnumerableProperty, redirected: kEnumerableProperty, statusText: kEnumerableProperty, headers: kEnumerableProperty, clone: kEnumerableProperty, body: kEnumerableProperty, bodyUsed: kEnumerableProperty, [Symbol.toStringTag]: { value: 'Response', configurable: true } }) Object.defineProperties(Response, { json: kEnumerableProperty, redirect: kEnumerableProperty, error: kEnumerableProperty }) // https://fetch.spec.whatwg.org/#concept-response-clone function cloneResponse (response) { // To clone a response response, run these steps: // 1. If response is a filtered response, then return a new identical // filtered response whose internal response is a clone of response’s // internal response. if (response.internalResponse) { return filterResponse( cloneResponse(response.internalResponse), response.type ) } // 2. Let newResponse be a copy of response, except for its body. const newResponse = makeResponse({ ...response, body: null }) // 3. If response’s body is non-null, then set newResponse’s body to the // result of cloning response’s body. if (response.body != null) { newResponse.body = cloneBody(newResponse, response.body) } // 4. Return newResponse. return newResponse } function makeResponse (init) { return { aborted: false, rangeRequested: false, timingAllowPassed: false, requestIncludesCredentials: false, type: 'default', status: 200, timingInfo: null, cacheState: '', statusText: '', ...init, headersList: init?.headersList ? new HeadersList(init?.headersList) : new HeadersList(), urlList: init?.urlList ? [...init.urlList] : [] } } function makeNetworkError (reason) { const isError = isErrorLike(reason) return makeResponse({ type: 'error', status: 0, error: isError ? reason : new Error(reason ? String(reason) : reason), aborted: reason && reason.name === 'AbortError' }) } // @see https://fetch.spec.whatwg.org/#concept-network-error function isNetworkError (response) { return ( // A network error is a response whose type is "error", response.type === 'error' && // status is 0 response.status === 0 ) } function makeFilteredResponse (response, state) { state = { internalResponse: response, ...state } return new Proxy(response, { get (target, p) { return p in state ? state[p] : target[p] }, set (target, p, value) { assert(!(p in state)) target[p] = value return true } }) } // https://fetch.spec.whatwg.org/#concept-filtered-response function filterResponse (response, type) { // Set response to the following filtered response with response as its // internal response, depending on request’s response tainting: if (type === 'basic') { // A basic filtered response is a filtered response whose type is "basic" // and header list excludes any headers in internal response’s header list // whose name is a forbidden response-header name. // Note: undici does not implement forbidden response-header names return makeFilteredResponse(response, { type: 'basic', headersList: response.headersList }) } else if (type === 'cors') { // A CORS filtered response is a filtered response whose type is "cors" // and header list excludes any headers in internal response’s header // list whose name is not a CORS-safelisted response-header name, given // internal response’s CORS-exposed header-name list. // Note: undici does not implement CORS-safelisted response-header names return makeFilteredResponse(response, { type: 'cors', headersList: response.headersList }) } else if (type === 'opaque') { // An opaque filtered response is a filtered response whose type is // "opaque", URL list is the empty list, status is 0, status message // is the empty byte sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaque', urlList: Object.freeze([]), status: 0, statusText: '', body: null }) } else if (type === 'opaqueredirect') { // An opaque-redirect filtered response is a filtered response whose type // is "opaqueredirect", status is 0, status message is the empty byte // sequence, header list is empty, and body is null. return makeFilteredResponse(response, { type: 'opaqueredirect', status: 0, statusText: '', headersList: [], body: null }) } else { assert(false) } } // https://fetch.spec.whatwg.org/#appropriate-network-error function makeAppropriateNetworkError (fetchParams, err = null) { // 1. Assert: fetchParams is canceled. assert(isCancelled(fetchParams)) // 2. Return an aborted network error if fetchParams is aborted; // otherwise return a network error. return isAborted(fetchParams) ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) } // https://whatpr.org/fetch/1392.html#initialize-a-response function initializeResponse (response, init, body) { // 1. If init["status"] is not in the range 200 to 599, inclusive, then // throw a RangeError. if (init.status !== null && (init.status < 200 || init.status > 599)) { throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') } // 2. If init["statusText"] does not match the reason-phrase token production, // then throw a TypeError. if ('statusText' in init && init.statusText != null) { // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) if (!isValidReasonPhrase(String(init.statusText))) { throw new TypeError('Invalid statusText') } } // 3. Set response’s response’s status to init["status"]. if ('status' in init && init.status != null) { response[kState].status = init.status } // 4. Set response’s response’s status message to init["statusText"]. if ('statusText' in init && init.statusText != null) { response[kState].statusText = init.statusText } // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. if ('headers' in init && init.headers != null) { fill(response[kHeaders], init.headers) } // 6. If body was given, then: if (body) { // 1. If response's status is a null body status, then throw a TypeError. if (nullBodyStatus.includes(response.status)) { throw webidl.errors.exception({ header: 'Response constructor', message: `Invalid response status code ${response.status}` }) } // 2. Set response's body to body's body. response[kState].body = body.body // 3. If body's type is non-null and response's header list does not contain // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. if (body.type != null && !response[kState].headersList.contains('content-type', true)) { response[kState].headersList.append('content-type', body.type, true) } } } /** * @see https://fetch.spec.whatwg.org/#response-create * @param {any} innerResponse * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard * @returns {Response} */ function fromInnerResponse (innerResponse, guard) { const response = new Response(kConstruct) response[kState] = innerResponse response[kHeaders] = new Headers(kConstruct) setHeadersList(response[kHeaders], innerResponse.headersList) setHeadersGuard(response[kHeaders], guard) if (hasFinalizationRegistry && innerResponse.body?.stream) { // If the target (response) is reclaimed, the cleanup callback may be called at some point with // the held value provided for it (innerResponse.body.stream). The held value can be any value: // a primitive or an object, even undefined. If the held value is an object, the registry keeps // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry streamRegistry.register(response, new WeakRef(innerResponse.body.stream)) } return response } webidl.converters.ReadableStream = webidl.interfaceConverter( ReadableStream ) webidl.converters.FormData = webidl.interfaceConverter( FormData ) webidl.converters.URLSearchParams = webidl.interfaceConverter( URLSearchParams ) // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit webidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) { if (typeof V === 'string') { return webidl.converters.USVString(V, prefix, name) } if (isBlobLike(V)) { return webidl.converters.Blob(V, prefix, name, { strict: false }) } if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { return webidl.converters.BufferSource(V, prefix, name) } if (util.isFormDataLike(V)) { return webidl.converters.FormData(V, prefix, name, { strict: false }) } if (V instanceof URLSearchParams) { return webidl.converters.URLSearchParams(V, prefix, name) } return webidl.converters.DOMString(V, prefix, name) } // https://fetch.spec.whatwg.org/#bodyinit webidl.converters.BodyInit = function (V, prefix, argument) { if (V instanceof ReadableStream) { return webidl.converters.ReadableStream(V, prefix, argument) } // Note: the spec doesn't include async iterables, // this is an undici extension. if (V?.[Symbol.asyncIterator]) { return V } return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument) } webidl.converters.ResponseInit = webidl.dictionaryConverter([ { key: 'status', converter: webidl.converters['unsigned short'], defaultValue: () => 200 }, { key: 'statusText', converter: webidl.converters.ByteString, defaultValue: () => '' }, { key: 'headers', converter: webidl.converters.HeadersInit } ]) module.exports = { isNetworkError, makeNetworkError, makeResponse, makeAppropriateNetworkError, filterResponse, Response, cloneResponse, fromInnerResponse } /***/ }), /***/ 3627: /***/ ((module) => { module.exports = { kUrl: Symbol('url'), kHeaders: Symbol('headers'), kSignal: Symbol('signal'), kState: Symbol('state'), kDispatcher: Symbol('dispatcher') } /***/ }), /***/ 3168: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Transform } = __nccwpck_require__(7075) const zlib = __nccwpck_require__(8522) const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(4495) const { getGlobalOrigin } = __nccwpck_require__(1059) const { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = __nccwpck_require__(1900) const { performance } = __nccwpck_require__(643) const { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = __nccwpck_require__(3440) const assert = __nccwpck_require__(4589) const { isUint8Array } = __nccwpck_require__(3429) const { webidl } = __nccwpck_require__(5893) let supportedHashes = [] // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(7598) const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) /* c8 ignore next 3 */ } catch { } function responseURL (response) { // https://fetch.spec.whatwg.org/#responses // A response has an associated URL. It is a pointer to the last URL // in response’s URL list and null if response’s URL list is empty. const urlList = response.urlList const length = urlList.length return length === 0 ? null : urlList[length - 1].toString() } // https://fetch.spec.whatwg.org/#concept-response-location-url function responseLocationURL (response, requestFragment) { // 1. If response’s status is not a redirect status, then return null. if (!redirectStatusSet.has(response.status)) { return null } // 2. Let location be the result of extracting header list values given // `Location` and response’s header list. let location = response.headersList.get('location', true) // 3. If location is a header value, then set location to the result of // parsing location with response’s URL. if (location !== null && isValidHeaderValue(location)) { if (!isValidEncodedURL(location)) { // Some websites respond location header in UTF-8 form without encoding them as ASCII // and major browsers redirect them to correctly UTF-8 encoded addresses. // Here, we handle that behavior in the same way. location = normalizeBinaryStringToUtf8(location) } location = new URL(location, responseURL(response)) } // 4. If location is a URL whose fragment is null, then set location’s // fragment to requestFragment. if (location && !location.hash) { location.hash = requestFragment } // 5. Return location. return location } /** * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2 * @param {string} url * @returns {boolean} */ function isValidEncodedURL (url) { for (let i = 0; i < url.length; ++i) { const code = url.charCodeAt(i) if ( code > 0x7E || // Non-US-ASCII + DEL code < 0x20 // Control characters NUL - US ) { return false } } return true } /** * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it. * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well. * @param {string} value * @returns {string} */ function normalizeBinaryStringToUtf8 (value) { return Buffer.from(value, 'binary').toString('utf8') } /** @returns {URL} */ function requestCurrentURL (request) { return request.urlList[request.urlList.length - 1] } function requestBadPort (request) { // 1. Let url be request’s current URL. const url = requestCurrentURL(request) // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, // then return blocked. if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { return 'blocked' } // 3. Return allowed. return 'allowed' } function isErrorLike (object) { return object instanceof Error || ( object?.constructor?.name === 'Error' || object?.constructor?.name === 'DOMException' ) } // Check whether |statusText| is a ByteString and // matches the Reason-Phrase token production. // RFC 2616: https://tools.ietf.org/html/rfc2616 // RFC 7230: https://tools.ietf.org/html/rfc7230 // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 function isValidReasonPhrase (statusText) { for (let i = 0; i < statusText.length; ++i) { const c = statusText.charCodeAt(i) if ( !( ( c === 0x09 || // HTAB (c >= 0x20 && c <= 0x7e) || // SP / VCHAR (c >= 0x80 && c <= 0xff) ) // obs-text ) ) { return false } } return true } /** * @see https://fetch.spec.whatwg.org/#header-name * @param {string} potentialValue */ const isValidHeaderName = isValidHTTPToken /** * @see https://fetch.spec.whatwg.org/#header-value * @param {string} potentialValue */ function isValidHeaderValue (potentialValue) { // - Has no leading or trailing HTTP tab or space bytes. // - Contains no 0x00 (NUL) or HTTP newline bytes. return ( potentialValue[0] === '\t' || potentialValue[0] === ' ' || potentialValue[potentialValue.length - 1] === '\t' || potentialValue[potentialValue.length - 1] === ' ' || potentialValue.includes('\n') || potentialValue.includes('\r') || potentialValue.includes('\0') ) === false } // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect function setRequestReferrerPolicyOnRedirect (request, actualResponse) { // Given a request request and a response actualResponse, this algorithm // updates request’s referrer policy according to the Referrer-Policy // header (if any) in actualResponse. // 1. Let policy be the result of executing § 8.1 Parse a referrer policy // from a Referrer-Policy header on actualResponse. // 8.1 Parse a referrer policy from a Referrer-Policy header // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. const { headersList } = actualResponse // 2. Let policy be the empty string. // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. // 4. Return policy. const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',') // Note: As the referrer-policy can contain multiple policies // separated by comma, we need to loop through all of them // and pick the first valid one. // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy let policy = '' if (policyHeader.length > 0) { // The right-most policy takes precedence. // The left-most policy is the fallback. for (let i = policyHeader.length; i !== 0; i--) { const token = policyHeader[i - 1].trim() if (referrerPolicyTokens.has(token)) { policy = token break } } } // 2. If policy is not the empty string, then set request’s referrer policy to policy. if (policy !== '') { request.referrerPolicy = policy } } // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check function crossOriginResourcePolicyCheck () { // TODO return 'allowed' } // https://fetch.spec.whatwg.org/#concept-cors-check function corsCheck () { // TODO return 'success' } // https://fetch.spec.whatwg.org/#concept-tao-check function TAOCheck () { // TODO return 'success' } function appendFetchMetadata (httpRequest) { // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header // 1. Assert: r’s url is a potentially trustworthy URL. // TODO // 2. Let header be a Structured Header whose value is a token. let header = null // 3. Set header’s value to r’s mode. header = httpRequest.mode // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. httpRequest.headersList.set('sec-fetch-mode', header, true) // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header // TODO // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header // TODO } // https://fetch.spec.whatwg.org/#append-a-request-origin-header function appendRequestOriginHeader (request) { // 1. Let serializedOrigin be the result of byte-serializing a request origin // with request. // TODO: implement "byte-serializing a request origin" let serializedOrigin = request.origin // - "'client' is changed to an origin during fetching." // This doesn't happen in undici (in most cases) because undici, by default, // has no concept of origin. // - request.origin can also be set to request.client.origin (client being // an environment settings object), which is undefined without using // setGlobalOrigin. if (serializedOrigin === 'client' || serializedOrigin === undefined) { return } // 2. If request’s response tainting is "cors" or request’s mode is "websocket", // then append (`Origin`, serializedOrigin) to request’s header list. // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: if (request.responseTainting === 'cors' || request.mode === 'websocket') { request.headersList.append('origin', serializedOrigin, true) } else if (request.method !== 'GET' && request.method !== 'HEAD') { // 1. Switch on request’s referrer policy: switch (request.referrerPolicy) { case 'no-referrer': // Set serializedOrigin to `null`. serializedOrigin = null break case 'no-referrer-when-downgrade': case 'strict-origin': case 'strict-origin-when-cross-origin': // If request’s origin is a tuple origin, its scheme is "https", and // request’s current URL’s scheme is not "https", then set // serializedOrigin to `null`. if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { serializedOrigin = null } break case 'same-origin': // If request’s origin is not same origin with request’s current URL’s // origin, then set serializedOrigin to `null`. if (!sameOrigin(request, requestCurrentURL(request))) { serializedOrigin = null } break default: // Do nothing. } // 2. Append (`Origin`, serializedOrigin) to request’s header list. request.headersList.append('origin', serializedOrigin, true) } } // https://w3c.github.io/hr-time/#dfn-coarsen-time function coarsenTime (timestamp, crossOriginIsolatedCapability) { // TODO return timestamp } // https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info function clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) { if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) { return { domainLookupStartTime: defaultStartTime, domainLookupEndTime: defaultStartTime, connectionStartTime: defaultStartTime, connectionEndTime: defaultStartTime, secureConnectionStartTime: defaultStartTime, ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol } } return { domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability), domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability), connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability), connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability), secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability), ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol } } // https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { return coarsenTime(performance.now(), crossOriginIsolatedCapability) } // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info function createOpaqueTimingInfo (timingInfo) { return { startTime: timingInfo.startTime ?? 0, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: timingInfo.startTime ?? 0, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null } } // https://html.spec.whatwg.org/multipage/origin.html#policy-container function makePolicyContainer () { // Note: the fetch spec doesn't make use of embedder policy or CSP list return { referrerPolicy: 'strict-origin-when-cross-origin' } } // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container function clonePolicyContainer (policyContainer) { return { referrerPolicy: policyContainer.referrerPolicy } } // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer function determineRequestsReferrer (request) { // 1. Let policy be request's referrer policy. const policy = request.referrerPolicy // Note: policy cannot (shouldn't) be null or an empty string. assert(policy) // 2. Let environment be request’s client. let referrerSource = null // 3. Switch on request’s referrer: if (request.referrer === 'client') { // Note: node isn't a browser and doesn't implement document/iframes, // so we bypass this step and replace it with our own. const globalOrigin = getGlobalOrigin() if (!globalOrigin || globalOrigin.origin === 'null') { return 'no-referrer' } // note: we need to clone it as it's mutated referrerSource = new URL(globalOrigin) } else if (request.referrer instanceof URL) { // Let referrerSource be request’s referrer. referrerSource = request.referrer } // 4. Let request’s referrerURL be the result of stripping referrerSource for // use as a referrer. let referrerURL = stripURLForReferrer(referrerSource) // 5. Let referrerOrigin be the result of stripping referrerSource for use as // a referrer, with the origin-only flag set to true. const referrerOrigin = stripURLForReferrer(referrerSource, true) // 6. If the result of serializing referrerURL is a string whose length is // greater than 4096, set referrerURL to referrerOrigin. if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin } const areSameOrigin = sameOrigin(request, referrerURL) const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request.url) // 8. Execute the switch statements corresponding to the value of policy: switch (policy) { case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) case 'unsafe-url': return referrerURL case 'same-origin': return areSameOrigin ? referrerOrigin : 'no-referrer' case 'origin-when-cross-origin': return areSameOrigin ? referrerURL : referrerOrigin case 'strict-origin-when-cross-origin': { const currentURL = requestCurrentURL(request) // 1. If the origin of referrerURL and the origin of request’s current // URL are the same, then return referrerURL. if (sameOrigin(referrerURL, currentURL)) { return referrerURL } // 2. If referrerURL is a potentially trustworthy URL and request’s // current URL is not a potentially trustworthy URL, then return no // referrer. if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { return 'no-referrer' } // 3. Return referrerOrigin. return referrerOrigin } case 'strict-origin': // eslint-disable-line /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, * then return no referrer. * 2. Return referrerOrigin */ case 'no-referrer-when-downgrade': // eslint-disable-line /** * 1. If referrerURL is a potentially trustworthy URL and * request’s current URL is not a potentially trustworthy URL, * then return no referrer. * 2. Return referrerOrigin */ default: // eslint-disable-line return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin } } /** * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url * @param {URL} url * @param {boolean|undefined} originOnly */ function stripURLForReferrer (url, originOnly) { // 1. Assert: url is a URL. assert(url instanceof URL) url = new URL(url) // 2. If url’s scheme is a local scheme, then return no referrer. if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { return 'no-referrer' } // 3. Set url’s username to the empty string. url.username = '' // 4. Set url’s password to the empty string. url.password = '' // 5. Set url’s fragment to null. url.hash = '' // 6. If the origin-only flag is true, then: if (originOnly) { // 1. Set url’s path to « the empty string ». url.pathname = '' // 2. Set url’s query to null. url.search = '' } // 7. Return url. return url } function isURLPotentiallyTrustworthy (url) { if (!(url instanceof URL)) { return false } // If child of about, return true if (url.href === 'about:blank' || url.href === 'about:srcdoc') { return true } // If scheme is data, return true if (url.protocol === 'data:') return true // If file, return true if (url.protocol === 'file:') return true return isOriginPotentiallyTrustworthy(url.origin) function isOriginPotentiallyTrustworthy (origin) { // If origin is explicitly null, return false if (origin == null || origin === 'null') return false const originAsURL = new URL(origin) // If secure, return true if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { return true } // If localhost or variants, return true if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || (originAsURL.hostname.endsWith('.localhost'))) { return true } // If any other, return false return false } } /** * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist * @param {Uint8Array} bytes * @param {string} metadataList */ function bytesMatch (bytes, metadataList) { // If node is not built with OpenSSL support, we cannot check // a request's integrity, so allow it by default (the spec will // allow requests if an invalid hash is given, as precedence). /* istanbul ignore if: only if node is built with --without-ssl */ if (crypto === undefined) { return true } // 1. Let parsedMetadata be the result of parsing metadataList. const parsedMetadata = parseMetadata(metadataList) // 2. If parsedMetadata is no metadata, return true. if (parsedMetadata === 'no metadata') { return true } // 3. If response is not eligible for integrity validation, return false. // TODO // 4. If parsedMetadata is the empty set, return true. if (parsedMetadata.length === 0) { return true } // 5. Let metadata be the result of getting the strongest // metadata from parsedMetadata. const strongest = getStrongestMetadata(parsedMetadata) const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) // 6. For each item in metadata: for (const item of metadata) { // 1. Let algorithm be the alg component of item. const algorithm = item.algo // 2. Let expectedValue be the val component of item. const expectedValue = item.hash // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e // "be liberal with padding". This is annoying, and it's not even in the spec. // 3. Let actualValue be the result of applying algorithm to bytes. let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') if (actualValue[actualValue.length - 1] === '=') { if (actualValue[actualValue.length - 2] === '=') { actualValue = actualValue.slice(0, -2) } else { actualValue = actualValue.slice(0, -1) } } // 4. If actualValue is a case-sensitive match for expectedValue, // return true. if (compareBase64Mixed(actualValue, expectedValue)) { return true } } // 7. Return false. return false } // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options // https://www.w3.org/TR/CSP2/#source-list-syntax // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i /** * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata * @param {string} metadata */ function parseMetadata (metadata) { // 1. Let result be the empty set. /** @type {{ algo: string, hash: string }[]} */ const result = [] // 2. Let empty be equal to true. let empty = true // 3. For each token returned by splitting metadata on spaces: for (const token of metadata.split(' ')) { // 1. Set empty to false. empty = false // 2. Parse token as a hash-with-options. const parsedToken = parseHashWithOptions.exec(token) // 3. If token does not parse, continue to the next token. if ( parsedToken === null || parsedToken.groups === undefined || parsedToken.groups.algo === undefined ) { // Note: Chromium blocks the request at this point, but Firefox // gives a warning that an invalid integrity was given. The // correct behavior is to ignore these, and subsequently not // check the integrity of the resource. continue } // 4. Let algorithm be the hash-algo component of token. const algorithm = parsedToken.groups.algo.toLowerCase() // 5. If algorithm is a hash function recognized by the user // agent, add the parsed token to result. if (supportedHashes.includes(algorithm)) { result.push(parsedToken.groups) } } // 4. Return no metadata if empty is true, otherwise return result. if (empty === true) { return 'no metadata' } return result } /** * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList */ function getStrongestMetadata (metadataList) { // Let algorithm be the algo component of the first item in metadataList. // Can be sha256 let algorithm = metadataList[0].algo // If the algorithm is sha512, then it is the strongest // and we can return immediately if (algorithm[3] === '5') { return algorithm } for (let i = 1; i < metadataList.length; ++i) { const metadata = metadataList[i] // If the algorithm is sha512, then it is the strongest // and we can break the loop immediately if (metadata.algo[3] === '5') { algorithm = 'sha512' break // If the algorithm is sha384, then a potential sha256 or sha384 is ignored } else if (algorithm[3] === '3') { continue // algorithm is sha256, check if algorithm is sha384 and if so, set it as // the strongest } else if (metadata.algo[3] === '3') { algorithm = 'sha384' } } return algorithm } function filterMetadataListByAlgorithm (metadataList, algorithm) { if (metadataList.length === 1) { return metadataList } let pos = 0 for (let i = 0; i < metadataList.length; ++i) { if (metadataList[i].algo === algorithm) { metadataList[pos++] = metadataList[i] } } metadataList.length = pos return metadataList } /** * Compares two base64 strings, allowing for base64url * in the second string. * * @param {string} actualValue always base64 * @param {string} expectedValue base64 or base64url * @returns {boolean} */ function compareBase64Mixed (actualValue, expectedValue) { if (actualValue.length !== expectedValue.length) { return false } for (let i = 0; i < actualValue.length; ++i) { if (actualValue[i] !== expectedValue[i]) { if ( (actualValue[i] === '+' && expectedValue[i] === '-') || (actualValue[i] === '/' && expectedValue[i] === '_') ) { continue } return false } } return true } // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { // TODO } /** * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} * @param {URL} A * @param {URL} B */ function sameOrigin (A, B) { // 1. If A and B are the same opaque origin, then return true. if (A.origin === B.origin && A.origin === 'null') { return true } // 2. If A and B are both tuple origins and their schemes, // hosts, and port are identical, then return true. if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { return true } // 3. Return false. return false } function createDeferredPromise () { let res let rej const promise = new Promise((resolve, reject) => { res = resolve rej = reject }) return { promise, resolve: res, reject: rej } } function isAborted (fetchParams) { return fetchParams.controller.state === 'aborted' } function isCancelled (fetchParams) { return fetchParams.controller.state === 'aborted' || fetchParams.controller.state === 'terminated' } /** * @see https://fetch.spec.whatwg.org/#concept-method-normalize * @param {string} method */ function normalizeMethod (method) { return normalizedMethodRecordsBase[method.toLowerCase()] ?? method } // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string function serializeJavascriptValueToJSONString (value) { // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). const result = JSON.stringify(value) // 2. If result is undefined, then throw a TypeError. if (result === undefined) { throw new TypeError('Value is not JSON serializable') } // 3. Assert: result is a string. assert(typeof result === 'string') // 4. Return result. return result } // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {string} name name of the instance * @param {symbol} kInternalIterator * @param {string | number} [keyIndex] * @param {string | number} [valueIndex] */ function createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) { class FastIterableIterator { /** @type {any} */ #target /** @type {'key' | 'value' | 'key+value'} */ #kind /** @type {number} */ #index /** * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object * @param {unknown} target * @param {'key' | 'value' | 'key+value'} kind */ constructor (target, kind) { this.#target = target this.#kind = kind this.#index = 0 } next () { // 1. Let interface be the interface for which the iterator prototype object exists. // 2. Let thisValue be the this value. // 3. Let object be ? ToObject(thisValue). // 4. If object is a platform object, then perform a security // check, passing: // 5. If object is not a default iterator object for interface, // then throw a TypeError. if (typeof this !== 'object' || this === null || !(#target in this)) { throw new TypeError( `'next' called on an object that does not implement interface ${name} Iterator.` ) } // 6. Let index be object’s index. // 7. Let kind be object’s kind. // 8. Let values be object’s target's value pairs to iterate over. const index = this.#index const values = this.#target[kInternalIterator] // 9. Let len be the length of values. const len = values.length // 10. If index is greater than or equal to len, then return // CreateIterResultObject(undefined, true). if (index >= len) { return { value: undefined, done: true } } // 11. Let pair be the entry in values at index index. const { [keyIndex]: key, [valueIndex]: value } = values[index] // 12. Set object’s index to index + 1. this.#index = index + 1 // 13. Return the iterator result for pair and kind. // https://webidl.spec.whatwg.org/#iterator-result // 1. Let result be a value determined by the value of kind: let result switch (this.#kind) { case 'key': // 1. Let idlKey be pair’s key. // 2. Let key be the result of converting idlKey to an // ECMAScript value. // 3. result is key. result = key break case 'value': // 1. Let idlValue be pair’s value. // 2. Let value be the result of converting idlValue to // an ECMAScript value. // 3. result is value. result = value break case 'key+value': // 1. Let idlKey be pair’s key. // 2. Let idlValue be pair’s value. // 3. Let key be the result of converting idlKey to an // ECMAScript value. // 4. Let value be the result of converting idlValue to // an ECMAScript value. // 5. Let array be ! ArrayCreate(2). // 6. Call ! CreateDataProperty(array, "0", key). // 7. Call ! CreateDataProperty(array, "1", value). // 8. result is array. result = [key, value] break } // 2. Return CreateIterResultObject(result, false). return { value: result, done: false } } } // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object // @ts-ignore delete FastIterableIterator.prototype.constructor Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype) Object.defineProperties(FastIterableIterator.prototype, { [Symbol.toStringTag]: { writable: false, enumerable: false, configurable: true, value: `${name} Iterator` }, next: { writable: true, enumerable: true, configurable: true } }) /** * @param {unknown} target * @param {'key' | 'value' | 'key+value'} kind * @returns {IterableIterator} */ return function (target, kind) { return new FastIterableIterator(target, kind) } } /** * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object * @param {string} name name of the instance * @param {any} object class * @param {symbol} kInternalIterator * @param {string | number} [keyIndex] * @param {string | number} [valueIndex] */ function iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex) const properties = { keys: { writable: true, enumerable: true, configurable: true, value: function keys () { webidl.brandCheck(this, object) return makeIterator(this, 'key') } }, values: { writable: true, enumerable: true, configurable: true, value: function values () { webidl.brandCheck(this, object) return makeIterator(this, 'value') } }, entries: { writable: true, enumerable: true, configurable: true, value: function entries () { webidl.brandCheck(this, object) return makeIterator(this, 'key+value') } }, forEach: { writable: true, enumerable: true, configurable: true, value: function forEach (callbackfn, thisArg = globalThis) { webidl.brandCheck(this, object) webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`) if (typeof callbackfn !== 'function') { throw new TypeError( `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.` ) } for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) { callbackfn.call(thisArg, value, key, this) } } } } return Object.defineProperties(object.prototype, { ...properties, [Symbol.iterator]: { writable: true, enumerable: false, configurable: true, value: properties.entries.value } }) } /** * @see https://fetch.spec.whatwg.org/#body-fully-read */ async function fullyReadBody (body, processBody, processBodyError) { // 1. If taskDestination is null, then set taskDestination to // the result of starting a new parallel queue. // 2. Let successSteps given a byte sequence bytes be to queue a // fetch task to run processBody given bytes, with taskDestination. const successSteps = processBody // 3. Let errorSteps be to queue a fetch task to run processBodyError, // with taskDestination. const errorSteps = processBodyError // 4. Let reader be the result of getting a reader for body’s stream. // If that threw an exception, then run errorSteps with that // exception and return. let reader try { reader = body.stream.getReader() } catch (e) { errorSteps(e) return } // 5. Read all bytes from reader, given successSteps and errorSteps. try { successSteps(await readAllBytes(reader)) } catch (e) { errorSteps(e) } } function isReadableStreamLike (stream) { return stream instanceof ReadableStream || ( stream[Symbol.toStringTag] === 'ReadableStream' && typeof stream.tee === 'function' ) } /** * @param {ReadableStreamController} controller */ function readableStreamClose (controller) { try { controller.close() controller.byobRequest?.respond(0) } catch (err) { // TODO: add comment explaining why this error occurs. if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) { throw err } } } const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/ // eslint-disable-line /** * @see https://infra.spec.whatwg.org/#isomorphic-encode * @param {string} input */ function isomorphicEncode (input) { // 1. Assert: input contains no code points greater than U+00FF. assert(!invalidIsomorphicEncodeValueRegex.test(input)) // 2. Return a byte sequence whose length is equal to input’s code // point length and whose bytes have the same values as the // values of input’s code points, in the same order return input } /** * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes * @see https://streams.spec.whatwg.org/#read-loop * @param {ReadableStreamDefaultReader} reader */ async function readAllBytes (reader) { const bytes = [] let byteLength = 0 while (true) { const { done, value: chunk } = await reader.read() if (done) { // 1. Call successSteps with bytes. return Buffer.concat(bytes, byteLength) } // 1. If chunk is not a Uint8Array object, call failureSteps // with a TypeError and abort these steps. if (!isUint8Array(chunk)) { throw new TypeError('Received non-Uint8Array chunk') } // 2. Append the bytes represented by chunk to bytes. bytes.push(chunk) byteLength += chunk.length // 3. Read-loop given reader, bytes, successSteps, and failureSteps. } } /** * @see https://fetch.spec.whatwg.org/#is-local * @param {URL} url */ function urlIsLocal (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' } /** * @param {string|URL} url * @returns {boolean} */ function urlHasHttpsScheme (url) { return ( ( typeof url === 'string' && url[5] === ':' && url[0] === 'h' && url[1] === 't' && url[2] === 't' && url[3] === 'p' && url[4] === 's' ) || url.protocol === 'https:' ) } /** * @see https://fetch.spec.whatwg.org/#http-scheme * @param {URL} url */ function urlIsHttpHttpsScheme (url) { assert('protocol' in url) // ensure it's a url object const protocol = url.protocol return protocol === 'http:' || protocol === 'https:' } /** * @see https://fetch.spec.whatwg.org/#simple-range-header-value * @param {string} value * @param {boolean} allowWhitespace */ function simpleRangeHeaderValue (value, allowWhitespace) { // 1. Let data be the isomorphic decoding of value. // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string, // nothing more. We obviously don't need to do that if value is a string already. const data = value // 2. If data does not start with "bytes", then return failure. if (!data.startsWith('bytes')) { return 'failure' } // 3. Let position be a position variable for data, initially pointing at the 5th code point of data. const position = { position: 5 } // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, // from data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 5. If the code point at position within data is not U+003D (=), then return failure. if (data.charCodeAt(position.position) !== 0x3D) { return 'failure' } // 6. Advance position by 1. position.position++ // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from // data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits, // from data given position. const rangeStart = collectASequenceOfCodePoints( (char) => { const code = char.charCodeAt(0) return code >= 0x30 && code <= 0x39 }, data, position ) // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the // empty string; otherwise null. const rangeStartValue = rangeStart.length ? Number(rangeStart) : null // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, // from data given position. if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 11. If the code point at position within data is not U+002D (-), then return failure. if (data.charCodeAt(position.position) !== 0x2D) { return 'failure' } // 12. Advance position by 1. position.position++ // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab // or space, from data given position. // Note from Khafra: its the same step as in #8 again lol if (allowWhitespace) { collectASequenceOfCodePoints( (char) => char === '\t' || char === ' ', data, position ) } // 14. Let rangeEnd be the result of collecting a sequence of code points that are // ASCII digits, from data given position. // Note from Khafra: you wouldn't guess it, but this is also the same step as #8 const rangeEnd = collectASequenceOfCodePoints( (char) => { const code = char.charCodeAt(0) return code >= 0x30 && code <= 0x39 }, data, position ) // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd // is not the empty string; otherwise null. // Note from Khafra: THE SAME STEP, AGAIN!!! // Note: why interpret as a decimal if we only collect ascii digits? const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null // 16. If position is not past the end of data, then return failure. if (position.position < data.length) { return 'failure' } // 17. If rangeEndValue and rangeStartValue are null, then return failure. if (rangeEndValue === null && rangeStartValue === null) { return 'failure' } // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is // greater than rangeEndValue, then return failure. // Note: ... when can they not be numbers? if (rangeStartValue > rangeEndValue) { return 'failure' } // 19. Return (rangeStartValue, rangeEndValue). return { rangeStartValue, rangeEndValue } } /** * @see https://fetch.spec.whatwg.org/#build-a-content-range * @param {number} rangeStart * @param {number} rangeEnd * @param {number} fullLength */ function buildContentRange (rangeStart, rangeEnd, fullLength) { // 1. Let contentRange be `bytes `. let contentRange = 'bytes ' // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange. contentRange += isomorphicEncode(`${rangeStart}`) // 3. Append 0x2D (-) to contentRange. contentRange += '-' // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange. contentRange += isomorphicEncode(`${rangeEnd}`) // 5. Append 0x2F (/) to contentRange. contentRange += '/' // 6. Append fullLength, serialized and isomorphic encoded to contentRange. contentRange += isomorphicEncode(`${fullLength}`) // 7. Return contentRange. return contentRange } // A Stream, which pipes the response to zlib.createInflate() or // zlib.createInflateRaw() depending on the first byte of the Buffer. // If the lower byte of the first byte is 0x08, then the stream is // interpreted as a zlib stream, otherwise it's interpreted as a // raw deflate stream. class InflateStream extends Transform { #zlibOptions /** @param {zlib.ZlibOptions} [zlibOptions] */ constructor (zlibOptions) { super() this.#zlibOptions = zlibOptions } _transform (chunk, encoding, callback) { if (!this._inflateStream) { if (chunk.length === 0) { callback() return } this._inflateStream = (chunk[0] & 0x0F) === 0x08 ? zlib.createInflate(this.#zlibOptions) : zlib.createInflateRaw(this.#zlibOptions) this._inflateStream.on('data', this.push.bind(this)) this._inflateStream.on('end', () => this.push(null)) this._inflateStream.on('error', (err) => this.destroy(err)) } this._inflateStream.write(chunk, encoding, callback) } _final (callback) { if (this._inflateStream) { this._inflateStream.end() this._inflateStream = null } callback() } } /** * @param {zlib.ZlibOptions} [zlibOptions] * @returns {InflateStream} */ function createInflate (zlibOptions) { return new InflateStream(zlibOptions) } /** * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type * @param {import('./headers').HeadersList} headers */ function extractMimeType (headers) { // 1. Let charset be null. let charset = null // 2. Let essence be null. let essence = null // 3. Let mimeType be null. let mimeType = null // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers. const values = getDecodeSplit('content-type', headers) // 5. If values is null, then return failure. if (values === null) { return 'failure' } // 6. For each value of values: for (const value of values) { // 6.1. Let temporaryMimeType be the result of parsing value. const temporaryMimeType = parseMIMEType(value) // 6.2. If temporaryMimeType is failure or its essence is "*/*", then continue. if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') { continue } // 6.3. Set mimeType to temporaryMimeType. mimeType = temporaryMimeType // 6.4. If mimeType’s essence is not essence, then: if (mimeType.essence !== essence) { // 6.4.1. Set charset to null. charset = null // 6.4.2. If mimeType’s parameters["charset"] exists, then set charset to // mimeType’s parameters["charset"]. if (mimeType.parameters.has('charset')) { charset = mimeType.parameters.get('charset') } // 6.4.3. Set essence to mimeType’s essence. essence = mimeType.essence } else if (!mimeType.parameters.has('charset') && charset !== null) { // 6.5. Otherwise, if mimeType’s parameters["charset"] does not exist, and // charset is non-null, set mimeType’s parameters["charset"] to charset. mimeType.parameters.set('charset', charset) } } // 7. If mimeType is null, then return failure. if (mimeType == null) { return 'failure' } // 8. Return mimeType. return mimeType } /** * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split * @param {string|null} value */ function gettingDecodingSplitting (value) { // 1. Let input be the result of isomorphic decoding value. const input = value // 2. Let position be a position variable for input, initially pointing at the start of input. const position = { position: 0 } // 3. Let values be a list of strings, initially empty. const values = [] // 4. Let temporaryValue be the empty string. let temporaryValue = '' // 5. While position is not past the end of input: while (position.position < input.length) { // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (") // or U+002C (,) from input, given position, to temporaryValue. temporaryValue += collectASequenceOfCodePoints( (char) => char !== '"' && char !== ',', input, position ) // 5.2. If position is not past the end of input, then: if (position.position < input.length) { // 5.2.1. If the code point at position within input is U+0022 ("), then: if (input.charCodeAt(position.position) === 0x22) { // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue. temporaryValue += collectAnHTTPQuotedString( input, position ) // 5.2.1.2. If position is not past the end of input, then continue. if (position.position < input.length) { continue } } else { // 5.2.2. Otherwise: // 5.2.2.1. Assert: the code point at position within input is U+002C (,). assert(input.charCodeAt(position.position) === 0x2C) // 5.2.2.2. Advance position by 1. position.position++ } } // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue. temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20) // 5.4. Append temporaryValue to values. values.push(temporaryValue) // 5.6. Set temporaryValue to the empty string. temporaryValue = '' } // 6. Return values. return values } /** * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split * @param {string} name lowercase header name * @param {import('./headers').HeadersList} list */ function getDecodeSplit (name, list) { // 1. Let value be the result of getting name from list. const value = list.get(name, true) // 2. If value is null, then return null. if (value === null) { return null } // 3. Return the result of getting, decoding, and splitting value. return gettingDecodingSplitting(value) } const textDecoder = new TextDecoder() /** * @see https://encoding.spec.whatwg.org/#utf-8-decode * @param {Buffer} buffer */ function utf8DecodeBytes (buffer) { if (buffer.length === 0) { return '' } // 1. Let buffer be the result of peeking three bytes from // ioQueue, converted to a byte sequence. // 2. If buffer is 0xEF 0xBB 0xBF, then read three // bytes from ioQueue. (Do nothing with those bytes.) if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { buffer = buffer.subarray(3) } // 3. Process a queue with an instance of UTF-8’s // decoder, ioQueue, output, and "replacement". const output = textDecoder.decode(buffer) // 4. Return output. return output } class EnvironmentSettingsObjectBase { get baseUrl () { return getGlobalOrigin() } get origin () { return this.baseUrl?.origin } policyContainer = makePolicyContainer() } class EnvironmentSettingsObject { settingsObject = new EnvironmentSettingsObjectBase() } const environmentSettingsObject = new EnvironmentSettingsObject() module.exports = { isAborted, isCancelled, isValidEncodedURL, createDeferredPromise, ReadableStreamFrom, tryUpgradeRequestToAPotentiallyTrustworthyURL, clampAndCoarsenConnectionTimingInfo, coarsenedSharedCurrentTime, determineRequestsReferrer, makePolicyContainer, clonePolicyContainer, appendFetchMetadata, appendRequestOriginHeader, TAOCheck, corsCheck, crossOriginResourcePolicyCheck, createOpaqueTimingInfo, setRequestReferrerPolicyOnRedirect, isValidHTTPToken, requestBadPort, requestCurrentURL, responseURL, responseLocationURL, isBlobLike, isURLPotentiallyTrustworthy, isValidReasonPhrase, sameOrigin, normalizeMethod, serializeJavascriptValueToJSONString, iteratorMixin, createIterator, isValidHeaderName, isValidHeaderValue, isErrorLike, fullyReadBody, bytesMatch, isReadableStreamLike, readableStreamClose, isomorphicEncode, urlIsLocal, urlHasHttpsScheme, urlIsHttpHttpsScheme, readAllBytes, simpleRangeHeaderValue, buildContentRange, parseMetadata, createInflate, extractMimeType, getDecodeSplit, utf8DecodeBytes, environmentSettingsObject } /***/ }), /***/ 5893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { types, inspect } = __nccwpck_require__(7975) const { markAsUncloneable } = __nccwpck_require__(5919) const { toUSVString } = __nccwpck_require__(3440) /** @type {import('../../../types/webidl').Webidl} */ const webidl = {} webidl.converters = {} webidl.util = {} webidl.errors = {} webidl.errors.exception = function (message) { return new TypeError(`${message.header}: ${message.message}`) } webidl.errors.conversionFailed = function (context) { const plural = context.types.length === 1 ? '' : ' one of' const message = `${context.argument} could not be converted to` + `${plural}: ${context.types.join(', ')}.` return webidl.errors.exception({ header: context.prefix, message }) } webidl.errors.invalidArgument = function (context) { return webidl.errors.exception({ header: context.prefix, message: `"${context.value}" is an invalid ${context.type}.` }) } // https://webidl.spec.whatwg.org/#implements webidl.brandCheck = function (V, I, opts) { if (opts?.strict !== false) { if (!(V instanceof I)) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } else { if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) { const err = new TypeError('Illegal invocation') err.code = 'ERR_INVALID_THIS' // node compat. throw err } } } webidl.argumentLengthCheck = function ({ length }, min, ctx) { if (length < min) { throw webidl.errors.exception({ message: `${min} argument${min !== 1 ? 's' : ''} required, ` + `but${length ? ' only' : ''} ${length} found.`, header: ctx }) } } webidl.illegalConstructor = function () { throw webidl.errors.exception({ header: 'TypeError', message: 'Illegal constructor' }) } // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values webidl.util.Type = function (V) { switch (typeof V) { case 'undefined': return 'Undefined' case 'boolean': return 'Boolean' case 'string': return 'String' case 'symbol': return 'Symbol' case 'number': return 'Number' case 'bigint': return 'BigInt' case 'function': case 'object': { if (V === null) { return 'Null' } return 'Object' } } } webidl.util.markAsUncloneable = markAsUncloneable || (() => {}) // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint webidl.util.ConvertToInt = function (V, bitLength, signedness, opts) { let upperBound let lowerBound // 1. If bitLength is 64, then: if (bitLength === 64) { // 1. Let upperBound be 2^53 − 1. upperBound = Math.pow(2, 53) - 1 // 2. If signedness is "unsigned", then let lowerBound be 0. if (signedness === 'unsigned') { lowerBound = 0 } else { // 3. Otherwise let lowerBound be −2^53 + 1. lowerBound = Math.pow(-2, 53) + 1 } } else if (signedness === 'unsigned') { // 2. Otherwise, if signedness is "unsigned", then: // 1. Let lowerBound be 0. lowerBound = 0 // 2. Let upperBound be 2^bitLength − 1. upperBound = Math.pow(2, bitLength) - 1 } else { // 3. Otherwise: // 1. Let lowerBound be -2^bitLength − 1. lowerBound = Math.pow(-2, bitLength) - 1 // 2. Let upperBound be 2^bitLength − 1 − 1. upperBound = Math.pow(2, bitLength - 1) - 1 } // 4. Let x be ? ToNumber(V). let x = Number(V) // 5. If x is −0, then set x to +0. if (x === 0) { x = 0 } // 6. If the conversion is to an IDL type associated // with the [EnforceRange] extended attribute, then: if (opts?.enforceRange === true) { // 1. If x is NaN, +∞, or −∞, then throw a TypeError. if ( Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Could not convert ${webidl.util.Stringify(V)} to an integer.` }) } // 2. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 3. If x < lowerBound or x > upperBound, then // throw a TypeError. if (x < lowerBound || x > upperBound) { throw webidl.errors.exception({ header: 'Integer conversion', message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` }) } // 4. Return x. return x } // 7. If x is not NaN and the conversion is to an IDL // type associated with the [Clamp] extended // attribute, then: if (!Number.isNaN(x) && opts?.clamp === true) { // 1. Set x to min(max(x, lowerBound), upperBound). x = Math.min(Math.max(x, lowerBound), upperBound) // 2. Round x to the nearest integer, choosing the // even integer if it lies halfway between two, // and choosing +0 rather than −0. if (Math.floor(x) % 2 === 0) { x = Math.floor(x) } else { x = Math.ceil(x) } // 3. Return x. return x } // 8. If x is NaN, +0, +∞, or −∞, then return +0. if ( Number.isNaN(x) || (x === 0 && Object.is(0, x)) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY ) { return 0 } // 9. Set x to IntegerPart(x). x = webidl.util.IntegerPart(x) // 10. Set x to x modulo 2^bitLength. x = x % Math.pow(2, bitLength) // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, // then return x − 2^bitLength. if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { return x - Math.pow(2, bitLength) } // 12. Otherwise, return x. return x } // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart webidl.util.IntegerPart = function (n) { // 1. Let r be floor(abs(n)). const r = Math.floor(Math.abs(n)) // 2. If n < 0, then return -1 × r. if (n < 0) { return -1 * r } // 3. Otherwise, return r. return r } webidl.util.Stringify = function (V) { const type = webidl.util.Type(V) switch (type) { case 'Symbol': return `Symbol(${V.description})` case 'Object': return inspect(V) case 'String': return `"${V}"` default: return `${V}` } } // https://webidl.spec.whatwg.org/#es-sequence webidl.sequenceConverter = function (converter) { return (V, prefix, argument, Iterable) => { // 1. If Type(V) is not Object, throw a TypeError. if (webidl.util.Type(V) !== 'Object') { throw webidl.errors.exception({ header: prefix, message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.` }) } // 2. Let method be ? GetMethod(V, @@iterator). /** @type {Generator} */ const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.() const seq = [] let index = 0 // 3. If method is undefined, throw a TypeError. if ( method === undefined || typeof method.next !== 'function' ) { throw webidl.errors.exception({ header: prefix, message: `${argument} is not iterable.` }) } // https://webidl.spec.whatwg.org/#create-sequence-from-iterable while (true) { const { done, value } = method.next() if (done) { break } seq.push(converter(value, prefix, `${argument}[${index++}]`)) } return seq } } // https://webidl.spec.whatwg.org/#es-to-record webidl.recordConverter = function (keyConverter, valueConverter) { return (O, prefix, argument) => { // 1. If Type(O) is not Object, throw a TypeError. if (webidl.util.Type(O) !== 'Object') { throw webidl.errors.exception({ header: prefix, message: `${argument} ("${webidl.util.Type(O)}") is not an Object.` }) } // 2. Let result be a new empty instance of record. const result = {} if (!types.isProxy(O)) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)] for (const key of keys) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, argument) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, argument) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } // 5. Return result. return result } // 3. Let keys be ? O.[[OwnPropertyKeys]](). const keys = Reflect.ownKeys(O) // 4. For each key of keys. for (const key of keys) { // 1. Let desc be ? O.[[GetOwnProperty]](key). const desc = Reflect.getOwnPropertyDescriptor(O, key) // 2. If desc is not undefined and desc.[[Enumerable]] is true: if (desc?.enumerable) { // 1. Let typedKey be key converted to an IDL value of type K. const typedKey = keyConverter(key, prefix, argument) // 2. Let value be ? Get(O, key). // 3. Let typedValue be value converted to an IDL value of type V. const typedValue = valueConverter(O[key], prefix, argument) // 4. Set result[typedKey] to typedValue. result[typedKey] = typedValue } } // 5. Return result. return result } } webidl.interfaceConverter = function (i) { return (V, prefix, argument, opts) => { if (opts?.strict !== false && !(V instanceof i)) { throw webidl.errors.exception({ header: prefix, message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${i.name}.` }) } return V } } webidl.dictionaryConverter = function (converters) { return (dictionary, prefix, argument) => { const type = webidl.util.Type(dictionary) const dict = {} if (type === 'Null' || type === 'Undefined') { return dict } else if (type !== 'Object') { throw webidl.errors.exception({ header: prefix, message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` }) } for (const options of converters) { const { key, defaultValue, required, converter } = options if (required === true) { if (!Object.hasOwn(dictionary, key)) { throw webidl.errors.exception({ header: prefix, message: `Missing required key "${key}".` }) } } let value = dictionary[key] const hasDefault = Object.hasOwn(options, 'defaultValue') // Only use defaultValue if value is undefined and // a defaultValue options was provided. if (hasDefault && value !== null) { value ??= defaultValue() } // A key can be optional and have no default value. // When this happens, do not perform a conversion, // and do not assign the key a value. if (required || hasDefault || value !== undefined) { value = converter(value, prefix, `${argument}.${key}`) if ( options.allowedValues && !options.allowedValues.includes(value) ) { throw webidl.errors.exception({ header: prefix, message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` }) } dict[key] = value } } return dict } } webidl.nullableConverter = function (converter) { return (V, prefix, argument) => { if (V === null) { return V } return converter(V, prefix, argument) } } // https://webidl.spec.whatwg.org/#es-DOMString webidl.converters.DOMString = function (V, prefix, argument, opts) { // 1. If V is null and the conversion is to an IDL type // associated with the [LegacyNullToEmptyString] // extended attribute, then return the DOMString value // that represents the empty string. if (V === null && opts?.legacyNullToEmptyString) { return '' } // 2. Let x be ? ToString(V). if (typeof V === 'symbol') { throw webidl.errors.exception({ header: prefix, message: `${argument} is a symbol, which cannot be converted to a DOMString.` }) } // 3. Return the IDL DOMString value that represents the // same sequence of code units as the one the // ECMAScript String value x represents. return String(V) } // https://webidl.spec.whatwg.org/#es-ByteString webidl.converters.ByteString = function (V, prefix, argument) { // 1. Let x be ? ToString(V). // Note: DOMString converter perform ? ToString(V) const x = webidl.converters.DOMString(V, prefix, argument) // 2. If the value of any element of x is greater than // 255, then throw a TypeError. for (let index = 0; index < x.length; index++) { if (x.charCodeAt(index) > 255) { throw new TypeError( 'Cannot convert argument to a ByteString because the character at ' + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` ) } } // 3. Return an IDL ByteString value whose length is the // length of x, and where the value of each element is // the value of the corresponding element of x. return x } // https://webidl.spec.whatwg.org/#es-USVString // TODO: rewrite this so we can control the errors thrown webidl.converters.USVString = toUSVString // https://webidl.spec.whatwg.org/#es-boolean webidl.converters.boolean = function (V) { // 1. Let x be the result of computing ToBoolean(V). const x = Boolean(V) // 2. Return the IDL boolean value that is the one that represents // the same truth value as the ECMAScript Boolean value x. return x } // https://webidl.spec.whatwg.org/#es-any webidl.converters.any = function (V) { return V } // https://webidl.spec.whatwg.org/#es-long-long webidl.converters['long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "signed"). const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument) // 2. Return the IDL long long value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long-long webidl.converters['unsigned long long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument) // 2. Return the IDL unsigned long long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-long webidl.converters['unsigned long'] = function (V, prefix, argument) { // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument) // 2. Return the IDL unsigned long value that // represents the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#es-unsigned-short webidl.converters['unsigned short'] = function (V, prefix, argument, opts) { // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument) // 2. Return the IDL unsigned short value that represents // the same numeric value as x. return x } // https://webidl.spec.whatwg.org/#idl-ArrayBuffer webidl.converters.ArrayBuffer = function (V, prefix, argument, opts) { // 1. If Type(V) is not Object, or V does not have an // [[ArrayBufferData]] internal slot, then throw a // TypeError. // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances if ( webidl.util.Type(V) !== 'Object' || !types.isAnyArrayBuffer(V) ) { throw webidl.errors.conversionFailed({ prefix, argument: `${argument} ("${webidl.util.Stringify(V)}")`, types: ['ArrayBuffer'] }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V) is true, then throw a // TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V) is true, then throw a // TypeError. if (V.resizable || V.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 4. Return the IDL ArrayBuffer value that is a // reference to the same object as V. return V } webidl.converters.TypedArray = function (V, T, prefix, name, opts) { // 1. Let T be the IDL type V is being converted to. // 2. If Type(V) is not Object, or V does not have a // [[TypedArrayName]] internal slot with a value // equal to T’s name, then throw a TypeError. if ( webidl.util.Type(V) !== 'Object' || !types.isTypedArray(V) || V.constructor.name !== T.name ) { throw webidl.errors.conversionFailed({ prefix, argument: `${name} ("${webidl.util.Stringify(V)}")`, types: [T.name] }) } // 3. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 4. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (V.buffer.resizable || V.buffer.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 5. Return the IDL value of type T that is a reference // to the same object as V. return V } webidl.converters.DataView = function (V, prefix, name, opts) { // 1. If Type(V) is not Object, or V does not have a // [[DataView]] internal slot, then throw a TypeError. if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { throw webidl.errors.exception({ header: prefix, message: `${name} is not a DataView.` }) } // 2. If the conversion is not to an IDL type associated // with the [AllowShared] extended attribute, and // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, // then throw a TypeError. if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'SharedArrayBuffer is not allowed.' }) } // 3. If the conversion is not to an IDL type associated // with the [AllowResizable] extended attribute, and // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is // true, then throw a TypeError. if (V.buffer.resizable || V.buffer.growable) { throw webidl.errors.exception({ header: 'ArrayBuffer', message: 'Received a resizable ArrayBuffer.' }) } // 4. Return the IDL DataView value that is a reference // to the same object as V. return V } // https://webidl.spec.whatwg.org/#BufferSource webidl.converters.BufferSource = function (V, prefix, name, opts) { if (types.isAnyArrayBuffer(V)) { return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false }) } if (types.isTypedArray(V)) { return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false }) } if (types.isDataView(V)) { return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false }) } throw webidl.errors.conversionFailed({ prefix, argument: `${name} ("${webidl.util.Stringify(V)}")`, types: ['BufferSource'] }) } webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.ByteString ) webidl.converters['sequence>'] = webidl.sequenceConverter( webidl.converters['sequence'] ) webidl.converters['record'] = webidl.recordConverter( webidl.converters.ByteString, webidl.converters.ByteString ) module.exports = { webidl } /***/ }), /***/ 2607: /***/ ((module) => { /** * @see https://encoding.spec.whatwg.org/#concept-encoding-get * @param {string|undefined} label */ function getEncoding (label) { if (!label) { return 'failure' } // 1. Remove any leading and trailing ASCII whitespace from label. // 2. If label is an ASCII case-insensitive match for any of the // labels listed in the table below, then return the // corresponding encoding; otherwise return failure. switch (label.trim().toLowerCase()) { case 'unicode-1-1-utf-8': case 'unicode11utf8': case 'unicode20utf8': case 'utf-8': case 'utf8': case 'x-unicode20utf8': return 'UTF-8' case '866': case 'cp866': case 'csibm866': case 'ibm866': return 'IBM866' case 'csisolatin2': case 'iso-8859-2': case 'iso-ir-101': case 'iso8859-2': case 'iso88592': case 'iso_8859-2': case 'iso_8859-2:1987': case 'l2': case 'latin2': return 'ISO-8859-2' case 'csisolatin3': case 'iso-8859-3': case 'iso-ir-109': case 'iso8859-3': case 'iso88593': case 'iso_8859-3': case 'iso_8859-3:1988': case 'l3': case 'latin3': return 'ISO-8859-3' case 'csisolatin4': case 'iso-8859-4': case 'iso-ir-110': case 'iso8859-4': case 'iso88594': case 'iso_8859-4': case 'iso_8859-4:1988': case 'l4': case 'latin4': return 'ISO-8859-4' case 'csisolatincyrillic': case 'cyrillic': case 'iso-8859-5': case 'iso-ir-144': case 'iso8859-5': case 'iso88595': case 'iso_8859-5': case 'iso_8859-5:1988': return 'ISO-8859-5' case 'arabic': case 'asmo-708': case 'csiso88596e': case 'csiso88596i': case 'csisolatinarabic': case 'ecma-114': case 'iso-8859-6': case 'iso-8859-6-e': case 'iso-8859-6-i': case 'iso-ir-127': case 'iso8859-6': case 'iso88596': case 'iso_8859-6': case 'iso_8859-6:1987': return 'ISO-8859-6' case 'csisolatingreek': case 'ecma-118': case 'elot_928': case 'greek': case 'greek8': case 'iso-8859-7': case 'iso-ir-126': case 'iso8859-7': case 'iso88597': case 'iso_8859-7': case 'iso_8859-7:1987': case 'sun_eu_greek': return 'ISO-8859-7' case 'csiso88598e': case 'csisolatinhebrew': case 'hebrew': case 'iso-8859-8': case 'iso-8859-8-e': case 'iso-ir-138': case 'iso8859-8': case 'iso88598': case 'iso_8859-8': case 'iso_8859-8:1988': case 'visual': return 'ISO-8859-8' case 'csiso88598i': case 'iso-8859-8-i': case 'logical': return 'ISO-8859-8-I' case 'csisolatin6': case 'iso-8859-10': case 'iso-ir-157': case 'iso8859-10': case 'iso885910': case 'l6': case 'latin6': return 'ISO-8859-10' case 'iso-8859-13': case 'iso8859-13': case 'iso885913': return 'ISO-8859-13' case 'iso-8859-14': case 'iso8859-14': case 'iso885914': return 'ISO-8859-14' case 'csisolatin9': case 'iso-8859-15': case 'iso8859-15': case 'iso885915': case 'iso_8859-15': case 'l9': return 'ISO-8859-15' case 'iso-8859-16': return 'ISO-8859-16' case 'cskoi8r': case 'koi': case 'koi8': case 'koi8-r': case 'koi8_r': return 'KOI8-R' case 'koi8-ru': case 'koi8-u': return 'KOI8-U' case 'csmacintosh': case 'mac': case 'macintosh': case 'x-mac-roman': return 'macintosh' case 'iso-8859-11': case 'iso8859-11': case 'iso885911': case 'tis-620': case 'windows-874': return 'windows-874' case 'cp1250': case 'windows-1250': case 'x-cp1250': return 'windows-1250' case 'cp1251': case 'windows-1251': case 'x-cp1251': return 'windows-1251' case 'ansi_x3.4-1968': case 'ascii': case 'cp1252': case 'cp819': case 'csisolatin1': case 'ibm819': case 'iso-8859-1': case 'iso-ir-100': case 'iso8859-1': case 'iso88591': case 'iso_8859-1': case 'iso_8859-1:1987': case 'l1': case 'latin1': case 'us-ascii': case 'windows-1252': case 'x-cp1252': return 'windows-1252' case 'cp1253': case 'windows-1253': case 'x-cp1253': return 'windows-1253' case 'cp1254': case 'csisolatin5': case 'iso-8859-9': case 'iso-ir-148': case 'iso8859-9': case 'iso88599': case 'iso_8859-9': case 'iso_8859-9:1989': case 'l5': case 'latin5': case 'windows-1254': case 'x-cp1254': return 'windows-1254' case 'cp1255': case 'windows-1255': case 'x-cp1255': return 'windows-1255' case 'cp1256': case 'windows-1256': case 'x-cp1256': return 'windows-1256' case 'cp1257': case 'windows-1257': case 'x-cp1257': return 'windows-1257' case 'cp1258': case 'windows-1258': case 'x-cp1258': return 'windows-1258' case 'x-mac-cyrillic': case 'x-mac-ukrainian': return 'x-mac-cyrillic' case 'chinese': case 'csgb2312': case 'csiso58gb231280': case 'gb2312': case 'gb_2312': case 'gb_2312-80': case 'gbk': case 'iso-ir-58': case 'x-gbk': return 'GBK' case 'gb18030': return 'gb18030' case 'big5': case 'big5-hkscs': case 'cn-big5': case 'csbig5': case 'x-x-big5': return 'Big5' case 'cseucpkdfmtjapanese': case 'euc-jp': case 'x-euc-jp': return 'EUC-JP' case 'csiso2022jp': case 'iso-2022-jp': return 'ISO-2022-JP' case 'csshiftjis': case 'ms932': case 'ms_kanji': case 'shift-jis': case 'shift_jis': case 'sjis': case 'windows-31j': case 'x-sjis': return 'Shift_JIS' case 'cseuckr': case 'csksc56011987': case 'euc-kr': case 'iso-ir-149': case 'korean': case 'ks_c_5601-1987': case 'ks_c_5601-1989': case 'ksc5601': case 'ksc_5601': case 'windows-949': return 'EUC-KR' case 'csiso2022kr': case 'hz-gb-2312': case 'iso-2022-cn': case 'iso-2022-cn-ext': case 'iso-2022-kr': case 'replacement': return 'replacement' case 'unicodefffe': case 'utf-16be': return 'UTF-16BE' case 'csunicode': case 'iso-10646-ucs-2': case 'ucs-2': case 'unicode': case 'unicodefeff': case 'utf-16': case 'utf-16le': return 'UTF-16LE' case 'x-user-defined': return 'x-user-defined' default: return 'failure' } } module.exports = { getEncoding } /***/ }), /***/ 8355: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { staticPropertyDescriptors, readOperation, fireAProgressEvent } = __nccwpck_require__(3610) const { kState, kError, kResult, kEvents, kAborted } = __nccwpck_require__(961) const { webidl } = __nccwpck_require__(5893) const { kEnumerableProperty } = __nccwpck_require__(3440) class FileReader extends EventTarget { constructor () { super() this[kState] = 'empty' this[kResult] = null this[kError] = null this[kEvents] = { loadend: null, error: null, abort: null, load: null, progress: null, loadstart: null } } /** * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer * @param {import('buffer').Blob} blob */ readAsArrayBuffer (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer') blob = webidl.converters.Blob(blob, { strict: false }) // The readAsArrayBuffer(blob) method, when invoked, // must initiate a read operation for blob with ArrayBuffer. readOperation(this, blob, 'ArrayBuffer') } /** * @see https://w3c.github.io/FileAPI/#readAsBinaryString * @param {import('buffer').Blob} blob */ readAsBinaryString (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString') blob = webidl.converters.Blob(blob, { strict: false }) // The readAsBinaryString(blob) method, when invoked, // must initiate a read operation for blob with BinaryString. readOperation(this, blob, 'BinaryString') } /** * @see https://w3c.github.io/FileAPI/#readAsDataText * @param {import('buffer').Blob} blob * @param {string?} encoding */ readAsText (blob, encoding = undefined) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText') blob = webidl.converters.Blob(blob, { strict: false }) if (encoding !== undefined) { encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding') } // The readAsText(blob, encoding) method, when invoked, // must initiate a read operation for blob with Text and encoding. readOperation(this, blob, 'Text', encoding) } /** * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL * @param {import('buffer').Blob} blob */ readAsDataURL (blob) { webidl.brandCheck(this, FileReader) webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL') blob = webidl.converters.Blob(blob, { strict: false }) // The readAsDataURL(blob) method, when invoked, must // initiate a read operation for blob with DataURL. readOperation(this, blob, 'DataURL') } /** * @see https://w3c.github.io/FileAPI/#dfn-abort */ abort () { // 1. If this's state is "empty" or if this's state is // "done" set this's result to null and terminate // this algorithm. if (this[kState] === 'empty' || this[kState] === 'done') { this[kResult] = null return } // 2. If this's state is "loading" set this's state to // "done" and set this's result to null. if (this[kState] === 'loading') { this[kState] = 'done' this[kResult] = null } // 3. If there are any tasks from this on the file reading // task source in an affiliated task queue, then remove // those tasks from that task queue. this[kAborted] = true // 4. Terminate the algorithm for the read method being processed. // TODO // 5. Fire a progress event called abort at this. fireAProgressEvent('abort', this) // 6. If this's state is not "loading", fire a progress // event called loadend at this. if (this[kState] !== 'loading') { fireAProgressEvent('loadend', this) } } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate */ get readyState () { webidl.brandCheck(this, FileReader) switch (this[kState]) { case 'empty': return this.EMPTY case 'loading': return this.LOADING case 'done': return this.DONE } } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-result */ get result () { webidl.brandCheck(this, FileReader) // The result attribute’s getter, when invoked, must return // this's result. return this[kResult] } /** * @see https://w3c.github.io/FileAPI/#dom-filereader-error */ get error () { webidl.brandCheck(this, FileReader) // The error attribute’s getter, when invoked, must return // this's error. return this[kError] } get onloadend () { webidl.brandCheck(this, FileReader) return this[kEvents].loadend } set onloadend (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].loadend) { this.removeEventListener('loadend', this[kEvents].loadend) } if (typeof fn === 'function') { this[kEvents].loadend = fn this.addEventListener('loadend', fn) } else { this[kEvents].loadend = null } } get onerror () { webidl.brandCheck(this, FileReader) return this[kEvents].error } set onerror (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].error) { this.removeEventListener('error', this[kEvents].error) } if (typeof fn === 'function') { this[kEvents].error = fn this.addEventListener('error', fn) } else { this[kEvents].error = null } } get onloadstart () { webidl.brandCheck(this, FileReader) return this[kEvents].loadstart } set onloadstart (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].loadstart) { this.removeEventListener('loadstart', this[kEvents].loadstart) } if (typeof fn === 'function') { this[kEvents].loadstart = fn this.addEventListener('loadstart', fn) } else { this[kEvents].loadstart = null } } get onprogress () { webidl.brandCheck(this, FileReader) return this[kEvents].progress } set onprogress (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].progress) { this.removeEventListener('progress', this[kEvents].progress) } if (typeof fn === 'function') { this[kEvents].progress = fn this.addEventListener('progress', fn) } else { this[kEvents].progress = null } } get onload () { webidl.brandCheck(this, FileReader) return this[kEvents].load } set onload (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].load) { this.removeEventListener('load', this[kEvents].load) } if (typeof fn === 'function') { this[kEvents].load = fn this.addEventListener('load', fn) } else { this[kEvents].load = null } } get onabort () { webidl.brandCheck(this, FileReader) return this[kEvents].abort } set onabort (fn) { webidl.brandCheck(this, FileReader) if (this[kEvents].abort) { this.removeEventListener('abort', this[kEvents].abort) } if (typeof fn === 'function') { this[kEvents].abort = fn this.addEventListener('abort', fn) } else { this[kEvents].abort = null } } } // https://w3c.github.io/FileAPI/#dom-filereader-empty FileReader.EMPTY = FileReader.prototype.EMPTY = 0 // https://w3c.github.io/FileAPI/#dom-filereader-loading FileReader.LOADING = FileReader.prototype.LOADING = 1 // https://w3c.github.io/FileAPI/#dom-filereader-done FileReader.DONE = FileReader.prototype.DONE = 2 Object.defineProperties(FileReader.prototype, { EMPTY: staticPropertyDescriptors, LOADING: staticPropertyDescriptors, DONE: staticPropertyDescriptors, readAsArrayBuffer: kEnumerableProperty, readAsBinaryString: kEnumerableProperty, readAsText: kEnumerableProperty, readAsDataURL: kEnumerableProperty, abort: kEnumerableProperty, readyState: kEnumerableProperty, result: kEnumerableProperty, error: kEnumerableProperty, onloadstart: kEnumerableProperty, onprogress: kEnumerableProperty, onload: kEnumerableProperty, onabort: kEnumerableProperty, onerror: kEnumerableProperty, onloadend: kEnumerableProperty, [Symbol.toStringTag]: { value: 'FileReader', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(FileReader, { EMPTY: staticPropertyDescriptors, LOADING: staticPropertyDescriptors, DONE: staticPropertyDescriptors }) module.exports = { FileReader } /***/ }), /***/ 8573: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { webidl } = __nccwpck_require__(5893) const kState = Symbol('ProgressEvent state') /** * @see https://xhr.spec.whatwg.org/#progressevent */ class ProgressEvent extends Event { constructor (type, eventInitDict = {}) { type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type') eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) super(type, eventInitDict) this[kState] = { lengthComputable: eventInitDict.lengthComputable, loaded: eventInitDict.loaded, total: eventInitDict.total } } get lengthComputable () { webidl.brandCheck(this, ProgressEvent) return this[kState].lengthComputable } get loaded () { webidl.brandCheck(this, ProgressEvent) return this[kState].loaded } get total () { webidl.brandCheck(this, ProgressEvent) return this[kState].total } } webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ { key: 'lengthComputable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'loaded', converter: webidl.converters['unsigned long long'], defaultValue: () => 0 }, { key: 'total', converter: webidl.converters['unsigned long long'], defaultValue: () => 0 }, { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: () => false } ]) module.exports = { ProgressEvent } /***/ }), /***/ 961: /***/ ((module) => { module.exports = { kState: Symbol('FileReader state'), kResult: Symbol('FileReader result'), kError: Symbol('FileReader error'), kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), kEvents: Symbol('FileReader events'), kAborted: Symbol('FileReader aborted') } /***/ }), /***/ 3610: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kState, kError, kResult, kAborted, kLastProgressEventFired } = __nccwpck_require__(961) const { ProgressEvent } = __nccwpck_require__(8573) const { getEncoding } = __nccwpck_require__(2607) const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(1900) const { types } = __nccwpck_require__(7975) const { StringDecoder } = __nccwpck_require__(3193) const { btoa } = __nccwpck_require__(4573) /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } /** * @see https://w3c.github.io/FileAPI/#readOperation * @param {import('./filereader').FileReader} fr * @param {import('buffer').Blob} blob * @param {string} type * @param {string?} encodingName */ function readOperation (fr, blob, type, encodingName) { // 1. If fr’s state is "loading", throw an InvalidStateError // DOMException. if (fr[kState] === 'loading') { throw new DOMException('Invalid state', 'InvalidStateError') } // 2. Set fr’s state to "loading". fr[kState] = 'loading' // 3. Set fr’s result to null. fr[kResult] = null // 4. Set fr’s error to null. fr[kError] = null // 5. Let stream be the result of calling get stream on blob. /** @type {import('stream/web').ReadableStream} */ const stream = blob.stream() // 6. Let reader be the result of getting a reader from stream. const reader = stream.getReader() // 7. Let bytes be an empty byte sequence. /** @type {Uint8Array[]} */ const bytes = [] // 8. Let chunkPromise be the result of reading a chunk from // stream with reader. let chunkPromise = reader.read() // 9. Let isFirstChunk be true. let isFirstChunk = true // 10. In parallel, while true: // Note: "In parallel" just means non-blocking // Note 2: readOperation itself cannot be async as double // reading the body would then reject the promise, instead // of throwing an error. ;(async () => { while (!fr[kAborted]) { // 1. Wait for chunkPromise to be fulfilled or rejected. try { const { done, value } = await chunkPromise // 2. If chunkPromise is fulfilled, and isFirstChunk is // true, queue a task to fire a progress event called // loadstart at fr. if (isFirstChunk && !fr[kAborted]) { queueMicrotask(() => { fireAProgressEvent('loadstart', fr) }) } // 3. Set isFirstChunk to false. isFirstChunk = false // 4. If chunkPromise is fulfilled with an object whose // done property is false and whose value property is // a Uint8Array object, run these steps: if (!done && types.isUint8Array(value)) { // 1. Let bs be the byte sequence represented by the // Uint8Array object. // 2. Append bs to bytes. bytes.push(value) // 3. If roughly 50ms have passed since these steps // were last invoked, queue a task to fire a // progress event called progress at fr. if ( ( fr[kLastProgressEventFired] === undefined || Date.now() - fr[kLastProgressEventFired] >= 50 ) && !fr[kAborted] ) { fr[kLastProgressEventFired] = Date.now() queueMicrotask(() => { fireAProgressEvent('progress', fr) }) } // 4. Set chunkPromise to the result of reading a // chunk from stream with reader. chunkPromise = reader.read() } else if (done) { // 5. Otherwise, if chunkPromise is fulfilled with an // object whose done property is true, queue a task // to run the following steps and abort this algorithm: queueMicrotask(() => { // 1. Set fr’s state to "done". fr[kState] = 'done' // 2. Let result be the result of package data given // bytes, type, blob’s type, and encodingName. try { const result = packageData(bytes, type, blob.type, encodingName) // 4. Else: if (fr[kAborted]) { return } // 1. Set fr’s result to result. fr[kResult] = result // 2. Fire a progress event called load at the fr. fireAProgressEvent('load', fr) } catch (error) { // 3. If package data threw an exception error: // 1. Set fr’s error to error. fr[kError] = error // 2. Fire a progress event called error at fr. fireAProgressEvent('error', fr) } // 5. If fr’s state is not "loading", fire a progress // event called loadend at the fr. if (fr[kState] !== 'loading') { fireAProgressEvent('loadend', fr) } }) break } } catch (error) { if (fr[kAborted]) { return } // 6. Otherwise, if chunkPromise is rejected with an // error error, queue a task to run the following // steps and abort this algorithm: queueMicrotask(() => { // 1. Set fr’s state to "done". fr[kState] = 'done' // 2. Set fr’s error to error. fr[kError] = error // 3. Fire a progress event called error at fr. fireAProgressEvent('error', fr) // 4. If fr’s state is not "loading", fire a progress // event called loadend at fr. if (fr[kState] !== 'loading') { fireAProgressEvent('loadend', fr) } }) break } } })() } /** * @see https://w3c.github.io/FileAPI/#fire-a-progress-event * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e The name of the event * @param {import('./filereader').FileReader} reader */ function fireAProgressEvent (e, reader) { // The progress event e does not bubble. e.bubbles must be false // The progress event e is NOT cancelable. e.cancelable must be false const event = new ProgressEvent(e, { bubbles: false, cancelable: false }) reader.dispatchEvent(event) } /** * @see https://w3c.github.io/FileAPI/#blob-package-data * @param {Uint8Array[]} bytes * @param {string} type * @param {string?} mimeType * @param {string?} encodingName */ function packageData (bytes, type, mimeType, encodingName) { // 1. A Blob has an associated package data algorithm, given // bytes, a type, a optional mimeType, and a optional // encodingName, which switches on type and runs the // associated steps: switch (type) { case 'DataURL': { // 1. Return bytes as a DataURL [RFC2397] subject to // the considerations below: // * Use mimeType as part of the Data URL if it is // available in keeping with the Data URL // specification [RFC2397]. // * If mimeType is not available return a Data URL // without a media-type. [RFC2397]. // https://datatracker.ietf.org/doc/html/rfc2397#section-3 // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data // mediatype := [ type "/" subtype ] *( ";" parameter ) // data := *urlchar // parameter := attribute "=" value let dataURL = 'data:' const parsed = parseMIMEType(mimeType || 'application/octet-stream') if (parsed !== 'failure') { dataURL += serializeAMimeType(parsed) } dataURL += ';base64,' const decoder = new StringDecoder('latin1') for (const chunk of bytes) { dataURL += btoa(decoder.write(chunk)) } dataURL += btoa(decoder.end()) return dataURL } case 'Text': { // 1. Let encoding be failure let encoding = 'failure' // 2. If the encodingName is present, set encoding to the // result of getting an encoding from encodingName. if (encodingName) { encoding = getEncoding(encodingName) } // 3. If encoding is failure, and mimeType is present: if (encoding === 'failure' && mimeType) { // 1. Let type be the result of parse a MIME type // given mimeType. const type = parseMIMEType(mimeType) // 2. If type is not failure, set encoding to the result // of getting an encoding from type’s parameters["charset"]. if (type !== 'failure') { encoding = getEncoding(type.parameters.get('charset')) } } // 4. If encoding is failure, then set encoding to UTF-8. if (encoding === 'failure') { encoding = 'UTF-8' } // 5. Decode bytes using fallback encoding encoding, and // return the result. return decode(bytes, encoding) } case 'ArrayBuffer': { // Return a new ArrayBuffer whose contents are bytes. const sequence = combineByteSequences(bytes) return sequence.buffer } case 'BinaryString': { // Return bytes as a binary string, in which every byte // is represented by a code unit of equal value [0..255]. let binaryString = '' const decoder = new StringDecoder('latin1') for (const chunk of bytes) { binaryString += decoder.write(chunk) } binaryString += decoder.end() return binaryString } } } /** * @see https://encoding.spec.whatwg.org/#decode * @param {Uint8Array[]} ioQueue * @param {string} encoding */ function decode (ioQueue, encoding) { const bytes = combineByteSequences(ioQueue) // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. const BOMEncoding = BOMSniffing(bytes) let slice = 0 // 2. If BOMEncoding is non-null: if (BOMEncoding !== null) { // 1. Set encoding to BOMEncoding. encoding = BOMEncoding // 2. Read three bytes from ioQueue, if BOMEncoding is // UTF-8; otherwise read two bytes. // (Do nothing with those bytes.) slice = BOMEncoding === 'UTF-8' ? 3 : 2 } // 3. Process a queue with an instance of encoding’s // decoder, ioQueue, output, and "replacement". // 4. Return output. const sliced = bytes.slice(slice) return new TextDecoder(encoding).decode(sliced) } /** * @see https://encoding.spec.whatwg.org/#bom-sniff * @param {Uint8Array} ioQueue */ function BOMSniffing (ioQueue) { // 1. Let BOM be the result of peeking 3 bytes from ioQueue, // converted to a byte sequence. const [a, b, c] = ioQueue // 2. For each of the rows in the table below, starting with // the first one and going down, if BOM starts with the // bytes given in the first column, then return the // encoding given in the cell in the second column of that // row. Otherwise, return null. if (a === 0xEF && b === 0xBB && c === 0xBF) { return 'UTF-8' } else if (a === 0xFE && b === 0xFF) { return 'UTF-16BE' } else if (a === 0xFF && b === 0xFE) { return 'UTF-16LE' } return null } /** * @param {Uint8Array[]} sequences */ function combineByteSequences (sequences) { const size = sequences.reduce((a, b) => { return a + b.byteLength }, 0) let offset = 0 return sequences.reduce((a, b) => { a.set(b, offset) offset += b.byteLength return a }, new Uint8Array(size)) } module.exports = { staticPropertyDescriptors, readOperation, fireAProgressEvent } /***/ }), /***/ 6897: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = __nccwpck_require__(736) const { kReadyState, kSentClose, kByteParser, kReceivedClose, kResponse } = __nccwpck_require__(1216) const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = __nccwpck_require__(8625) const { channels } = __nccwpck_require__(2414) const { CloseEvent } = __nccwpck_require__(5188) const { makeRequest } = __nccwpck_require__(9967) const { fetching } = __nccwpck_require__(4398) const { Headers, getHeadersList } = __nccwpck_require__(660) const { getDecodeSplit } = __nccwpck_require__(3168) const { WebsocketFrameSend } = __nccwpck_require__(3264) /** @type {import('crypto')} */ let crypto try { crypto = __nccwpck_require__(7598) /* c8 ignore next 3 */ } catch { } /** * @see https://websockets.spec.whatwg.org/#concept-websocket-establish * @param {URL} url * @param {string|string[]} protocols * @param {import('./websocket').WebSocket} ws * @param {(response: any, extensions: string[] | undefined) => void} onEstablish * @param {Partial} options */ function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) { // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s // scheme is "ws", and to "https" otherwise. const requestURL = url requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' // 2. Let request be a new request, whose URL is requestURL, client is client, // service-workers mode is "none", referrer is "no-referrer", mode is // "websocket", credentials mode is "include", cache mode is "no-store" , // and redirect mode is "error". const request = makeRequest({ urlList: [requestURL], client, serviceWorkers: 'none', referrer: 'no-referrer', mode: 'websocket', credentials: 'include', cache: 'no-store', redirect: 'error' }) // Note: undici extension, allow setting custom headers. if (options.headers) { const headersList = getHeadersList(new Headers(options.headers)) request.headersList = headersList } // 3. Append (`Upgrade`, `websocket`) to request’s header list. // 4. Append (`Connection`, `Upgrade`) to request’s header list. // Note: both of these are handled by undici currently. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 // 5. Let keyValue be a nonce consisting of a randomly selected // 16-byte value that has been forgiving-base64-encoded and // isomorphic encoded. const keyValue = crypto.randomBytes(16).toString('base64') // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s // header list. request.headersList.append('sec-websocket-key', keyValue) // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s // header list. request.headersList.append('sec-websocket-version', '13') // 8. For each protocol in protocols, combine // (`Sec-WebSocket-Protocol`, protocol) in request’s header // list. for (const protocol of protocols) { request.headersList.append('sec-websocket-protocol', protocol) } // 9. Let permessageDeflate be a user-agent defined // "permessage-deflate" extension header value. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 const permessageDeflate = 'permessage-deflate; client_max_window_bits' // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to // request’s header list. request.headersList.append('sec-websocket-extensions', permessageDeflate) // 11. Fetch request with useParallelQueue set to true, and // processResponse given response being these steps: const controller = fetching({ request, useParallelQueue: true, dispatcher: options.dispatcher, processResponse (response) { // 1. If response is a network error or its status is not 101, // fail the WebSocket connection. if (response.type === 'error' || response.status !== 101) { failWebsocketConnection(ws, 'Received network error or non-101 status code.') return } // 2. If protocols is not the empty list and extracting header // list values given `Sec-WebSocket-Protocol` and response’s // header list results in null, failure, or the empty byte // sequence, then fail the WebSocket connection. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { failWebsocketConnection(ws, 'Server did not respond with sent protocols.') return } // 3. Follow the requirements stated step 2 to step 6, inclusive, // of the last set of steps in section 4.1 of The WebSocket // Protocol to validate response. This either results in fail // the WebSocket connection or the WebSocket connection is // established. // 2. If the response lacks an |Upgrade| header field or the |Upgrade| // header field contains a value that is not an ASCII case- // insensitive match for the value "websocket", the client MUST // _Fail the WebSocket Connection_. if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') return } // 3. If the response lacks a |Connection| header field or the // |Connection| header field doesn't contain a token that is an // ASCII case-insensitive match for the value "Upgrade", the client // MUST _Fail the WebSocket Connection_. if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') return } // 4. If the response lacks a |Sec-WebSocket-Accept| header field or // the |Sec-WebSocket-Accept| contains a value other than the // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- // Key| (as a string, not base64-decoded) with the string "258EAFA5- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and // trailing whitespace, the client MUST _Fail the WebSocket // Connection_. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') if (secWSAccept !== digest) { failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') return } // 5. If the response includes a |Sec-WebSocket-Extensions| header // field and this header field indicates the use of an extension // that was not present in the client's handshake (the server has // indicated an extension not requested by the client), the client // MUST _Fail the WebSocket Connection_. (The parsing of this // header field to determine which extensions are requested is // discussed in Section 9.1.) const secExtension = response.headersList.get('Sec-WebSocket-Extensions') let extensions if (secExtension !== null) { extensions = parseExtensions(secExtension) if (!extensions.has('permessage-deflate')) { failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.') return } } // 6. If the response includes a |Sec-WebSocket-Protocol| header field // and this header field indicates the use of a subprotocol that was // not present in the client's handshake (the server has indicated a // subprotocol not requested by the client), the client MUST _Fail // the WebSocket Connection_. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') if (secProtocol !== null) { const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList) // The client can request that the server use a specific subprotocol by // including the |Sec-WebSocket-Protocol| field in its handshake. If it // is specified, the server needs to include the same field and one of // the selected subprotocol values in its response for the connection to // be established. if (!requestProtocols.includes(secProtocol)) { failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') return } } response.socket.on('data', onSocketData) response.socket.on('close', onSocketClose) response.socket.on('error', onSocketError) if (channels.open.hasSubscribers) { channels.open.publish({ address: response.socket.address(), protocol: secProtocol, extensions: secExtension }) } onEstablish(response, extensions) } }) return controller } function closeWebSocketConnection (ws, code, reason, reasonByteLength) { if (isClosing(ws) || isClosed(ws)) { // If this's ready state is CLOSING (2) or CLOSED (3) // Do nothing. } else if (!isEstablished(ws)) { // If the WebSocket connection is not yet established // Fail the WebSocket connection and set this's ready state // to CLOSING (2). failWebsocketConnection(ws, 'Connection was closed before it was established.') ws[kReadyState] = states.CLOSING } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) { // If the WebSocket closing handshake has not yet been started // Start the WebSocket closing handshake and set this's ready // state to CLOSING (2). // - If neither code nor reason is present, the WebSocket Close // message must not have a body. // - If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. // - If reason is also present, then reasonBytes must be // provided in the Close message after the status code. ws[kSentClose] = sentCloseFrameState.PROCESSING const frame = new WebsocketFrameSend() // If neither code nor reason is present, the WebSocket Close // message must not have a body. // If code is present, then the status code to use in the // WebSocket Close message must be the integer given by code. if (code !== undefined && reason === undefined) { frame.frameData = Buffer.allocUnsafe(2) frame.frameData.writeUInt16BE(code, 0) } else if (code !== undefined && reason !== undefined) { // If reason is also present, then reasonBytes must be // provided in the Close message after the status code. frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) frame.frameData.writeUInt16BE(code, 0) // the body MAY contain UTF-8-encoded data with value /reason/ frame.frameData.write(reason, 2, 'utf-8') } else { frame.frameData = emptyBuffer } /** @type {import('stream').Duplex} */ const socket = ws[kResponse].socket socket.write(frame.createFrame(opcodes.CLOSE)) ws[kSentClose] = sentCloseFrameState.SENT // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. ws[kReadyState] = states.CLOSING } else { // Otherwise // Set this's ready state to CLOSING (2). ws[kReadyState] = states.CLOSING } } /** * @param {Buffer} chunk */ function onSocketData (chunk) { if (!this.ws[kByteParser].write(chunk)) { this.pause() } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 */ function onSocketClose () { const { ws } = this const { [kResponse]: response } = ws response.socket.off('data', onSocketData) response.socket.off('close', onSocketClose) response.socket.off('error', onSocketError) // If the TCP connection was closed after the // WebSocket closing handshake was completed, the WebSocket connection // is said to have been closed _cleanly_. const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose] let code = 1005 let reason = '' const result = ws[kByteParser].closingInfo if (result && !result.error) { code = result.code ?? 1005 reason = result.reason } else if (!ws[kReceivedClose]) { // If _The WebSocket // Connection is Closed_ and no Close control frame was received by the // endpoint (such as could occur if the underlying transport connection // is lost), _The WebSocket Connection Close Code_ is considered to be // 1006. code = 1006 } // 1. Change the ready state to CLOSED (3). ws[kReadyState] = states.CLOSED // 2. If the user agent was required to fail the WebSocket // connection, or if the WebSocket connection was closed // after being flagged as full, fire an event named error // at the WebSocket object. // TODO // 3. Fire an event named close at the WebSocket object, // using CloseEvent, with the wasClean attribute // initialized to true if the connection closed cleanly // and false otherwise, the code attribute initialized to // the WebSocket connection close code, and the reason // attribute initialized to the result of applying UTF-8 // decode without BOM to the WebSocket connection close // reason. // TODO: process.nextTick fireEvent('close', ws, (type, init) => new CloseEvent(type, init), { wasClean, code, reason }) if (channels.close.hasSubscribers) { channels.close.publish({ websocket: ws, code, reason }) } } function onSocketError (error) { const { ws } = this ws[kReadyState] = states.CLOSING if (channels.socketError.hasSubscribers) { channels.socketError.publish(error) } this.destroy() } module.exports = { establishWebSocketConnection, closeWebSocketConnection } /***/ }), /***/ 736: /***/ ((module) => { // This is a Globally Unique Identifier unique used // to validate that the endpoint accepts websocket // connections. // See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' /** @type {PropertyDescriptor} */ const staticPropertyDescriptors = { enumerable: true, writable: false, configurable: false } const states = { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 } const sentCloseFrameState = { NOT_SENT: 0, PROCESSING: 1, SENT: 2 } const opcodes = { CONTINUATION: 0x0, TEXT: 0x1, BINARY: 0x2, CLOSE: 0x8, PING: 0x9, PONG: 0xA } const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 const parserStates = { INFO: 0, PAYLOADLENGTH_16: 2, PAYLOADLENGTH_64: 3, READ_DATA: 4 } const emptyBuffer = Buffer.allocUnsafe(0) const sendHints = { string: 1, typedArray: 2, arrayBuffer: 3, blob: 4 } module.exports = { uid, sentCloseFrameState, staticPropertyDescriptors, states, opcodes, maxUnsigned16Bit, parserStates, emptyBuffer, sendHints } /***/ }), /***/ 5188: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { webidl } = __nccwpck_require__(5893) const { kEnumerableProperty } = __nccwpck_require__(3440) const { kConstruct } = __nccwpck_require__(6443) const { MessagePort } = __nccwpck_require__(5919) /** * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent */ class MessageEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { if (type === kConstruct) { super(arguments[1], arguments[2]) webidl.util.markAsUncloneable(this) return } const prefix = 'MessageEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict') super(type, eventInitDict) this.#eventInit = eventInitDict webidl.util.markAsUncloneable(this) } get data () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.data } get origin () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.origin } get lastEventId () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.lastEventId } get source () { webidl.brandCheck(this, MessageEvent) return this.#eventInit.source } get ports () { webidl.brandCheck(this, MessageEvent) if (!Object.isFrozen(this.#eventInit.ports)) { Object.freeze(this.#eventInit.ports) } return this.#eventInit.ports } initMessageEvent ( type, bubbles = false, cancelable = false, data = null, origin = '', lastEventId = '', source = null, ports = [] ) { webidl.brandCheck(this, MessageEvent) webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent') return new MessageEvent(type, { bubbles, cancelable, data, origin, lastEventId, source, ports }) } static createFastMessageEvent (type, init) { const messageEvent = new MessageEvent(kConstruct, type, init) messageEvent.#eventInit = init messageEvent.#eventInit.data ??= null messageEvent.#eventInit.origin ??= '' messageEvent.#eventInit.lastEventId ??= '' messageEvent.#eventInit.source ??= null messageEvent.#eventInit.ports ??= [] return messageEvent } } const { createFastMessageEvent } = MessageEvent delete MessageEvent.createFastMessageEvent /** * @see https://websockets.spec.whatwg.org/#the-closeevent-interface */ class CloseEvent extends Event { #eventInit constructor (type, eventInitDict = {}) { const prefix = 'CloseEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.CloseEventInit(eventInitDict) super(type, eventInitDict) this.#eventInit = eventInitDict webidl.util.markAsUncloneable(this) } get wasClean () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.wasClean } get code () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.code } get reason () { webidl.brandCheck(this, CloseEvent) return this.#eventInit.reason } } // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface class ErrorEvent extends Event { #eventInit constructor (type, eventInitDict) { const prefix = 'ErrorEvent constructor' webidl.argumentLengthCheck(arguments, 1, prefix) super(type, eventInitDict) webidl.util.markAsUncloneable(this) type = webidl.converters.DOMString(type, prefix, 'type') eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) this.#eventInit = eventInitDict } get message () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.message } get filename () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.filename } get lineno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.lineno } get colno () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.colno } get error () { webidl.brandCheck(this, ErrorEvent) return this.#eventInit.error } } Object.defineProperties(MessageEvent.prototype, { [Symbol.toStringTag]: { value: 'MessageEvent', configurable: true }, data: kEnumerableProperty, origin: kEnumerableProperty, lastEventId: kEnumerableProperty, source: kEnumerableProperty, ports: kEnumerableProperty, initMessageEvent: kEnumerableProperty }) Object.defineProperties(CloseEvent.prototype, { [Symbol.toStringTag]: { value: 'CloseEvent', configurable: true }, reason: kEnumerableProperty, code: kEnumerableProperty, wasClean: kEnumerableProperty }) Object.defineProperties(ErrorEvent.prototype, { [Symbol.toStringTag]: { value: 'ErrorEvent', configurable: true }, message: kEnumerableProperty, filename: kEnumerableProperty, lineno: kEnumerableProperty, colno: kEnumerableProperty, error: kEnumerableProperty }) webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.MessagePort ) const eventInit = [ { key: 'bubbles', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'cancelable', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'composed', converter: webidl.converters.boolean, defaultValue: () => false } ] webidl.converters.MessageEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'data', converter: webidl.converters.any, defaultValue: () => null }, { key: 'origin', converter: webidl.converters.USVString, defaultValue: () => '' }, { key: 'lastEventId', converter: webidl.converters.DOMString, defaultValue: () => '' }, { key: 'source', // Node doesn't implement WindowProxy or ServiceWorker, so the only // valid value for source is a MessagePort. converter: webidl.nullableConverter(webidl.converters.MessagePort), defaultValue: () => null }, { key: 'ports', converter: webidl.converters['sequence'], defaultValue: () => new Array(0) } ]) webidl.converters.CloseEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'wasClean', converter: webidl.converters.boolean, defaultValue: () => false }, { key: 'code', converter: webidl.converters['unsigned short'], defaultValue: () => 0 }, { key: 'reason', converter: webidl.converters.USVString, defaultValue: () => '' } ]) webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ ...eventInit, { key: 'message', converter: webidl.converters.DOMString, defaultValue: () => '' }, { key: 'filename', converter: webidl.converters.USVString, defaultValue: () => '' }, { key: 'lineno', converter: webidl.converters['unsigned long'], defaultValue: () => 0 }, { key: 'colno', converter: webidl.converters['unsigned long'], defaultValue: () => 0 }, { key: 'error', converter: webidl.converters.any } ]) module.exports = { MessageEvent, CloseEvent, ErrorEvent, createFastMessageEvent } /***/ }), /***/ 3264: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { maxUnsigned16Bit } = __nccwpck_require__(736) const BUFFER_SIZE = 16386 /** @type {import('crypto')} */ let crypto let buffer = null let bufIdx = BUFFER_SIZE try { crypto = __nccwpck_require__(7598) /* c8 ignore next 3 */ } catch { crypto = { // not full compatibility, but minimum. randomFillSync: function randomFillSync (buffer, _offset, _size) { for (let i = 0; i < buffer.length; ++i) { buffer[i] = Math.random() * 255 | 0 } return buffer } } } function generateMask () { if (bufIdx === BUFFER_SIZE) { bufIdx = 0 crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE) } return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]] } class WebsocketFrameSend { /** * @param {Buffer|undefined} data */ constructor (data) { this.frameData = data } createFrame (opcode) { const frameData = this.frameData const maskKey = generateMask() const bodyLength = frameData?.byteLength ?? 0 /** @type {number} */ let payloadLength = bodyLength // 0-125 let offset = 6 if (bodyLength > maxUnsigned16Bit) { offset += 8 // payload length is next 8 bytes payloadLength = 127 } else if (bodyLength > 125) { offset += 2 // payload length is next 2 bytes payloadLength = 126 } const buffer = Buffer.allocUnsafe(bodyLength + offset) // Clear first 2 bytes, everything else is overwritten buffer[0] = buffer[1] = 0 buffer[0] |= 0x80 // FIN buffer[0] = (buffer[0] & 0xF0) + opcode // opcode /*! ws. MIT License. Einar Otto Stangvik */ buffer[offset - 4] = maskKey[0] buffer[offset - 3] = maskKey[1] buffer[offset - 2] = maskKey[2] buffer[offset - 1] = maskKey[3] buffer[1] = payloadLength if (payloadLength === 126) { buffer.writeUInt16BE(bodyLength, 2) } else if (payloadLength === 127) { // Clear extended payload length buffer[2] = buffer[3] = 0 buffer.writeUIntBE(bodyLength, 4, 6) } buffer[1] |= 0x80 // MASK // mask body for (let i = 0; i < bodyLength; ++i) { buffer[offset + i] = frameData[i] ^ maskKey[i & 3] } return buffer } } module.exports = { WebsocketFrameSend } /***/ }), /***/ 9469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __nccwpck_require__(8522) const { isValidClientWindowBits } = __nccwpck_require__(8625) const { MessageSizeExceededError } = __nccwpck_require__(8707) const tail = Buffer.from([0x00, 0x00, 0xff, 0xff]) const kBuffer = Symbol('kBuffer') const kLength = Symbol('kLength') class PerMessageDeflate { /** @type {import('node:zlib').InflateRaw} */ #inflate #options = {} #maxPayloadSize = 0 /** * @param {Map} extensions */ constructor (extensions, options) { this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover') this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits') this.#maxPayloadSize = options.maxPayloadSize } /** * Decompress a compressed payload. * @param {Buffer} chunk Compressed data * @param {boolean} fin Final fragment flag * @param {Function} callback Callback function */ decompress (chunk, fin, callback) { // An endpoint uses the following algorithm to decompress a message. // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the // payload of the message. // 2. Decompress the resulting data using DEFLATE. if (!this.#inflate) { let windowBits = Z_DEFAULT_WINDOWBITS if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) { callback(new Error('Invalid server_max_window_bits')) return } windowBits = Number.parseInt(this.#options.serverMaxWindowBits) } try { this.#inflate = createInflateRaw({ windowBits }) } catch (err) { callback(err) return } this.#inflate[kBuffer] = [] this.#inflate[kLength] = 0 this.#inflate.on('data', (data) => { this.#inflate[kLength] += data.length if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) { callback(new MessageSizeExceededError()) this.#inflate.removeAllListeners() this.#inflate = null return } this.#inflate[kBuffer].push(data) }) this.#inflate.on('error', (err) => { this.#inflate = null callback(err) }) } this.#inflate.write(chunk) if (fin) { this.#inflate.write(tail) } this.#inflate.flush(() => { if (!this.#inflate) { return } const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]) this.#inflate[kBuffer].length = 0 this.#inflate[kLength] = 0 callback(null, full) }) } } module.exports = { PerMessageDeflate } /***/ }), /***/ 1652: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { Writable } = __nccwpck_require__(7075) const assert = __nccwpck_require__(4589) const { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = __nccwpck_require__(736) const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(1216) const { channels } = __nccwpck_require__(2414) const { isValidStatusCode, isValidOpcode, failWebsocketConnection, websocketMessageReceived, utf8Decode, isControlFrame, isTextBinaryFrame, isContinuationFrame } = __nccwpck_require__(8625) const { WebsocketFrameSend } = __nccwpck_require__(3264) const { closeWebSocketConnection } = __nccwpck_require__(6897) const { PerMessageDeflate } = __nccwpck_require__(9469) const { MessageSizeExceededError } = __nccwpck_require__(8707) function failWebsocketConnectionWithCode (ws, code, reason) { closeWebSocketConnection(ws, code, reason, Buffer.byteLength(reason)) failWebsocketConnection(ws, reason) } // This code was influenced by ws released under the MIT license. // Copyright (c) 2011 Einar Otto Stangvik // Copyright (c) 2013 Arnout Kazemier and contributors // Copyright (c) 2016 Luigi Pinca and contributors class ByteParser extends Writable { #buffers = [] #fragmentsBytes = 0 #byteOffset = 0 #loop = false #state = parserStates.INFO #info = {} #fragments = [] /** @type {Map} */ #extensions /** @type {number} */ #maxFragments /** @type {number} */ #maxPayloadSize /** * @param {import('./websocket').WebSocket} ws * @param {Map|null} extensions * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options] */ constructor (ws, extensions, options = {}) { super() this.ws = ws this.#extensions = extensions == null ? new Map() : extensions this.#maxFragments = options.maxFragments ?? 0 this.#maxPayloadSize = options.maxPayloadSize ?? 0 if (this.#extensions.has('permessage-deflate')) { this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, options)) } } /** * @param {Buffer} chunk * @param {() => void} callback */ _write (chunk, _, callback) { this.#buffers.push(chunk) this.#byteOffset += chunk.length this.#loop = true this.run(callback) } #validatePayloadLength () { if ( this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize ) { failWebsocketConnectionWithCode(this.ws, 1009, 'Payload size exceeds maximum allowed size') return false } return true } /** * Runs whenever a new chunk is received. * Callback is called whenever there are no more chunks buffering, * or not enough bytes are buffered to parse. */ run (callback) { while (this.#loop) { if (this.#state === parserStates.INFO) { // If there aren't enough bytes to parse the payload length, etc. if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) const fin = (buffer[0] & 0x80) !== 0 const opcode = buffer[0] & 0x0F const masked = (buffer[1] & 0x80) === 0x80 const fragmented = !fin && opcode !== opcodes.CONTINUATION const payloadLength = buffer[1] & 0x7F const rsv1 = buffer[0] & 0x40 const rsv2 = buffer[0] & 0x20 const rsv3 = buffer[0] & 0x10 if (!isValidOpcode(opcode)) { failWebsocketConnection(this.ws, 'Invalid opcode received') return callback() } if (masked) { failWebsocketConnection(this.ws, 'Frame cannot be masked') return callback() } // MUST be 0 unless an extension is negotiated that defines meanings // for non-zero values. If a nonzero value is received and none of // the negotiated extensions defines the meaning of such a nonzero // value, the receiving endpoint MUST _Fail the WebSocket // Connection_. // This document allocates the RSV1 bit of the WebSocket header for // PMCEs and calls the bit the "Per-Message Compressed" bit. On a // WebSocket connection where a PMCE is in use, this bit indicates // whether a message is compressed or not. if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) { failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.') return } if (rsv2 !== 0 || rsv3 !== 0) { failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear') return } if (fragmented && !isTextBinaryFrame(opcode)) { // Only text and binary frames can be fragmented failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') return } // If we are already parsing a text/binary frame and do not receive either // a continuation frame or close frame, fail the connection. if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) { failWebsocketConnection(this.ws, 'Expected continuation frame') return } if (this.#info.fragmented && fragmented) { // A fragmented frame can't be fragmented itself failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') return } // "All control frames MUST have a payload length of 125 bytes or less // and MUST NOT be fragmented." if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) { failWebsocketConnection(this.ws, 'Control frame either too large or fragmented') return } if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) { failWebsocketConnection(this.ws, 'Unexpected continuation frame') return } if (payloadLength <= 125) { this.#info.payloadLength = payloadLength this.#state = parserStates.READ_DATA if (!this.#validatePayloadLength()) { return } } else if (payloadLength === 126) { this.#state = parserStates.PAYLOADLENGTH_16 } else if (payloadLength === 127) { this.#state = parserStates.PAYLOADLENGTH_64 } if (isTextBinaryFrame(opcode)) { this.#info.binaryType = opcode this.#info.compressed = rsv1 !== 0 } this.#info.opcode = opcode this.#info.masked = masked this.#info.fin = fin this.#info.fragmented = fragmented } else if (this.#state === parserStates.PAYLOADLENGTH_16) { if (this.#byteOffset < 2) { return callback() } const buffer = this.consume(2) this.#info.payloadLength = buffer.readUInt16BE(0) this.#state = parserStates.READ_DATA if (!this.#validatePayloadLength()) { return } } else if (this.#state === parserStates.PAYLOADLENGTH_64) { if (this.#byteOffset < 8) { return callback() } const buffer = this.consume(8) const upper = buffer.readUInt32BE(0) const lower = buffer.readUInt32BE(4) // 2^31 is the maximum bytes an arraybuffer can contain // on 32-bit systems. Although, on 64-bit systems, this is // 2^53-1 bytes. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e if (upper !== 0 || lower > 2 ** 31 - 1) { failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') return } this.#info.payloadLength = lower this.#state = parserStates.READ_DATA if (!this.#validatePayloadLength()) { return } } else if (this.#state === parserStates.READ_DATA) { if (this.#byteOffset < this.#info.payloadLength) { return callback() } const body = this.consume(this.#info.payloadLength) if (isControlFrame(this.#info.opcode)) { this.#loop = this.parseControlFrame(body) this.#state = parserStates.INFO } else { if (!this.#info.compressed) { if (!this.writeFragments(body)) { return } if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message) return } // If the frame is not fragmented, a message has been received. // If the frame is fragmented, it will terminate with a fin bit set // and an opcode of 0 (continuation), therefore we handle that when // parsing continuation frames, not here. if (!this.#info.fragmented && this.#info.fin) { websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()) } this.#state = parserStates.INFO } else { this.#extensions.get('permessage-deflate').decompress( body, this.#info.fin, (error, data) => { if (error) { const code = error instanceof MessageSizeExceededError ? 1009 : 1007 failWebsocketConnectionWithCode(this.ws, code, error.message) return } if (!this.writeFragments(data)) { return } if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) { failWebsocketConnectionWithCode(this.ws, 1009, new MessageSizeExceededError().message) return } if (!this.#info.fin) { this.#state = parserStates.INFO this.#loop = true this.run(callback) return } websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments()) this.#loop = true this.#state = parserStates.INFO this.run(callback) } ) this.#loop = false break } } } } } /** * Take n bytes from the buffered Buffers * @param {number} n * @returns {Buffer} */ consume (n) { if (n > this.#byteOffset) { throw new Error('Called consume() before buffers satiated.') } else if (n === 0) { return emptyBuffer } if (this.#buffers[0].length === n) { this.#byteOffset -= this.#buffers[0].length return this.#buffers.shift() } const buffer = Buffer.allocUnsafe(n) let offset = 0 while (offset !== n) { const next = this.#buffers[0] const { length } = next if (length + offset === n) { buffer.set(this.#buffers.shift(), offset) break } else if (length + offset > n) { buffer.set(next.subarray(0, n - offset), offset) this.#buffers[0] = next.subarray(n - offset) break } else { buffer.set(this.#buffers.shift(), offset) offset += next.length } } this.#byteOffset -= n return buffer } writeFragments (fragment) { if ( this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments ) { failWebsocketConnectionWithCode(this.ws, 1008, 'Too many message fragments') return false } this.#fragmentsBytes += fragment.length this.#fragments.push(fragment) return true } consumeFragments () { const fragments = this.#fragments if (fragments.length === 1) { this.#fragmentsBytes = 0 return fragments.shift() } const output = Buffer.concat(fragments, this.#fragmentsBytes) this.#fragments = [] this.#fragmentsBytes = 0 return output } parseCloseBody (data) { assert(data.length !== 1) // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 /** @type {number|undefined} */ let code if (data.length >= 2) { // _The WebSocket Connection Close Code_ is // defined as the status code (Section 7.4) contained in the first Close // control frame received by the application code = data.readUInt16BE(0) } if (code !== undefined && !isValidStatusCode(code)) { return { code: 1002, reason: 'Invalid status code', error: true } } // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 /** @type {Buffer} */ let reason = data.subarray(2) // Remove BOM if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { reason = reason.subarray(3) } try { reason = utf8Decode(reason) } catch { return { code: 1007, reason: 'Invalid UTF-8', error: true } } return { code, reason, error: false } } /** * Parses control frames. * @param {Buffer} body */ parseControlFrame (body) { const { opcode, payloadLength } = this.#info if (opcode === opcodes.CLOSE) { if (payloadLength === 1) { failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') return false } this.#info.closeInfo = this.parseCloseBody(body) if (this.#info.closeInfo.error) { const { code, reason } = this.#info.closeInfo closeWebSocketConnection(this.ws, code, reason, reason.length) failWebsocketConnection(this.ws, reason) return false } if (this.ws[kSentClose] !== sentCloseFrameState.SENT) { // If an endpoint receives a Close frame and did not previously send a // Close frame, the endpoint MUST send a Close frame in response. (When // sending a Close frame in response, the endpoint typically echos the // status code it received.) let body = emptyBuffer if (this.#info.closeInfo.code) { body = Buffer.allocUnsafe(2) body.writeUInt16BE(this.#info.closeInfo.code, 0) } const closeFrame = new WebsocketFrameSend(body) this.ws[kResponse].socket.write( closeFrame.createFrame(opcodes.CLOSE), (err) => { if (!err) { this.ws[kSentClose] = sentCloseFrameState.SENT } } ) } // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. this.ws[kReadyState] = states.CLOSING this.ws[kReceivedClose] = true return false } else if (opcode === opcodes.PING) { // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in // response, unless it already received a Close frame. // A Pong frame sent in response to a Ping frame must have identical // "Application data" if (!this.ws[kReceivedClose]) { const frame = new WebsocketFrameSend(body) this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) if (channels.ping.hasSubscribers) { channels.ping.publish({ payload: body }) } } } else if (opcode === opcodes.PONG) { // A Pong frame MAY be sent unsolicited. This serves as a // unidirectional heartbeat. A response to an unsolicited Pong frame is // not expected. if (channels.pong.hasSubscribers) { channels.pong.publish({ payload: body }) } } return true } get closingInfo () { return this.#info.closeInfo } } module.exports = { ByteParser } /***/ }), /***/ 3900: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { WebsocketFrameSend } = __nccwpck_require__(3264) const { opcodes, sendHints } = __nccwpck_require__(736) const FixedQueue = __nccwpck_require__(4660) /** @type {typeof Uint8Array} */ const FastBuffer = Buffer[Symbol.species] /** * @typedef {object} SendQueueNode * @property {Promise | null} promise * @property {((...args: any[]) => any)} callback * @property {Buffer | null} frame */ class SendQueue { /** * @type {FixedQueue} */ #queue = new FixedQueue() /** * @type {boolean} */ #running = false /** @type {import('node:net').Socket} */ #socket constructor (socket) { this.#socket = socket } add (item, cb, hint) { if (hint !== sendHints.blob) { const frame = createFrame(item, hint) if (!this.#running) { // fast-path this.#socket.write(frame, cb) } else { /** @type {SendQueueNode} */ const node = { promise: null, callback: cb, frame } this.#queue.push(node) } return } /** @type {SendQueueNode} */ const node = { promise: item.arrayBuffer().then((ab) => { node.promise = null node.frame = createFrame(ab, hint) }), callback: cb, frame: null } this.#queue.push(node) if (!this.#running) { this.#run() } } async #run () { this.#running = true const queue = this.#queue while (!queue.isEmpty()) { const node = queue.shift() // wait pending promise if (node.promise !== null) { await node.promise } // write this.#socket.write(node.frame, node.callback) // cleanup node.callback = node.frame = null } this.#running = false } } function createFrame (data, hint) { return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY) } function toBuffer (data, hint) { switch (hint) { case sendHints.string: return Buffer.from(data) case sendHints.arrayBuffer: case sendHints.blob: return new FastBuffer(data) case sendHints.typedArray: return new FastBuffer(data.buffer, data.byteOffset, data.byteLength) } } module.exports = { SendQueue } /***/ }), /***/ 1216: /***/ ((module) => { module.exports = { kWebSocketURL: Symbol('url'), kReadyState: Symbol('ready state'), kController: Symbol('controller'), kResponse: Symbol('response'), kBinaryType: Symbol('binary type'), kSentClose: Symbol('sent close'), kReceivedClose: Symbol('received close'), kByteParser: Symbol('byte parser') } /***/ }), /***/ 8625: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(1216) const { states, opcodes } = __nccwpck_require__(736) const { ErrorEvent, createFastMessageEvent } = __nccwpck_require__(5188) const { isUtf8 } = __nccwpck_require__(4573) const { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = __nccwpck_require__(1900) /* globals Blob */ /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isConnecting (ws) { // If the WebSocket connection is not yet established, and the connection // is not yet closed, then the WebSocket connection is in the CONNECTING state. return ws[kReadyState] === states.CONNECTING } /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isEstablished (ws) { // If the server's response is validated as provided for above, it is // said that _The WebSocket Connection is Established_ and that the // WebSocket Connection is in the OPEN state. return ws[kReadyState] === states.OPEN } /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isClosing (ws) { // Upon either sending or receiving a Close control frame, it is said // that _The WebSocket Closing Handshake is Started_ and that the // WebSocket connection is in the CLOSING state. return ws[kReadyState] === states.CLOSING } /** * @param {import('./websocket').WebSocket} ws * @returns {boolean} */ function isClosed (ws) { return ws[kReadyState] === states.CLOSED } /** * @see https://dom.spec.whatwg.org/#concept-event-fire * @param {string} e * @param {EventTarget} target * @param {(...args: ConstructorParameters) => Event} eventFactory * @param {EventInit | undefined} eventInitDict */ function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) { // 1. If eventConstructor is not given, then let eventConstructor be Event. // 2. Let event be the result of creating an event given eventConstructor, // in the relevant realm of target. // 3. Initialize event’s type attribute to e. const event = eventFactory(e, eventInitDict) // 4. Initialize any other IDL attributes of event as described in the // invocation of this algorithm. // 5. Return the result of dispatching event at target, with legacy target // override flag set if set. target.dispatchEvent(event) } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol * @param {import('./websocket').WebSocket} ws * @param {number} type Opcode * @param {Buffer} data application data */ function websocketMessageReceived (ws, type, data) { // 1. If ready state is not OPEN (1), then return. if (ws[kReadyState] !== states.OPEN) { return } // 2. Let dataForEvent be determined by switching on type and binary type: let dataForEvent if (type === opcodes.TEXT) { // -> type indicates that the data is Text // a new DOMString containing data try { dataForEvent = utf8Decode(data) } catch { failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') return } } else if (type === opcodes.BINARY) { if (ws[kBinaryType] === 'blob') { // -> type indicates that the data is Binary and binary type is "blob" // a new Blob object, created in the relevant Realm of the WebSocket // object, that represents data as its raw data dataForEvent = new Blob([data]) } else { // -> type indicates that the data is Binary and binary type is "arraybuffer" // a new ArrayBuffer object, created in the relevant Realm of the // WebSocket object, whose contents are data dataForEvent = toArrayBuffer(data) } } // 3. Fire an event named message at the WebSocket object, using MessageEvent, // with the origin attribute initialized to the serialization of the WebSocket // object’s url's origin, and the data attribute initialized to dataForEvent. fireEvent('message', ws, createFastMessageEvent, { origin: ws[kWebSocketURL].origin, data: dataForEvent }) } function toArrayBuffer (buffer) { if (buffer.byteLength === buffer.buffer.byteLength) { return buffer.buffer } return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) } /** * @see https://datatracker.ietf.org/doc/html/rfc6455 * @see https://datatracker.ietf.org/doc/html/rfc2616 * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 * @param {string} protocol */ function isValidSubprotocol (protocol) { // If present, this value indicates one // or more comma-separated subprotocol the client wishes to speak, // ordered by preference. The elements that comprise this value // MUST be non-empty strings with characters in the range U+0021 to // U+007E not including separator characters as defined in // [RFC2616] and MUST all be unique strings. if (protocol.length === 0) { return false } for (let i = 0; i < protocol.length; ++i) { const code = protocol.charCodeAt(i) if ( code < 0x21 || // CTL, contains SP (0x20) and HT (0x09) code > 0x7E || code === 0x22 || // " code === 0x28 || // ( code === 0x29 || // ) code === 0x2C || // , code === 0x2F || // / code === 0x3A || // : code === 0x3B || // ; code === 0x3C || // < code === 0x3D || // = code === 0x3E || // > code === 0x3F || // ? code === 0x40 || // @ code === 0x5B || // [ code === 0x5C || // \ code === 0x5D || // ] code === 0x7B || // { code === 0x7D // } ) { return false } } return true } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 * @param {number} code */ function isValidStatusCode (code) { if (code >= 1000 && code < 1015) { return ( code !== 1004 && // reserved code !== 1005 && // "MUST NOT be set as a status code" code !== 1006 // "MUST NOT be set as a status code" ) } return code >= 3000 && code <= 4999 } /** * @param {import('./websocket').WebSocket} ws * @param {string|undefined} reason */ function failWebsocketConnection (ws, reason) { const { [kController]: controller, [kResponse]: response } = ws controller.abort() if (response?.socket && !response.socket.destroyed) { response.socket.destroy() } if (reason) { // TODO: process.nextTick fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), { error: new Error(reason), message: reason }) } } /** * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5 * @param {number} opcode */ function isControlFrame (opcode) { return ( opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG ) } function isContinuationFrame (opcode) { return opcode === opcodes.CONTINUATION } function isTextBinaryFrame (opcode) { return opcode === opcodes.TEXT || opcode === opcodes.BINARY } function isValidOpcode (opcode) { return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode) } /** * Parses a Sec-WebSocket-Extensions header value. * @param {string} extensions * @returns {Map} */ // TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 function parseExtensions (extensions) { const position = { position: 0 } const extensionList = new Map() while (position.position < extensions.length) { const pair = collectASequenceOfCodePointsFast(';', extensions, position) const [name, value = ''] = pair.split('=') extensionList.set( removeHTTPWhitespace(name, true, false), removeHTTPWhitespace(value, false, true) ) position.position++ } return extensionList } /** * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2 * @description "client-max-window-bits = 1*DIGIT" * @param {string} value */ function isValidClientWindowBits (value) { // Must have at least one character if (value.length === 0) { return false } // Check all characters are ASCII digits for (let i = 0; i < value.length; i++) { const byte = value.charCodeAt(i) if (byte < 0x30 || byte > 0x39) { return false } } // Check numeric range: zlib requires windowBits in range 8-15 const num = Number.parseInt(value, 10) return num >= 8 && num <= 15 } // https://nodejs.org/api/intl.html#detecting-internationalization-support const hasIntl = typeof process.versions.icu === 'string' const fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined /** * Converts a Buffer to utf-8, even on platforms without icu. * @param {Buffer} buffer */ const utf8Decode = hasIntl ? fatalDecoder.decode.bind(fatalDecoder) : function (buffer) { if (isUtf8(buffer)) { return buffer.toString('utf-8') } throw new TypeError('Invalid utf-8 received.') } module.exports = { isConnecting, isEstablished, isClosing, isClosed, fireEvent, isValidSubprotocol, isValidStatusCode, failWebsocketConnection, websocketMessageReceived, utf8Decode, isControlFrame, isContinuationFrame, isTextBinaryFrame, isValidOpcode, parseExtensions, isValidClientWindowBits } /***/ }), /***/ 3726: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { webidl } = __nccwpck_require__(5893) const { URLSerializer } = __nccwpck_require__(1900) const { environmentSettingsObject } = __nccwpck_require__(3168) const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = __nccwpck_require__(736) const { kWebSocketURL, kReadyState, kController, kBinaryType, kResponse, kSentClose, kByteParser } = __nccwpck_require__(1216) const { isConnecting, isEstablished, isClosing, isValidSubprotocol, fireEvent } = __nccwpck_require__(8625) const { establishWebSocketConnection, closeWebSocketConnection } = __nccwpck_require__(6897) const { ByteParser } = __nccwpck_require__(1652) const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440) const { getGlobalDispatcher } = __nccwpck_require__(2581) const { types } = __nccwpck_require__(7975) const { ErrorEvent, CloseEvent } = __nccwpck_require__(5188) const { SendQueue } = __nccwpck_require__(3900) // https://websockets.spec.whatwg.org/#interface-definition class WebSocket extends EventTarget { #events = { open: null, error: null, close: null, message: null } #bufferedAmount = 0 #protocol = '' #extensions = '' /** @type {SendQueue} */ #sendQueue /** * @param {string} url * @param {string|string[]} protocols */ constructor (url, protocols = []) { super() webidl.util.markAsUncloneable(this) const prefix = 'WebSocket constructor' webidl.argumentLengthCheck(arguments, 1, prefix) const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options') url = webidl.converters.USVString(url, prefix, 'url') protocols = options.protocols // 1. Let baseURL be this's relevant settings object's API base URL. const baseURL = environmentSettingsObject.settingsObject.baseUrl // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. let urlRecord try { urlRecord = new URL(url, baseURL) } catch (e) { // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. throw new DOMException(e, 'SyntaxError') } // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". if (urlRecord.protocol === 'http:') { urlRecord.protocol = 'ws:' } else if (urlRecord.protocol === 'https:') { // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". urlRecord.protocol = 'wss:' } // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { throw new DOMException( `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, 'SyntaxError' ) } // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" // DOMException. if (urlRecord.hash || urlRecord.href.endsWith('#')) { throw new DOMException('Got fragment', 'SyntaxError') } // 8. If protocols is a string, set protocols to a sequence consisting // of just that string. if (typeof protocols === 'string') { protocols = [protocols] } // 9. If any of the values in protocols occur more than once or otherwise // fail to match the requirements for elements that comprise the value // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket // protocol, then throw a "SyntaxError" DOMException. if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } // 10. Set this's url to urlRecord. this[kWebSocketURL] = new URL(urlRecord.href) // 11. Let client be this's relevant settings object. const client = environmentSettingsObject.settingsObject // 12. Run this step in parallel: // 1. Establish a WebSocket connection given urlRecord, protocols, // and client. this[kController] = establishWebSocketConnection( urlRecord, protocols, client, this, (response, extensions) => this.#onConnectionEstablished(response, extensions), options ) // Each WebSocket object has an associated ready state, which is a // number representing the state of the connection. Initially it must // be CONNECTING (0). this[kReadyState] = WebSocket.CONNECTING this[kSentClose] = sentCloseFrameState.NOT_SENT // The extensions attribute must initially return the empty string. // The protocol attribute must initially return the empty string. // Each WebSocket object has an associated binary type, which is a // BinaryType. Initially it must be "blob". this[kBinaryType] = 'blob' } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-close * @param {number|undefined} code * @param {string|undefined} reason */ close (code = undefined, reason = undefined) { webidl.brandCheck(this, WebSocket) const prefix = 'WebSocket.close' if (code !== undefined) { code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true }) } if (reason !== undefined) { reason = webidl.converters.USVString(reason, prefix, 'reason') } // 1. If code is present, but is neither an integer equal to 1000 nor an // integer in the range 3000 to 4999, inclusive, throw an // "InvalidAccessError" DOMException. if (code !== undefined) { if (code !== 1000 && (code < 3000 || code > 4999)) { throw new DOMException('invalid code', 'InvalidAccessError') } } let reasonByteLength = 0 // 2. If reason is present, then run these substeps: if (reason !== undefined) { // 1. Let reasonBytes be the result of encoding reason. // 2. If reasonBytes is longer than 123 bytes, then throw a // "SyntaxError" DOMException. reasonByteLength = Buffer.byteLength(reason) if (reasonByteLength > 123) { throw new DOMException( `Reason must be less than 123 bytes; received ${reasonByteLength}`, 'SyntaxError' ) } } // 3. Run the first matching steps from the following list: closeWebSocketConnection(this, code, reason, reasonByteLength) } /** * @see https://websockets.spec.whatwg.org/#dom-websocket-send * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data */ send (data) { webidl.brandCheck(this, WebSocket) const prefix = 'WebSocket.send' webidl.argumentLengthCheck(arguments, 1, prefix) data = webidl.converters.WebSocketSendData(data, prefix, 'data') // 1. If this's ready state is CONNECTING, then throw an // "InvalidStateError" DOMException. if (isConnecting(this)) { throw new DOMException('Sent before connected.', 'InvalidStateError') } // 2. Run the appropriate set of steps from the following list: // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 if (!isEstablished(this) || isClosing(this)) { return } // If data is a string if (typeof data === 'string') { // If the WebSocket connection is established and the WebSocket // closing handshake has not yet started, then the user agent // must send a WebSocket Message comprised of the data argument // using a text frame opcode; if the data cannot be sent, e.g. // because it would need to be buffered but the buffer is full, // the user agent must flag the WebSocket as full and then close // the WebSocket connection. Any invocation of this method with a // string argument that does not throw an exception must increase // the bufferedAmount attribute by the number of bytes needed to // express the argument as UTF-8. const length = Buffer.byteLength(data) this.#bufferedAmount += length this.#sendQueue.add(data, () => { this.#bufferedAmount -= length }, sendHints.string) } else if (types.isArrayBuffer(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need // to be buffered but the buffer is full, the user agent must flag // the WebSocket as full and then close the WebSocket connection. // The data to be sent is the data stored in the buffer described // by the ArrayBuffer object. Any invocation of this method with an // ArrayBuffer argument that does not throw an exception must // increase the bufferedAmount attribute by the length of the // ArrayBuffer in bytes. this.#bufferedAmount += data.byteLength this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength }, sendHints.arrayBuffer) } else if (ArrayBuffer.isView(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The // data to be sent is the data stored in the section of the buffer // described by the ArrayBuffer object that data references. Any // invocation of this method with this kind of argument that does // not throw an exception must increase the bufferedAmount attribute // by the length of data’s buffer in bytes. this.#bufferedAmount += data.byteLength this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.byteLength }, sendHints.typedArray) } else if (isBlobLike(data)) { // If the WebSocket connection is established, and the WebSocket // closing handshake has not yet started, then the user agent must // send a WebSocket Message comprised of data using a binary frame // opcode; if the data cannot be sent, e.g. because it would need to // be buffered but the buffer is full, the user agent must flag the // WebSocket as full and then close the WebSocket connection. The data // to be sent is the raw data represented by the Blob object. Any // invocation of this method with a Blob argument that does not throw // an exception must increase the bufferedAmount attribute by the size // of the Blob object’s raw data, in bytes. this.#bufferedAmount += data.size this.#sendQueue.add(data, () => { this.#bufferedAmount -= data.size }, sendHints.blob) } } get readyState () { webidl.brandCheck(this, WebSocket) // The readyState getter steps are to return this's ready state. return this[kReadyState] } get bufferedAmount () { webidl.brandCheck(this, WebSocket) return this.#bufferedAmount } get url () { webidl.brandCheck(this, WebSocket) // The url getter steps are to return this's url, serialized. return URLSerializer(this[kWebSocketURL]) } get extensions () { webidl.brandCheck(this, WebSocket) return this.#extensions } get protocol () { webidl.brandCheck(this, WebSocket) return this.#protocol } get onopen () { webidl.brandCheck(this, WebSocket) return this.#events.open } set onopen (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.open) { this.removeEventListener('open', this.#events.open) } if (typeof fn === 'function') { this.#events.open = fn this.addEventListener('open', fn) } else { this.#events.open = null } } get onerror () { webidl.brandCheck(this, WebSocket) return this.#events.error } set onerror (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.error) { this.removeEventListener('error', this.#events.error) } if (typeof fn === 'function') { this.#events.error = fn this.addEventListener('error', fn) } else { this.#events.error = null } } get onclose () { webidl.brandCheck(this, WebSocket) return this.#events.close } set onclose (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.close) { this.removeEventListener('close', this.#events.close) } if (typeof fn === 'function') { this.#events.close = fn this.addEventListener('close', fn) } else { this.#events.close = null } } get onmessage () { webidl.brandCheck(this, WebSocket) return this.#events.message } set onmessage (fn) { webidl.brandCheck(this, WebSocket) if (this.#events.message) { this.removeEventListener('message', this.#events.message) } if (typeof fn === 'function') { this.#events.message = fn this.addEventListener('message', fn) } else { this.#events.message = null } } get binaryType () { webidl.brandCheck(this, WebSocket) return this[kBinaryType] } set binaryType (type) { webidl.brandCheck(this, WebSocket) if (type !== 'blob' && type !== 'arraybuffer') { this[kBinaryType] = 'blob' } else { this[kBinaryType] = type } } /** * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol */ #onConnectionEstablished (response, parsedExtensions) { // processResponse is called when the "response's header list has been received and initialized." // once this happens, the connection is open this[kResponse] = response const webSocketOptions = this[kController]?.dispatcher?.webSocketOptions const maxFragments = webSocketOptions?.maxFragments const maxPayloadSize = webSocketOptions?.maxPayloadSize const parser = new ByteParser(this, parsedExtensions, { maxFragments, maxPayloadSize }) parser.on('drain', onParserDrain) parser.on('error', onParserError.bind(this)) response.socket.ws = this this[kByteParser] = parser this.#sendQueue = new SendQueue(response.socket) // 1. Change the ready state to OPEN (1). this[kReadyState] = states.OPEN // 2. Change the extensions attribute’s value to the extensions in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 const extensions = response.headersList.get('sec-websocket-extensions') if (extensions !== null) { this.#extensions = extensions } // 3. Change the protocol attribute’s value to the subprotocol in use, if // it is not the null value. // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 const protocol = response.headersList.get('sec-websocket-protocol') if (protocol !== null) { this.#protocol = protocol } // 4. Fire an event named open at the WebSocket object. fireEvent('open', this) } } // https://websockets.spec.whatwg.org/#dom-websocket-connecting WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING // https://websockets.spec.whatwg.org/#dom-websocket-open WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN // https://websockets.spec.whatwg.org/#dom-websocket-closing WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING // https://websockets.spec.whatwg.org/#dom-websocket-closed WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED Object.defineProperties(WebSocket.prototype, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors, url: kEnumerableProperty, readyState: kEnumerableProperty, bufferedAmount: kEnumerableProperty, onopen: kEnumerableProperty, onerror: kEnumerableProperty, onclose: kEnumerableProperty, close: kEnumerableProperty, onmessage: kEnumerableProperty, binaryType: kEnumerableProperty, send: kEnumerableProperty, extensions: kEnumerableProperty, protocol: kEnumerableProperty, [Symbol.toStringTag]: { value: 'WebSocket', writable: false, enumerable: false, configurable: true } }) Object.defineProperties(WebSocket, { CONNECTING: staticPropertyDescriptors, OPEN: staticPropertyDescriptors, CLOSING: staticPropertyDescriptors, CLOSED: staticPropertyDescriptors }) webidl.converters['sequence'] = webidl.sequenceConverter( webidl.converters.DOMString ) webidl.converters['DOMString or sequence'] = function (V, prefix, argument) { if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { return webidl.converters['sequence'](V) } return webidl.converters.DOMString(V, prefix, argument) } // This implements the proposal made in https://github.com/whatwg/websockets/issues/42 webidl.converters.WebSocketInit = webidl.dictionaryConverter([ { key: 'protocols', converter: webidl.converters['DOMString or sequence'], defaultValue: () => new Array(0) }, { key: 'dispatcher', converter: webidl.converters.any, defaultValue: () => getGlobalDispatcher() }, { key: 'headers', converter: webidl.nullableConverter(webidl.converters.HeadersInit) } ]) webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { return webidl.converters.WebSocketInit(V) } return { protocols: webidl.converters['DOMString or sequence'](V) } } webidl.converters.WebSocketSendData = function (V) { if (webidl.util.Type(V) === 'Object') { if (isBlobLike(V)) { return webidl.converters.Blob(V, { strict: false }) } if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) { return webidl.converters.BufferSource(V) } } return webidl.converters.USVString(V) } function onParserDrain () { this.ws[kResponse].socket.resume() } function onParserError (err) { let message let code if (err instanceof CloseEvent) { message = err.reason code = err.code } else { message = err.message } fireEvent('error', this, () => new ErrorEvent('error', { error: err, message })) closeWebSocketConnection(this, code) } module.exports = { WebSocket } /***/ }), /***/ 3585: /***/ (function(__unused_webpack_module, exports) { /** * @license * web-streams-polyfill v3.3.3 * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. * This code is released under the MIT license. * SPDX-License-Identifier: MIT */ (function (global, factory) { true ? factory(exports) : 0; })(this, (function (exports) { 'use strict'; function noop() { return undefined; } function typeIsObject(x) { return (typeof x === 'object' && x !== null) || typeof x === 'function'; } const rethrowAssertionErrorRejection = noop; function setFunctionName(fn, name) { try { Object.defineProperty(fn, 'name', { value: name, configurable: true }); } catch (_a) { // This property is non-configurable in older browsers, so ignore if this throws. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility } } const originalPromise = Promise; const originalPromiseThen = Promise.prototype.then; const originalPromiseReject = Promise.reject.bind(originalPromise); // https://webidl.spec.whatwg.org/#a-new-promise function newPromise(executor) { return new originalPromise(executor); } // https://webidl.spec.whatwg.org/#a-promise-resolved-with function promiseResolvedWith(value) { return newPromise(resolve => resolve(value)); } // https://webidl.spec.whatwg.org/#a-promise-rejected-with function promiseRejectedWith(reason) { return originalPromiseReject(reason); } function PerformPromiseThen(promise, onFulfilled, onRejected) { // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an // approximation. return originalPromiseThen.call(promise, onFulfilled, onRejected); } // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned // from that handler. To prevent this, return null instead of void from all handlers. // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it function uponPromise(promise, onFulfilled, onRejected) { PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); } function uponFulfillment(promise, onFulfilled) { uponPromise(promise, onFulfilled); } function uponRejection(promise, onRejected) { uponPromise(promise, undefined, onRejected); } function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); } function setPromiseIsHandledToTrue(promise) { PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); } let _queueMicrotask = callback => { if (typeof queueMicrotask === 'function') { _queueMicrotask = queueMicrotask; } else { const resolvedPromise = promiseResolvedWith(undefined); _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); } return _queueMicrotask(callback); }; function reflectCall(F, V, args) { if (typeof F !== 'function') { throw new TypeError('Argument is not a function'); } return Function.prototype.apply.call(F, V, args); } function promiseCall(F, V, args) { try { return promiseResolvedWith(reflectCall(F, V, args)); } catch (value) { return promiseRejectedWith(value); } } // Original from Chromium // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js const QUEUE_MAX_ARRAY_SIZE = 16384; /** * Simple queue structure. * * Avoids scalability issues with using a packed array directly by using * multiple arrays in a linked list and keeping the array size bounded. */ class SimpleQueue { constructor() { this._cursor = 0; this._size = 0; // _front and _back are always defined. this._front = { _elements: [], _next: undefined }; this._back = this._front; // The cursor is used to avoid calling Array.shift(). // It contains the index of the front element of the array inside the // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). this._cursor = 0; // When there is only one node, size === elements.length - cursor. this._size = 0; } get length() { return this._size; } // For exception safety, this method is structured in order: // 1. Read state // 2. Calculate required state mutations // 3. Perform state mutations push(element) { const oldBack = this._back; let newBack = oldBack; if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { newBack = { _elements: [], _next: undefined }; } // push() is the mutation most likely to throw an exception, so it // goes first. oldBack._elements.push(element); if (newBack !== oldBack) { this._back = newBack; oldBack._next = newBack; } ++this._size; } // Like push(), shift() follows the read -> calculate -> mutate pattern for // exception safety. shift() { // must not be called on an empty queue const oldFront = this._front; let newFront = oldFront; const oldCursor = this._cursor; let newCursor = oldCursor + 1; const elements = oldFront._elements; const element = elements[oldCursor]; if (newCursor === QUEUE_MAX_ARRAY_SIZE) { newFront = oldFront._next; newCursor = 0; } // No mutations before this point. --this._size; this._cursor = newCursor; if (oldFront !== newFront) { this._front = newFront; } // Permit shifted element to be garbage collected. elements[oldCursor] = undefined; return element; } // The tricky thing about forEach() is that it can be called // re-entrantly. The queue may be mutated inside the callback. It is easy to // see that push() within the callback has no negative effects since the end // of the queue is checked for on every iteration. If shift() is called // repeatedly within the callback then the next iteration may return an // element that has been removed. In this case the callback will be called // with undefined values until we either "catch up" with elements that still // exist or reach the back of the queue. forEach(callback) { let i = this._cursor; let node = this._front; let elements = node._elements; while (i !== elements.length || node._next !== undefined) { if (i === elements.length) { node = node._next; elements = node._elements; i = 0; if (elements.length === 0) { break; } } callback(elements[i]); ++i; } } // Return the element that would be returned if shift() was called now, // without modifying the queue. peek() { // must not be called on an empty queue const front = this._front; const cursor = this._cursor; return front._elements[cursor]; } } const AbortSteps = Symbol('[[AbortSteps]]'); const ErrorSteps = Symbol('[[ErrorSteps]]'); const CancelSteps = Symbol('[[CancelSteps]]'); const PullSteps = Symbol('[[PullSteps]]'); const ReleaseSteps = Symbol('[[ReleaseSteps]]'); function ReadableStreamReaderGenericInitialize(reader, stream) { reader._ownerReadableStream = stream; stream._reader = reader; if (stream._state === 'readable') { defaultReaderClosedPromiseInitialize(reader); } else if (stream._state === 'closed') { defaultReaderClosedPromiseInitializeAsResolved(reader); } else { defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); } } // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state // check. function ReadableStreamReaderGenericCancel(reader, reason) { const stream = reader._ownerReadableStream; return ReadableStreamCancel(stream, reason); } function ReadableStreamReaderGenericRelease(reader) { const stream = reader._ownerReadableStream; if (stream._state === 'readable') { defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } else { defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); } stream._readableStreamController[ReleaseSteps](); stream._reader = undefined; reader._ownerReadableStream = undefined; } // Helper functions for the readers. function readerLockException(name) { return new TypeError('Cannot ' + name + ' a stream using a released reader'); } // Helper functions for the ReadableStreamDefaultReader. function defaultReaderClosedPromiseInitialize(reader) { reader._closedPromise = newPromise((resolve, reject) => { reader._closedPromise_resolve = resolve; reader._closedPromise_reject = reject; }); } function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseReject(reader, reason); } function defaultReaderClosedPromiseInitializeAsResolved(reader) { defaultReaderClosedPromiseInitialize(reader); defaultReaderClosedPromiseResolve(reader); } function defaultReaderClosedPromiseReject(reader, reason) { if (reader._closedPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(reader._closedPromise); reader._closedPromise_reject(reason); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } function defaultReaderClosedPromiseResetToRejected(reader, reason) { defaultReaderClosedPromiseInitializeAsRejected(reader, reason); } function defaultReaderClosedPromiseResolve(reader) { if (reader._closedPromise_resolve === undefined) { return; } reader._closedPromise_resolve(undefined); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } /// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill const NumberIsFinite = Number.isFinite || function (x) { return typeof x === 'number' && isFinite(x); }; /// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill const MathTrunc = Math.trunc || function (v) { return v < 0 ? Math.ceil(v) : Math.floor(v); }; // https://heycam.github.io/webidl/#idl-dictionaries function isDictionary(x) { return typeof x === 'object' || typeof x === 'function'; } function assertDictionary(obj, context) { if (obj !== undefined && !isDictionary(obj)) { throw new TypeError(`${context} is not an object.`); } } // https://heycam.github.io/webidl/#idl-callback-functions function assertFunction(x, context) { if (typeof x !== 'function') { throw new TypeError(`${context} is not a function.`); } } // https://heycam.github.io/webidl/#idl-object function isObject(x) { return (typeof x === 'object' && x !== null) || typeof x === 'function'; } function assertObject(x, context) { if (!isObject(x)) { throw new TypeError(`${context} is not an object.`); } } function assertRequiredArgument(x, position, context) { if (x === undefined) { throw new TypeError(`Parameter ${position} is required in '${context}'.`); } } function assertRequiredField(x, field, context) { if (x === undefined) { throw new TypeError(`${field} is required in '${context}'.`); } } // https://heycam.github.io/webidl/#idl-unrestricted-double function convertUnrestrictedDouble(value) { return Number(value); } function censorNegativeZero(x) { return x === 0 ? 0 : x; } function integerPart(x) { return censorNegativeZero(MathTrunc(x)); } // https://heycam.github.io/webidl/#idl-unsigned-long-long function convertUnsignedLongLongWithEnforceRange(value, context) { const lowerBound = 0; const upperBound = Number.MAX_SAFE_INTEGER; let x = Number(value); x = censorNegativeZero(x); if (!NumberIsFinite(x)) { throw new TypeError(`${context} is not a finite number`); } x = integerPart(x); if (x < lowerBound || x > upperBound) { throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); } if (!NumberIsFinite(x) || x === 0) { return 0; } // TODO Use BigInt if supported? // let xBigInt = BigInt(integerPart(x)); // xBigInt = BigInt.asUintN(64, xBigInt); // return Number(xBigInt); return x; } function assertReadableStream(x, context) { if (!IsReadableStream(x)) { throw new TypeError(`${context} is not a ReadableStream.`); } } // Abstract operations for the ReadableStream. function AcquireReadableStreamDefaultReader(stream) { return new ReadableStreamDefaultReader(stream); } // ReadableStream API exposed for controllers. function ReadableStreamAddReadRequest(stream, readRequest) { stream._reader._readRequests.push(readRequest); } function ReadableStreamFulfillReadRequest(stream, chunk, done) { const reader = stream._reader; const readRequest = reader._readRequests.shift(); if (done) { readRequest._closeSteps(); } else { readRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadRequests(stream) { return stream._reader._readRequests.length; } function ReadableStreamHasDefaultReader(stream) { const reader = stream._reader; if (reader === undefined) { return false; } if (!IsReadableStreamDefaultReader(reader)) { return false; } return true; } /** * A default reader vended by a {@link ReadableStream}. * * @public */ class ReadableStreamDefaultReader { constructor(stream) { assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); assertReadableStream(stream, 'First parameter'); if (IsReadableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive reading by another reader'); } ReadableStreamReaderGenericInitialize(this, stream); this._readRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException('closed')); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = undefined) { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('cancel')); } return ReadableStreamReaderGenericCancel(this, reason); } /** * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. * * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. */ read() { if (!IsReadableStreamDefaultReader(this)) { return promiseRejectedWith(defaultReaderBrandCheckException('read')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('read from')); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), _closeSteps: () => resolvePromise({ value: undefined, done: true }), _errorSteps: e => rejectPromise(e) }; ReadableStreamDefaultReaderRead(this, readRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamDefaultReader(this)) { throw defaultReaderBrandCheckException('releaseLock'); } if (this._ownerReadableStream === undefined) { return; } ReadableStreamDefaultReaderRelease(this); } } Object.defineProperties(ReadableStreamDefaultReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { value: 'ReadableStreamDefaultReader', configurable: true }); } // Abstract operations for the readers. function IsReadableStreamDefaultReader(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { return false; } return x instanceof ReadableStreamDefaultReader; } function ReadableStreamDefaultReaderRead(reader, readRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === 'closed') { readRequest._closeSteps(); } else if (stream._state === 'errored') { readRequest._errorSteps(stream._storedError); } else { stream._readableStreamController[PullSteps](readRequest); } } function ReadableStreamDefaultReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e = new TypeError('Reader was released'); ReadableStreamDefaultReaderErrorReadRequests(reader, e); } function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach(readRequest => { readRequest._errorSteps(e); }); } // Helper functions for the ReadableStreamDefaultReader. function defaultReaderBrandCheckException(name) { return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); } /// /* eslint-disable @typescript-eslint/no-empty-function */ const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); /// class ReadableStreamAsyncIteratorImpl { constructor(reader, preventCancel) { this._ongoingPromise = undefined; this._isFinished = false; this._reader = reader; this._preventCancel = preventCancel; } next() { const nextSteps = () => this._nextSteps(); this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); return this._ongoingPromise; } return(value) { const returnSteps = () => this._returnSteps(value); return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); } _nextSteps() { if (this._isFinished) { return Promise.resolve({ value: undefined, done: true }); } const reader = this._reader; let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readRequest = { _chunkSteps: chunk => { this._ongoingPromise = undefined; // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. // FIXME Is this a bug in the specification, or in the test? _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); }, _closeSteps: () => { this._ongoingPromise = undefined; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); resolvePromise({ value: undefined, done: true }); }, _errorSteps: reason => { this._ongoingPromise = undefined; this._isFinished = true; ReadableStreamReaderGenericRelease(reader); rejectPromise(reason); } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promise; } _returnSteps(value) { if (this._isFinished) { return Promise.resolve({ value, done: true }); } this._isFinished = true; const reader = this._reader; if (!this._preventCancel) { const result = ReadableStreamReaderGenericCancel(reader, value); ReadableStreamReaderGenericRelease(reader); return transformPromiseWith(result, () => ({ value, done: true })); } ReadableStreamReaderGenericRelease(reader); return promiseResolvedWith({ value, done: true }); } } const ReadableStreamAsyncIteratorPrototype = { next() { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); } return this._asyncIteratorImpl.next(); }, return(value) { if (!IsReadableStreamAsyncIterator(this)) { return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); } return this._asyncIteratorImpl.return(value); } }; Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); // Abstract operations for the ReadableStream. function AcquireReadableStreamAsyncIterator(stream, preventCancel) { const reader = AcquireReadableStreamDefaultReader(stream); const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); iterator._asyncIteratorImpl = impl; return iterator; } function IsReadableStreamAsyncIterator(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { return false; } try { // noinspection SuspiciousTypeOfGuard return x._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; } catch (_a) { return false; } } // Helper functions for the ReadableStream. function streamAsyncIteratorBrandCheckException(name) { return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); } /// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill const NumberIsNaN = Number.isNaN || function (x) { // eslint-disable-next-line no-self-compare return x !== x; }; var _a, _b, _c; function CreateArrayFromList(elements) { // We use arrays to represent lists, so this is basically a no-op. // Do a slice though just in case we happen to depend on the unique-ness. return elements.slice(); } function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); } let TransferArrayBuffer = (O) => { if (typeof O.transfer === 'function') { TransferArrayBuffer = buffer => buffer.transfer(); } else if (typeof structuredClone === 'function') { TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); } else { // Not implemented correctly TransferArrayBuffer = buffer => buffer; } return TransferArrayBuffer(O); }; let IsDetachedBuffer = (O) => { if (typeof O.detached === 'boolean') { IsDetachedBuffer = buffer => buffer.detached; } else { // Not implemented correctly IsDetachedBuffer = buffer => buffer.byteLength === 0; } return IsDetachedBuffer(O); }; function ArrayBufferSlice(buffer, begin, end) { // ArrayBuffer.prototype.slice is not available on IE10 // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice if (buffer.slice) { return buffer.slice(begin, end); } const length = end - begin; const slice = new ArrayBuffer(length); CopyDataBlockBytes(slice, 0, buffer, begin, length); return slice; } function GetMethod(receiver, prop) { const func = receiver[prop]; if (func === undefined || func === null) { return undefined; } if (typeof func !== 'function') { throw new TypeError(`${String(prop)} is not a function`); } return func; } function CreateAsyncFromSyncIterator(syncIteratorRecord) { // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, // we use yield* inside an async generator function to achieve the same result. // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. const syncIterable = { [Symbol.iterator]: () => syncIteratorRecord.iterator }; // Create an async generator function and immediately invoke it. const asyncIterator = (async function* () { return yield* syncIterable; }()); // Return as an async iterator record. const nextMethod = asyncIterator.next; return { iterator: asyncIterator, nextMethod, done: false }; } // Aligns with core-js/modules/es.symbol.async-iterator.js const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, 'Symbol.asyncIterator')) !== null && _c !== void 0 ? _c : '@@asyncIterator'; function GetIterator(obj, hint = 'sync', method) { if (method === undefined) { if (hint === 'async') { method = GetMethod(obj, SymbolAsyncIterator); if (method === undefined) { const syncMethod = GetMethod(obj, Symbol.iterator); const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); return CreateAsyncFromSyncIterator(syncIteratorRecord); } } else { method = GetMethod(obj, Symbol.iterator); } } if (method === undefined) { throw new TypeError('The object is not iterable'); } const iterator = reflectCall(method, obj, []); if (!typeIsObject(iterator)) { throw new TypeError('The iterator method must return an object'); } const nextMethod = iterator.next; return { iterator, nextMethod, done: false }; } function IteratorNext(iteratorRecord) { const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); if (!typeIsObject(result)) { throw new TypeError('The iterator.next() method must return an object'); } return result; } function IteratorComplete(iterResult) { return Boolean(iterResult.done); } function IteratorValue(iterResult) { return iterResult.value; } function IsNonNegativeNumber(v) { if (typeof v !== 'number') { return false; } if (NumberIsNaN(v)) { return false; } if (v < 0) { return false; } return true; } function CloneAsUint8Array(O) { const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); return new Uint8Array(buffer); } function DequeueValue(container) { const pair = container._queue.shift(); container._queueTotalSize -= pair.size; if (container._queueTotalSize < 0) { container._queueTotalSize = 0; } return pair.value; } function EnqueueValueWithSize(container, value, size) { if (!IsNonNegativeNumber(size) || size === Infinity) { throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); } container._queue.push({ value, size }); container._queueTotalSize += size; } function PeekQueueValue(container) { const pair = container._queue.peek(); return pair.value; } function ResetQueue(container) { container._queue = new SimpleQueue(); container._queueTotalSize = 0; } function isDataViewConstructor(ctor) { return ctor === DataView; } function isDataView(view) { return isDataViewConstructor(view.constructor); } function arrayBufferViewElementSize(ctor) { if (isDataViewConstructor(ctor)) { return 1; } return ctor.BYTES_PER_ELEMENT; } /** * A pull-into request in a {@link ReadableByteStreamController}. * * @public */ class ReadableStreamBYOBRequest { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. */ get view() { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException('view'); } return this._view; } respond(bytesWritten) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException('respond'); } assertRequiredArgument(bytesWritten, 1, 'respond'); bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); if (this._associatedReadableByteStreamController === undefined) { throw new TypeError('This BYOB request has been invalidated'); } if (IsDetachedBuffer(this._view.buffer)) { throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); } ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); } respondWithNewView(view) { if (!IsReadableStreamBYOBRequest(this)) { throw byobRequestBrandCheckException('respondWithNewView'); } assertRequiredArgument(view, 1, 'respondWithNewView'); if (!ArrayBuffer.isView(view)) { throw new TypeError('You can only respond with array buffer views'); } if (this._associatedReadableByteStreamController === undefined) { throw new TypeError('This BYOB request has been invalidated'); } if (IsDetachedBuffer(view.buffer)) { throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); } ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); } } Object.defineProperties(ReadableStreamBYOBRequest.prototype, { respond: { enumerable: true }, respondWithNewView: { enumerable: true }, view: { enumerable: true } }); setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { value: 'ReadableStreamBYOBRequest', configurable: true }); } /** * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. * * @public */ class ReadableByteStreamController { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the current BYOB pull request, or `null` if there isn't one. */ get byobRequest() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('byobRequest'); } return ReadableByteStreamControllerGetBYOBRequest(this); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('desiredSize'); } return ReadableByteStreamControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('close'); } if (this._closeRequested) { throw new TypeError('The stream has already been closed; do not close it again!'); } const state = this._controlledReadableByteStream._state; if (state !== 'readable') { throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); } ReadableByteStreamControllerClose(this); } enqueue(chunk) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('enqueue'); } assertRequiredArgument(chunk, 1, 'enqueue'); if (!ArrayBuffer.isView(chunk)) { throw new TypeError('chunk must be an array buffer view'); } if (chunk.byteLength === 0) { throw new TypeError('chunk must have non-zero byteLength'); } if (chunk.buffer.byteLength === 0) { throw new TypeError(`chunk's buffer must have non-zero byteLength`); } if (this._closeRequested) { throw new TypeError('stream is closed or draining'); } const state = this._controlledReadableByteStream._state; if (state !== 'readable') { throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); } ReadableByteStreamControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e = undefined) { if (!IsReadableByteStreamController(this)) { throw byteStreamControllerBrandCheckException('error'); } ReadableByteStreamControllerError(this, e); } /** @internal */ [CancelSteps](reason) { ReadableByteStreamControllerClearPendingPullIntos(this); ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableByteStreamControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableByteStream; if (this._queueTotalSize > 0) { ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); return; } const autoAllocateChunkSize = this._autoAllocateChunkSize; if (autoAllocateChunkSize !== undefined) { let buffer; try { buffer = new ArrayBuffer(autoAllocateChunkSize); } catch (bufferE) { readRequest._errorSteps(bufferE); return; } const pullIntoDescriptor = { buffer, bufferByteLength: autoAllocateChunkSize, byteOffset: 0, byteLength: autoAllocateChunkSize, bytesFilled: 0, minimumFill: 1, elementSize: 1, viewConstructor: Uint8Array, readerType: 'default' }; this._pendingPullIntos.push(pullIntoDescriptor); } ReadableStreamAddReadRequest(stream, readRequest); ReadableByteStreamControllerCallPullIfNeeded(this); } /** @internal */ [ReleaseSteps]() { if (this._pendingPullIntos.length > 0) { const firstPullInto = this._pendingPullIntos.peek(); firstPullInto.readerType = 'none'; this._pendingPullIntos = new SimpleQueue(); this._pendingPullIntos.push(firstPullInto); } } } Object.defineProperties(ReadableByteStreamController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, byobRequest: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(ReadableByteStreamController.prototype.close, 'close'); setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); setFunctionName(ReadableByteStreamController.prototype.error, 'error'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { value: 'ReadableByteStreamController', configurable: true }); } // Abstract operations for the ReadableByteStreamController. function IsReadableByteStreamController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { return false; } return x instanceof ReadableByteStreamController; } function IsReadableStreamBYOBRequest(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { return false; } return x instanceof ReadableStreamBYOBRequest; } function ReadableByteStreamControllerCallPullIfNeeded(controller) { const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; // TODO: Test controller argument const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableByteStreamControllerCallPullIfNeeded(controller); } return null; }, e => { ReadableByteStreamControllerError(controller, e); return null; }); } function ReadableByteStreamControllerClearPendingPullIntos(controller) { ReadableByteStreamControllerInvalidateBYOBRequest(controller); controller._pendingPullIntos = new SimpleQueue(); } function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { let done = false; if (stream._state === 'closed') { done = true; } const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); if (pullIntoDescriptor.readerType === 'default') { ReadableStreamFulfillReadRequest(stream, filledView, done); } else { ReadableStreamFulfillReadIntoRequest(stream, filledView, done); } } function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { const bytesFilled = pullIntoDescriptor.bytesFilled; const elementSize = pullIntoDescriptor.elementSize; return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); } function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { controller._queue.push({ buffer, byteOffset, byteLength }); controller._queueTotalSize += byteLength; } function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { let clonedChunk; try { clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); } catch (cloneE) { ReadableByteStreamControllerError(controller, cloneE); throw cloneE; } ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); } function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { if (firstDescriptor.bytesFilled > 0) { ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); } ReadableByteStreamControllerShiftPendingPullInto(controller); } function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; let totalBytesToCopyRemaining = maxBytesToCopy; let ready = false; const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; const maxAlignedBytes = maxBytesFilled - remainderBytes; // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head // of the queue, so the underlying source can keep filling it. if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; ready = true; } const queue = controller._queue; while (totalBytesToCopyRemaining > 0) { const headOfQueue = queue.peek(); const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); if (headOfQueue.byteLength === bytesToCopy) { queue.shift(); } else { headOfQueue.byteOffset += bytesToCopy; headOfQueue.byteLength -= bytesToCopy; } controller._queueTotalSize -= bytesToCopy; ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); totalBytesToCopyRemaining -= bytesToCopy; } return ready; } function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { pullIntoDescriptor.bytesFilled += size; } function ReadableByteStreamControllerHandleQueueDrain(controller) { if (controller._queueTotalSize === 0 && controller._closeRequested) { ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(controller._controlledReadableByteStream); } else { ReadableByteStreamControllerCallPullIfNeeded(controller); } } function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { if (controller._byobRequest === null) { return; } controller._byobRequest._associatedReadableByteStreamController = undefined; controller._byobRequest._view = null; controller._byobRequest = null; } function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { while (controller._pendingPullIntos.length > 0) { if (controller._queueTotalSize === 0) { return; } const pullIntoDescriptor = controller._pendingPullIntos.peek(); if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); } } } function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { const reader = controller._controlledReadableByteStream._reader; while (reader._readRequests.length > 0) { if (controller._queueTotalSize === 0) { return; } const readRequest = reader._readRequests.shift(); ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); } } function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { const stream = controller._controlledReadableByteStream; const ctor = view.constructor; const elementSize = arrayBufferViewElementSize(ctor); const { byteOffset, byteLength } = view; const minimumFill = min * elementSize; let buffer; try { buffer = TransferArrayBuffer(view.buffer); } catch (e) { readIntoRequest._errorSteps(e); return; } const pullIntoDescriptor = { buffer, bufferByteLength: buffer.byteLength, byteOffset, byteLength, bytesFilled: 0, minimumFill, elementSize, viewConstructor: ctor, readerType: 'byob' }; if (controller._pendingPullIntos.length > 0) { controller._pendingPullIntos.push(pullIntoDescriptor); // No ReadableByteStreamControllerCallPullIfNeeded() call since: // - No change happens on desiredSize // - The source has already been notified of that there's at least 1 pending read(view) ReadableStreamAddReadIntoRequest(stream, readIntoRequest); return; } if (stream._state === 'closed') { const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); readIntoRequest._closeSteps(emptyView); return; } if (controller._queueTotalSize > 0) { if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); ReadableByteStreamControllerHandleQueueDrain(controller); readIntoRequest._chunkSteps(filledView); return; } if (controller._closeRequested) { const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); ReadableByteStreamControllerError(controller, e); readIntoRequest._errorSteps(e); return; } } controller._pendingPullIntos.push(pullIntoDescriptor); ReadableStreamAddReadIntoRequest(stream, readIntoRequest); ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { if (firstDescriptor.readerType === 'none') { ReadableByteStreamControllerShiftPendingPullInto(controller); } const stream = controller._controlledReadableByteStream; if (ReadableStreamHasBYOBReader(stream)) { while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); } } } function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); if (pullIntoDescriptor.readerType === 'none') { ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); return; } if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head // of the queue, so the underlying source can keep filling it. return; } ReadableByteStreamControllerShiftPendingPullInto(controller); const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; if (remainderSize > 0) { const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); } pullIntoDescriptor.bytesFilled -= remainderSize; ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); ReadableByteStreamControllerInvalidateBYOBRequest(controller); const state = controller._controlledReadableByteStream._state; if (state === 'closed') { ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); } else { ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerShiftPendingPullInto(controller) { const descriptor = controller._pendingPullIntos.shift(); return descriptor; } function ReadableByteStreamControllerShouldCallPull(controller) { const stream = controller._controlledReadableByteStream; if (stream._state !== 'readable') { return false; } if (controller._closeRequested) { return false; } if (!controller._started) { return false; } if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { return true; } const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableByteStreamControllerClearAlgorithms(controller) { controller._pullAlgorithm = undefined; controller._cancelAlgorithm = undefined; } // A client of ReadableByteStreamController may use these functions directly to bypass state check. function ReadableByteStreamControllerClose(controller) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== 'readable') { return; } if (controller._queueTotalSize > 0) { controller._closeRequested = true; return; } if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); ReadableByteStreamControllerError(controller, e); throw e; } } ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamClose(stream); } function ReadableByteStreamControllerEnqueue(controller, chunk) { const stream = controller._controlledReadableByteStream; if (controller._closeRequested || stream._state !== 'readable') { return; } const { buffer, byteOffset, byteLength } = chunk; if (IsDetachedBuffer(buffer)) { throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); } const transferredBuffer = TransferArrayBuffer(buffer); if (controller._pendingPullIntos.length > 0) { const firstPendingPullInto = controller._pendingPullIntos.peek(); if (IsDetachedBuffer(firstPendingPullInto.buffer)) { throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); } ReadableByteStreamControllerInvalidateBYOBRequest(controller); firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); if (firstPendingPullInto.readerType === 'none') { ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); } } if (ReadableStreamHasDefaultReader(stream)) { ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); if (ReadableStreamGetNumReadRequests(stream) === 0) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } else { if (controller._pendingPullIntos.length > 0) { ReadableByteStreamControllerShiftPendingPullInto(controller); } const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); ReadableStreamFulfillReadRequest(stream, transferredView, false); } } else if (ReadableStreamHasBYOBReader(stream)) { // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } else { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } ReadableByteStreamControllerCallPullIfNeeded(controller); } function ReadableByteStreamControllerError(controller, e) { const stream = controller._controlledReadableByteStream; if (stream._state !== 'readable') { return; } ReadableByteStreamControllerClearPendingPullIntos(controller); ResetQueue(controller); ReadableByteStreamControllerClearAlgorithms(controller); ReadableStreamError(stream, e); } function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { const entry = controller._queue.shift(); controller._queueTotalSize -= entry.byteLength; ReadableByteStreamControllerHandleQueueDrain(controller); const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); readRequest._chunkSteps(view); } function ReadableByteStreamControllerGetBYOBRequest(controller) { if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { const firstDescriptor = controller._pendingPullIntos.peek(); const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); SetUpReadableStreamBYOBRequest(byobRequest, controller, view); controller._byobRequest = byobRequest; } return controller._byobRequest; } function ReadableByteStreamControllerGetDesiredSize(controller) { const state = controller._controlledReadableByteStream._state; if (state === 'errored') { return null; } if (state === 'closed') { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableByteStreamControllerRespond(controller, bytesWritten) { const firstDescriptor = controller._pendingPullIntos.peek(); const state = controller._controlledReadableByteStream._state; if (state === 'closed') { if (bytesWritten !== 0) { throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); } } else { if (bytesWritten === 0) { throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); } if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { throw new RangeError('bytesWritten out of range'); } } firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); ReadableByteStreamControllerRespondInternal(controller, bytesWritten); } function ReadableByteStreamControllerRespondWithNewView(controller, view) { const firstDescriptor = controller._pendingPullIntos.peek(); const state = controller._controlledReadableByteStream._state; if (state === 'closed') { if (view.byteLength !== 0) { throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); } } else { if (view.byteLength === 0) { throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); } } if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { throw new RangeError('The region specified by view does not match byobRequest'); } if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { throw new RangeError('The buffer of view has different capacity than byobRequest'); } if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { throw new RangeError('The region specified by view is larger than byobRequest'); } const viewByteLength = view.byteLength; firstDescriptor.buffer = TransferArrayBuffer(view.buffer); ReadableByteStreamControllerRespondInternal(controller, viewByteLength); } function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { controller._controlledReadableByteStream = stream; controller._pullAgain = false; controller._pulling = false; controller._byobRequest = null; // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. controller._queue = controller._queueTotalSize = undefined; ResetQueue(controller); controller._closeRequested = false; controller._started = false; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._autoAllocateChunkSize = autoAllocateChunkSize; controller._pendingPullIntos = new SimpleQueue(); stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableByteStreamControllerCallPullIfNeeded(controller); return null; }, r => { ReadableByteStreamControllerError(controller, r); return null; }); } function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { const controller = Object.create(ReadableByteStreamController.prototype); let startAlgorithm; let pullAlgorithm; let cancelAlgorithm; if (underlyingByteSource.start !== undefined) { startAlgorithm = () => underlyingByteSource.start(controller); } else { startAlgorithm = () => undefined; } if (underlyingByteSource.pull !== undefined) { pullAlgorithm = () => underlyingByteSource.pull(controller); } else { pullAlgorithm = () => promiseResolvedWith(undefined); } if (underlyingByteSource.cancel !== undefined) { cancelAlgorithm = reason => underlyingByteSource.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(undefined); } const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; if (autoAllocateChunkSize === 0) { throw new TypeError('autoAllocateChunkSize must be greater than 0'); } SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); } function SetUpReadableStreamBYOBRequest(request, controller, view) { request._associatedReadableByteStreamController = controller; request._view = view; } // Helper functions for the ReadableStreamBYOBRequest. function byobRequestBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); } // Helper functions for the ReadableByteStreamController. function byteStreamControllerBrandCheckException(name) { return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); } function convertReaderOptions(options, context) { assertDictionary(options, context); const mode = options === null || options === void 0 ? void 0 : options.mode; return { mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) }; } function convertReadableStreamReaderMode(mode, context) { mode = `${mode}`; if (mode !== 'byob') { throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); } return mode; } function convertByobReadOptions(options, context) { var _a; assertDictionary(options, context); const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; return { min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) }; } // Abstract operations for the ReadableStream. function AcquireReadableStreamBYOBReader(stream) { return new ReadableStreamBYOBReader(stream); } // ReadableStream API exposed for controllers. function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { stream._reader._readIntoRequests.push(readIntoRequest); } function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { const reader = stream._reader; const readIntoRequest = reader._readIntoRequests.shift(); if (done) { readIntoRequest._closeSteps(chunk); } else { readIntoRequest._chunkSteps(chunk); } } function ReadableStreamGetNumReadIntoRequests(stream) { return stream._reader._readIntoRequests.length; } function ReadableStreamHasBYOBReader(stream) { const reader = stream._reader; if (reader === undefined) { return false; } if (!IsReadableStreamBYOBReader(reader)) { return false; } return true; } /** * A BYOB reader vended by a {@link ReadableStream}. * * @public */ class ReadableStreamBYOBReader { constructor(stream) { assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); assertReadableStream(stream, 'First parameter'); if (IsReadableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive reading by another reader'); } if (!IsReadableByteStreamController(stream._readableStreamController)) { throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + 'source'); } ReadableStreamReaderGenericInitialize(this, stream); this._readIntoRequests = new SimpleQueue(); } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the reader's lock is released before the stream finishes closing. */ get closed() { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException('closed')); } return this._closedPromise; } /** * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. */ cancel(reason = undefined) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException('cancel')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('cancel')); } return ReadableStreamReaderGenericCancel(this, reason); } read(view, rawOptions = {}) { if (!IsReadableStreamBYOBReader(this)) { return promiseRejectedWith(byobReaderBrandCheckException('read')); } if (!ArrayBuffer.isView(view)) { return promiseRejectedWith(new TypeError('view must be an array buffer view')); } if (view.byteLength === 0) { return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); } if (view.buffer.byteLength === 0) { return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); } if (IsDetachedBuffer(view.buffer)) { return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); } let options; try { options = convertByobReadOptions(rawOptions, 'options'); } catch (e) { return promiseRejectedWith(e); } const min = options.min; if (min === 0) { return promiseRejectedWith(new TypeError('options.min must be greater than 0')); } if (!isDataView(view)) { if (min > view.length) { return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); } } else if (min > view.byteLength) { return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); } if (this._ownerReadableStream === undefined) { return promiseRejectedWith(readerLockException('read from')); } let resolvePromise; let rejectPromise; const promise = newPromise((resolve, reject) => { resolvePromise = resolve; rejectPromise = reject; }); const readIntoRequest = { _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), _errorSteps: e => rejectPromise(e) }; ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); return promise; } /** * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. * If the associated stream is errored when the lock is released, the reader will appear errored in the same way * from now on; otherwise, the reader will appear closed. * * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to * do so will throw a `TypeError` and leave the reader locked to the stream. */ releaseLock() { if (!IsReadableStreamBYOBReader(this)) { throw byobReaderBrandCheckException('releaseLock'); } if (this._ownerReadableStream === undefined) { return; } ReadableStreamBYOBReaderRelease(this); } } Object.defineProperties(ReadableStreamBYOBReader.prototype, { cancel: { enumerable: true }, read: { enumerable: true }, releaseLock: { enumerable: true }, closed: { enumerable: true } }); setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { value: 'ReadableStreamBYOBReader', configurable: true }); } // Abstract operations for the readers. function IsReadableStreamBYOBReader(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { return false; } return x instanceof ReadableStreamBYOBReader; } function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { const stream = reader._ownerReadableStream; stream._disturbed = true; if (stream._state === 'errored') { readIntoRequest._errorSteps(stream._storedError); } else { ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); } } function ReadableStreamBYOBReaderRelease(reader) { ReadableStreamReaderGenericRelease(reader); const e = new TypeError('Reader was released'); ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); } function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { const readIntoRequests = reader._readIntoRequests; reader._readIntoRequests = new SimpleQueue(); readIntoRequests.forEach(readIntoRequest => { readIntoRequest._errorSteps(e); }); } // Helper functions for the ReadableStreamBYOBReader. function byobReaderBrandCheckException(name) { return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); } function ExtractHighWaterMark(strategy, defaultHWM) { const { highWaterMark } = strategy; if (highWaterMark === undefined) { return defaultHWM; } if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { throw new RangeError('Invalid highWaterMark'); } return highWaterMark; } function ExtractSizeAlgorithm(strategy) { const { size } = strategy; if (!size) { return () => 1; } return size; } function convertQueuingStrategy(init, context) { assertDictionary(init, context); const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; const size = init === null || init === void 0 ? void 0 : init.size; return { highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) }; } function convertQueuingStrategySize(fn, context) { assertFunction(fn, context); return chunk => convertUnrestrictedDouble(fn(chunk)); } function convertUnderlyingSink(original, context) { assertDictionary(original, context); const abort = original === null || original === void 0 ? void 0 : original.abort; const close = original === null || original === void 0 ? void 0 : original.close; const start = original === null || original === void 0 ? void 0 : original.start; const type = original === null || original === void 0 ? void 0 : original.type; const write = original === null || original === void 0 ? void 0 : original.write; return { abort: abort === undefined ? undefined : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), close: close === undefined ? undefined : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), start: start === undefined ? undefined : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), write: write === undefined ? undefined : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), type }; } function convertUnderlyingSinkAbortCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } function convertUnderlyingSinkCloseCallback(fn, original, context) { assertFunction(fn, context); return () => promiseCall(fn, original, []); } function convertUnderlyingSinkStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertUnderlyingSinkWriteCallback(fn, original, context) { assertFunction(fn, context); return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); } function assertWritableStream(x, context) { if (!IsWritableStream(x)) { throw new TypeError(`${context} is not a WritableStream.`); } } function isAbortSignal(value) { if (typeof value !== 'object' || value === null) { return false; } try { return typeof value.aborted === 'boolean'; } catch (_a) { // AbortSignal.prototype.aborted throws if its brand check fails return false; } } const supportsAbortController = typeof AbortController === 'function'; /** * Construct a new AbortController, if supported by the platform. * * @internal */ function createAbortController() { if (supportsAbortController) { return new AbortController(); } return undefined; } /** * A writable stream represents a destination for data, into which you can write. * * @public */ class WritableStream { constructor(rawUnderlyingSink = {}, rawStrategy = {}) { if (rawUnderlyingSink === undefined) { rawUnderlyingSink = null; } else { assertObject(rawUnderlyingSink, 'First parameter'); } const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); InitializeWritableStream(this); const type = underlyingSink.type; if (type !== undefined) { throw new RangeError('Invalid type is specified'); } const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); } /** * Returns whether or not the writable stream is locked to a writer. */ get locked() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2('locked'); } return IsWritableStreamLocked(this); } /** * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort * mechanism of the underlying sink. * * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel * the stream) if the stream is currently locked. */ abort(reason = undefined) { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2('abort')); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); } return WritableStreamAbort(this, reason); } /** * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its * close behavior. During this time any further attempts to write will fail (without erroring the stream). * * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. */ close() { if (!IsWritableStream(this)) { return promiseRejectedWith(streamBrandCheckException$2('close')); } if (IsWritableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); } if (WritableStreamCloseQueuedOrInFlight(this)) { return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); } return WritableStreamClose(this); } /** * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream * is locked, no other writer can be acquired until this one is released. * * This functionality is especially useful for creating abstractions that desire the ability to write to a stream * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at * the same time, which would cause the resulting written data to be unpredictable and probably useless. */ getWriter() { if (!IsWritableStream(this)) { throw streamBrandCheckException$2('getWriter'); } return AcquireWritableStreamDefaultWriter(this); } } Object.defineProperties(WritableStream.prototype, { abort: { enumerable: true }, close: { enumerable: true }, getWriter: { enumerable: true }, locked: { enumerable: true } }); setFunctionName(WritableStream.prototype.abort, 'abort'); setFunctionName(WritableStream.prototype.close, 'close'); setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { value: 'WritableStream', configurable: true }); } // Abstract operations for the WritableStream. function AcquireWritableStreamDefaultWriter(stream) { return new WritableStreamDefaultWriter(stream); } // Throws if and only if startAlgorithm throws. function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(WritableStream.prototype); InitializeWritableStream(stream); const controller = Object.create(WritableStreamDefaultController.prototype); SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); return stream; } function InitializeWritableStream(stream) { stream._state = 'writable'; // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is // 'erroring' or 'errored'. May be set to an undefined value. stream._storedError = undefined; stream._writer = undefined; // Initialize to undefined first because the constructor of the controller checks this // variable to validate the caller. stream._writableStreamController = undefined; // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data // producer without waiting for the queued writes to finish. stream._writeRequests = new SimpleQueue(); // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. stream._inFlightWriteRequest = undefined; // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer // has been detached. stream._closeRequest = undefined; // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. stream._inFlightCloseRequest = undefined; // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. stream._pendingAbortRequest = undefined; // The backpressure signal set by the controller. stream._backpressure = false; } function IsWritableStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { return false; } return x instanceof WritableStream; } function IsWritableStreamLocked(stream) { if (stream._writer === undefined) { return false; } return true; } function WritableStreamAbort(stream, reason) { var _a; if (stream._state === 'closed' || stream._state === 'errored') { return promiseResolvedWith(undefined); } stream._writableStreamController._abortReason = reason; (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', // but it doesn't know that signaling abort runs author code that might have changed the state. // Widen the type again by casting to WritableStreamState. const state = stream._state; if (state === 'closed' || state === 'errored') { return promiseResolvedWith(undefined); } if (stream._pendingAbortRequest !== undefined) { return stream._pendingAbortRequest._promise; } let wasAlreadyErroring = false; if (state === 'erroring') { wasAlreadyErroring = true; // reason will not be used, so don't keep a reference to it. reason = undefined; } const promise = newPromise((resolve, reject) => { stream._pendingAbortRequest = { _promise: undefined, _resolve: resolve, _reject: reject, _reason: reason, _wasAlreadyErroring: wasAlreadyErroring }; }); stream._pendingAbortRequest._promise = promise; if (!wasAlreadyErroring) { WritableStreamStartErroring(stream, reason); } return promise; } function WritableStreamClose(stream) { const state = stream._state; if (state === 'closed' || state === 'errored') { return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); } const promise = newPromise((resolve, reject) => { const closeRequest = { _resolve: resolve, _reject: reject }; stream._closeRequest = closeRequest; }); const writer = stream._writer; if (writer !== undefined && stream._backpressure && state === 'writable') { defaultWriterReadyPromiseResolve(writer); } WritableStreamDefaultControllerClose(stream._writableStreamController); return promise; } // WritableStream API exposed for controllers. function WritableStreamAddWriteRequest(stream) { const promise = newPromise((resolve, reject) => { const writeRequest = { _resolve: resolve, _reject: reject }; stream._writeRequests.push(writeRequest); }); return promise; } function WritableStreamDealWithRejection(stream, error) { const state = stream._state; if (state === 'writable') { WritableStreamStartErroring(stream, error); return; } WritableStreamFinishErroring(stream); } function WritableStreamStartErroring(stream, reason) { const controller = stream._writableStreamController; stream._state = 'erroring'; stream._storedError = reason; const writer = stream._writer; if (writer !== undefined) { WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); } if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { WritableStreamFinishErroring(stream); } } function WritableStreamFinishErroring(stream) { stream._state = 'errored'; stream._writableStreamController[ErrorSteps](); const storedError = stream._storedError; stream._writeRequests.forEach(writeRequest => { writeRequest._reject(storedError); }); stream._writeRequests = new SimpleQueue(); if (stream._pendingAbortRequest === undefined) { WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const abortRequest = stream._pendingAbortRequest; stream._pendingAbortRequest = undefined; if (abortRequest._wasAlreadyErroring) { abortRequest._reject(storedError); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); uponPromise(promise, () => { abortRequest._resolve(); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return null; }, (reason) => { abortRequest._reject(reason); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return null; }); } function WritableStreamFinishInFlightWrite(stream) { stream._inFlightWriteRequest._resolve(undefined); stream._inFlightWriteRequest = undefined; } function WritableStreamFinishInFlightWriteWithError(stream, error) { stream._inFlightWriteRequest._reject(error); stream._inFlightWriteRequest = undefined; WritableStreamDealWithRejection(stream, error); } function WritableStreamFinishInFlightClose(stream) { stream._inFlightCloseRequest._resolve(undefined); stream._inFlightCloseRequest = undefined; const state = stream._state; if (state === 'erroring') { // The error was too late to do anything, so it is ignored. stream._storedError = undefined; if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._resolve(); stream._pendingAbortRequest = undefined; } } stream._state = 'closed'; const writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseResolve(writer); } } function WritableStreamFinishInFlightCloseWithError(stream, error) { stream._inFlightCloseRequest._reject(error); stream._inFlightCloseRequest = undefined; // Never execute sink abort() after sink close(). if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._reject(error); stream._pendingAbortRequest = undefined; } WritableStreamDealWithRejection(stream, error); } // TODO(ricea): Fix alphabetical order. function WritableStreamCloseQueuedOrInFlight(stream) { if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamHasOperationMarkedInFlight(stream) { if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamMarkCloseRequestInFlight(stream) { stream._inFlightCloseRequest = stream._closeRequest; stream._closeRequest = undefined; } function WritableStreamMarkFirstWriteRequestInFlight(stream) { stream._inFlightWriteRequest = stream._writeRequests.shift(); } function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { if (stream._closeRequest !== undefined) { stream._closeRequest._reject(stream._storedError); stream._closeRequest = undefined; } const writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseReject(writer, stream._storedError); } } function WritableStreamUpdateBackpressure(stream, backpressure) { const writer = stream._writer; if (writer !== undefined && backpressure !== stream._backpressure) { if (backpressure) { defaultWriterReadyPromiseReset(writer); } else { defaultWriterReadyPromiseResolve(writer); } } stream._backpressure = backpressure; } /** * A default writer vended by a {@link WritableStream}. * * @public */ class WritableStreamDefaultWriter { constructor(stream) { assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); assertWritableStream(stream, 'First parameter'); if (IsWritableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive writing by another writer'); } this._ownerWritableStream = stream; stream._writer = this; const state = stream._state; if (state === 'writable') { if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { defaultWriterReadyPromiseInitialize(this); } else { defaultWriterReadyPromiseInitializeAsResolved(this); } defaultWriterClosedPromiseInitialize(this); } else if (state === 'erroring') { defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); defaultWriterClosedPromiseInitialize(this); } else if (state === 'closed') { defaultWriterReadyPromiseInitializeAsResolved(this); defaultWriterClosedPromiseInitializeAsResolved(this); } else { const storedError = stream._storedError; defaultWriterReadyPromiseInitializeAsRejected(this, storedError); defaultWriterClosedPromiseInitializeAsRejected(this, storedError); } } /** * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or * the writer’s lock is released before the stream finishes closing. */ get closed() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('closed')); } return this._closedPromise; } /** * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. * A producer can use this information to determine the right amount of data to write. * * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when * the writer’s lock is released. */ get desiredSize() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException('desiredSize'); } if (this._ownerWritableStream === undefined) { throw defaultWriterLockException('desiredSize'); } return WritableStreamDefaultWriterGetDesiredSize(this); } /** * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips * back to zero or below, the getter will return a new promise that stays pending until the next transition. * * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become * rejected. */ get ready() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('ready')); } return this._readyPromise; } /** * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. */ abort(reason = undefined) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('abort')); } if (this._ownerWritableStream === undefined) { return promiseRejectedWith(defaultWriterLockException('abort')); } return WritableStreamDefaultWriterAbort(this, reason); } /** * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. */ close() { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('close')); } const stream = this._ownerWritableStream; if (stream === undefined) { return promiseRejectedWith(defaultWriterLockException('close')); } if (WritableStreamCloseQueuedOrInFlight(stream)) { return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); } return WritableStreamDefaultWriterClose(this); } /** * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from * now on; otherwise, the writer will appear closed. * * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents * other producers from writing in an interleaved manner. */ releaseLock() { if (!IsWritableStreamDefaultWriter(this)) { throw defaultWriterBrandCheckException('releaseLock'); } const stream = this._ownerWritableStream; if (stream === undefined) { return; } WritableStreamDefaultWriterRelease(this); } write(chunk = undefined) { if (!IsWritableStreamDefaultWriter(this)) { return promiseRejectedWith(defaultWriterBrandCheckException('write')); } if (this._ownerWritableStream === undefined) { return promiseRejectedWith(defaultWriterLockException('write to')); } return WritableStreamDefaultWriterWrite(this, chunk); } } Object.defineProperties(WritableStreamDefaultWriter.prototype, { abort: { enumerable: true }, close: { enumerable: true }, releaseLock: { enumerable: true }, write: { enumerable: true }, closed: { enumerable: true }, desiredSize: { enumerable: true }, ready: { enumerable: true } }); setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { value: 'WritableStreamDefaultWriter', configurable: true }); } // Abstract operations for the WritableStreamDefaultWriter. function IsWritableStreamDefaultWriter(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { return false; } return x instanceof WritableStreamDefaultWriter; } // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. function WritableStreamDefaultWriterAbort(writer, reason) { const stream = writer._ownerWritableStream; return WritableStreamAbort(stream, reason); } function WritableStreamDefaultWriterClose(writer) { const stream = writer._ownerWritableStream; return WritableStreamClose(stream); } function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { const stream = writer._ownerWritableStream; const state = stream._state; if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { return promiseResolvedWith(undefined); } if (state === 'errored') { return promiseRejectedWith(stream._storedError); } return WritableStreamDefaultWriterClose(writer); } function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { if (writer._closedPromiseState === 'pending') { defaultWriterClosedPromiseReject(writer, error); } else { defaultWriterClosedPromiseResetToRejected(writer, error); } } function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { if (writer._readyPromiseState === 'pending') { defaultWriterReadyPromiseReject(writer, error); } else { defaultWriterReadyPromiseResetToRejected(writer, error); } } function WritableStreamDefaultWriterGetDesiredSize(writer) { const stream = writer._ownerWritableStream; const state = stream._state; if (state === 'errored' || state === 'erroring') { return null; } if (state === 'closed') { return 0; } return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); } function WritableStreamDefaultWriterRelease(writer) { const stream = writer._ownerWritableStream; const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not // rejected until afterwards. This means that simply testing state will not work. WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); stream._writer = undefined; writer._ownerWritableStream = undefined; } function WritableStreamDefaultWriterWrite(writer, chunk) { const stream = writer._ownerWritableStream; const controller = stream._writableStreamController; const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); if (stream !== writer._ownerWritableStream) { return promiseRejectedWith(defaultWriterLockException('write to')); } const state = stream._state; if (state === 'errored') { return promiseRejectedWith(stream._storedError); } if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); } if (state === 'erroring') { return promiseRejectedWith(stream._storedError); } const promise = WritableStreamAddWriteRequest(stream); WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); return promise; } const closeSentinel = {}; /** * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. * * @public */ class WritableStreamDefaultController { constructor() { throw new TypeError('Illegal constructor'); } /** * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. * * @deprecated * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. */ get abortReason() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2('abortReason'); } return this._abortReason; } /** * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. */ get signal() { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2('signal'); } if (this._abortController === undefined) { // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, // so instead we only implement support for `signal` if we find a global `AbortController` constructor. throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); } return this._abortController.signal; } /** * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. * * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the * normal lifecycle of interactions with the underlying sink. */ error(e = undefined) { if (!IsWritableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$2('error'); } const state = this._controlledWritableStream._state; if (state !== 'writable') { // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so // just treat it as a no-op. return; } WritableStreamDefaultControllerError(this, e); } /** @internal */ [AbortSteps](reason) { const result = this._abortAlgorithm(reason); WritableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [ErrorSteps]() { ResetQueue(this); } } Object.defineProperties(WritableStreamDefaultController.prototype, { abortReason: { enumerable: true }, signal: { enumerable: true }, error: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { value: 'WritableStreamDefaultController', configurable: true }); } // Abstract operations implementing interface required by the WritableStream. function IsWritableStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { return false; } return x instanceof WritableStreamDefaultController; } function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledWritableStream = stream; stream._writableStreamController = controller; // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. controller._queue = undefined; controller._queueTotalSize = undefined; ResetQueue(controller); controller._abortReason = undefined; controller._abortController = createAbortController(); controller._started = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._writeAlgorithm = writeAlgorithm; controller._closeAlgorithm = closeAlgorithm; controller._abortAlgorithm = abortAlgorithm; const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); const startResult = startAlgorithm(); const startPromise = promiseResolvedWith(startResult); uponPromise(startPromise, () => { controller._started = true; WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); return null; }, r => { controller._started = true; WritableStreamDealWithRejection(stream, r); return null; }); } function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { const controller = Object.create(WritableStreamDefaultController.prototype); let startAlgorithm; let writeAlgorithm; let closeAlgorithm; let abortAlgorithm; if (underlyingSink.start !== undefined) { startAlgorithm = () => underlyingSink.start(controller); } else { startAlgorithm = () => undefined; } if (underlyingSink.write !== undefined) { writeAlgorithm = chunk => underlyingSink.write(chunk, controller); } else { writeAlgorithm = () => promiseResolvedWith(undefined); } if (underlyingSink.close !== undefined) { closeAlgorithm = () => underlyingSink.close(); } else { closeAlgorithm = () => promiseResolvedWith(undefined); } if (underlyingSink.abort !== undefined) { abortAlgorithm = reason => underlyingSink.abort(reason); } else { abortAlgorithm = () => promiseResolvedWith(undefined); } SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); } // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. function WritableStreamDefaultControllerClearAlgorithms(controller) { controller._writeAlgorithm = undefined; controller._closeAlgorithm = undefined; controller._abortAlgorithm = undefined; controller._strategySizeAlgorithm = undefined; } function WritableStreamDefaultControllerClose(controller) { EnqueueValueWithSize(controller, closeSentinel, 0); WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { try { return controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); return 1; } } function WritableStreamDefaultControllerGetDesiredSize(controller) { return controller._strategyHWM - controller._queueTotalSize; } function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); return; } const stream = controller._controlledWritableStream; if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } // Abstract operations for the WritableStreamDefaultController. function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { const stream = controller._controlledWritableStream; if (!controller._started) { return; } if (stream._inFlightWriteRequest !== undefined) { return; } const state = stream._state; if (state === 'erroring') { WritableStreamFinishErroring(stream); return; } if (controller._queue.length === 0) { return; } const value = PeekQueueValue(controller); if (value === closeSentinel) { WritableStreamDefaultControllerProcessClose(controller); } else { WritableStreamDefaultControllerProcessWrite(controller, value); } } function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { if (controller._controlledWritableStream._state === 'writable') { WritableStreamDefaultControllerError(controller, error); } } function WritableStreamDefaultControllerProcessClose(controller) { const stream = controller._controlledWritableStream; WritableStreamMarkCloseRequestInFlight(stream); DequeueValue(controller); const sinkClosePromise = controller._closeAlgorithm(); WritableStreamDefaultControllerClearAlgorithms(controller); uponPromise(sinkClosePromise, () => { WritableStreamFinishInFlightClose(stream); return null; }, reason => { WritableStreamFinishInFlightCloseWithError(stream, reason); return null; }); } function WritableStreamDefaultControllerProcessWrite(controller, chunk) { const stream = controller._controlledWritableStream; WritableStreamMarkFirstWriteRequestInFlight(stream); const sinkWritePromise = controller._writeAlgorithm(chunk); uponPromise(sinkWritePromise, () => { WritableStreamFinishInFlightWrite(stream); const state = stream._state; DequeueValue(controller); if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); return null; }, reason => { if (stream._state === 'writable') { WritableStreamDefaultControllerClearAlgorithms(controller); } WritableStreamFinishInFlightWriteWithError(stream, reason); return null; }); } function WritableStreamDefaultControllerGetBackpressure(controller) { const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; } // A client of WritableStreamDefaultController may use these functions directly to bypass state check. function WritableStreamDefaultControllerError(controller, error) { const stream = controller._controlledWritableStream; WritableStreamDefaultControllerClearAlgorithms(controller); WritableStreamStartErroring(stream, error); } // Helper functions for the WritableStream. function streamBrandCheckException$2(name) { return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); } // Helper functions for the WritableStreamDefaultController. function defaultControllerBrandCheckException$2(name) { return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); } // Helper functions for the WritableStreamDefaultWriter. function defaultWriterBrandCheckException(name) { return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); } function defaultWriterLockException(name) { return new TypeError('Cannot ' + name + ' a stream using a released writer'); } function defaultWriterClosedPromiseInitialize(writer) { writer._closedPromise = newPromise((resolve, reject) => { writer._closedPromise_resolve = resolve; writer._closedPromise_reject = reject; writer._closedPromiseState = 'pending'; }); } function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseReject(writer, reason); } function defaultWriterClosedPromiseInitializeAsResolved(writer) { defaultWriterClosedPromiseInitialize(writer); defaultWriterClosedPromiseResolve(writer); } function defaultWriterClosedPromiseReject(writer, reason) { if (writer._closedPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(writer._closedPromise); writer._closedPromise_reject(reason); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'rejected'; } function defaultWriterClosedPromiseResetToRejected(writer, reason) { defaultWriterClosedPromiseInitializeAsRejected(writer, reason); } function defaultWriterClosedPromiseResolve(writer) { if (writer._closedPromise_resolve === undefined) { return; } writer._closedPromise_resolve(undefined); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'resolved'; } function defaultWriterReadyPromiseInitialize(writer) { writer._readyPromise = newPromise((resolve, reject) => { writer._readyPromise_resolve = resolve; writer._readyPromise_reject = reject; }); writer._readyPromiseState = 'pending'; } function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseReject(writer, reason); } function defaultWriterReadyPromiseInitializeAsResolved(writer) { defaultWriterReadyPromiseInitialize(writer); defaultWriterReadyPromiseResolve(writer); } function defaultWriterReadyPromiseReject(writer, reason) { if (writer._readyPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(writer._readyPromise); writer._readyPromise_reject(reason); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'rejected'; } function defaultWriterReadyPromiseReset(writer) { defaultWriterReadyPromiseInitialize(writer); } function defaultWriterReadyPromiseResetToRejected(writer, reason) { defaultWriterReadyPromiseInitializeAsRejected(writer, reason); } function defaultWriterReadyPromiseResolve(writer) { if (writer._readyPromise_resolve === undefined) { return; } writer._readyPromise_resolve(undefined); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'fulfilled'; } /// function getGlobals() { if (typeof globalThis !== 'undefined') { return globalThis; } else if (typeof self !== 'undefined') { return self; } else if (typeof global !== 'undefined') { return global; } return undefined; } const globals = getGlobals(); /// function isDOMExceptionConstructor(ctor) { if (!(typeof ctor === 'function' || typeof ctor === 'object')) { return false; } if (ctor.name !== 'DOMException') { return false; } try { new ctor(); return true; } catch (_a) { return false; } } /** * Support: * - Web browsers * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) */ function getFromGlobal() { const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; return isDOMExceptionConstructor(ctor) ? ctor : undefined; } /** * Support: * - All platforms */ function createPolyfill() { // eslint-disable-next-line @typescript-eslint/no-shadow const ctor = function DOMException(message, name) { this.message = message || ''; this.name = name || 'Error'; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } }; setFunctionName(ctor, 'DOMException'); ctor.prototype = Object.create(Error.prototype); Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); return ctor; } // eslint-disable-next-line @typescript-eslint/no-redeclare const DOMException = getFromGlobal() || createPolyfill(); function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { const reader = AcquireReadableStreamDefaultReader(source); const writer = AcquireWritableStreamDefaultWriter(dest); source._disturbed = true; let shuttingDown = false; // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. let currentWrite = promiseResolvedWith(undefined); return newPromise((resolve, reject) => { let abortAlgorithm; if (signal !== undefined) { abortAlgorithm = () => { const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); const actions = []; if (!preventAbort) { actions.push(() => { if (dest._state === 'writable') { return WritableStreamAbort(dest, error); } return promiseResolvedWith(undefined); }); } if (!preventCancel) { actions.push(() => { if (source._state === 'readable') { return ReadableStreamCancel(source, error); } return promiseResolvedWith(undefined); }); } shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); }; if (signal.aborted) { abortAlgorithm(); return; } signal.addEventListener('abort', abortAlgorithm); } // Using reader and writer, read all chunks from this and write them to dest // - Backpressure must be enforced // - Shutdown must stop all activity function pipeLoop() { return newPromise((resolveLoop, rejectLoop) => { function next(done) { if (done) { resolveLoop(); } else { // Use `PerformPromiseThen` instead of `uponPromise` to avoid // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers PerformPromiseThen(pipeStep(), next, rejectLoop); } } next(false); }); } function pipeStep() { if (shuttingDown) { return promiseResolvedWith(true); } return PerformPromiseThen(writer._readyPromise, () => { return newPromise((resolveRead, rejectRead) => { ReadableStreamDefaultReaderRead(reader, { _chunkSteps: chunk => { currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); resolveRead(false); }, _closeSteps: () => resolveRead(true), _errorSteps: rejectRead }); }); }); } // Errors must be propagated forward isOrBecomesErrored(source, reader._closedPromise, storedError => { if (!preventAbort) { shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); } else { shutdown(true, storedError); } return null; }); // Errors must be propagated backward isOrBecomesErrored(dest, writer._closedPromise, storedError => { if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); } else { shutdown(true, storedError); } return null; }); // Closing must be propagated forward isOrBecomesClosed(source, reader._closedPromise, () => { if (!preventClose) { shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); } else { shutdown(); } return null; }); // Closing must be propagated backward if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); if (!preventCancel) { shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); } else { shutdown(true, destClosed); } } setPromiseIsHandledToTrue(pipeLoop()); function waitForWritesToFinish() { // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait // for that too. const oldCurrentWrite = currentWrite; return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); } function isOrBecomesErrored(stream, promise, action) { if (stream._state === 'errored') { action(stream._storedError); } else { uponRejection(promise, action); } } function isOrBecomesClosed(stream, promise, action) { if (stream._state === 'closed') { action(); } else { uponFulfillment(promise, action); } } function shutdownWithAction(action, originalIsError, originalError) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), doTheRest); } else { doTheRest(); } function doTheRest() { uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); return null; } } function shutdown(isError, error) { if (shuttingDown) { return; } shuttingDown = true; if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); } else { finalize(isError, error); } } function finalize(isError, error) { WritableStreamDefaultWriterRelease(writer); ReadableStreamReaderGenericRelease(reader); if (signal !== undefined) { signal.removeEventListener('abort', abortAlgorithm); } if (isError) { reject(error); } else { resolve(undefined); } return null; } }); } /** * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. * * @public */ class ReadableStreamDefaultController { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. */ get desiredSize() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('desiredSize'); } return ReadableStreamDefaultControllerGetDesiredSize(this); } /** * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from * the stream, but once those are read, the stream will become closed. */ close() { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('close'); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError('The stream is not in a state that permits close'); } ReadableStreamDefaultControllerClose(this); } enqueue(chunk = undefined) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('enqueue'); } if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { throw new TypeError('The stream is not in a state that permits enqueue'); } return ReadableStreamDefaultControllerEnqueue(this, chunk); } /** * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. */ error(e = undefined) { if (!IsReadableStreamDefaultController(this)) { throw defaultControllerBrandCheckException$1('error'); } ReadableStreamDefaultControllerError(this, e); } /** @internal */ [CancelSteps](reason) { ResetQueue(this); const result = this._cancelAlgorithm(reason); ReadableStreamDefaultControllerClearAlgorithms(this); return result; } /** @internal */ [PullSteps](readRequest) { const stream = this._controlledReadableStream; if (this._queue.length > 0) { const chunk = DequeueValue(this); if (this._closeRequested && this._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(this); ReadableStreamClose(stream); } else { ReadableStreamDefaultControllerCallPullIfNeeded(this); } readRequest._chunkSteps(chunk); } else { ReadableStreamAddReadRequest(stream, readRequest); ReadableStreamDefaultControllerCallPullIfNeeded(this); } } /** @internal */ [ReleaseSteps]() { // Do nothing. } } Object.defineProperties(ReadableStreamDefaultController.prototype, { close: { enumerable: true }, enqueue: { enumerable: true }, error: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { value: 'ReadableStreamDefaultController', configurable: true }); } // Abstract operations for the ReadableStreamDefaultController. function IsReadableStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { return false; } return x instanceof ReadableStreamDefaultController; } function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); if (!shouldPull) { return; } if (controller._pulling) { controller._pullAgain = true; return; } controller._pulling = true; const pullPromise = controller._pullAlgorithm(); uponPromise(pullPromise, () => { controller._pulling = false; if (controller._pullAgain) { controller._pullAgain = false; ReadableStreamDefaultControllerCallPullIfNeeded(controller); } return null; }, e => { ReadableStreamDefaultControllerError(controller, e); return null; }); } function ReadableStreamDefaultControllerShouldCallPull(controller) { const stream = controller._controlledReadableStream; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return false; } if (!controller._started) { return false; } if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableStreamDefaultControllerClearAlgorithms(controller) { controller._pullAlgorithm = undefined; controller._cancelAlgorithm = undefined; controller._strategySizeAlgorithm = undefined; } // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. function ReadableStreamDefaultControllerClose(controller) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; controller._closeRequested = true; if (controller._queue.length === 0) { ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamClose(stream); } } function ReadableStreamDefaultControllerEnqueue(controller, chunk) { if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { return; } const stream = controller._controlledReadableStream; if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { ReadableStreamFulfillReadRequest(stream, chunk, false); } else { let chunkSize; try { chunkSize = controller._strategySizeAlgorithm(chunk); } catch (chunkSizeE) { ReadableStreamDefaultControllerError(controller, chunkSizeE); throw chunkSizeE; } try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { ReadableStreamDefaultControllerError(controller, enqueueE); throw enqueueE; } } ReadableStreamDefaultControllerCallPullIfNeeded(controller); } function ReadableStreamDefaultControllerError(controller, e) { const stream = controller._controlledReadableStream; if (stream._state !== 'readable') { return; } ResetQueue(controller); ReadableStreamDefaultControllerClearAlgorithms(controller); ReadableStreamError(stream, e); } function ReadableStreamDefaultControllerGetDesiredSize(controller) { const state = controller._controlledReadableStream._state; if (state === 'errored') { return null; } if (state === 'closed') { return 0; } return controller._strategyHWM - controller._queueTotalSize; } // This is used in the implementation of TransformStream. function ReadableStreamDefaultControllerHasBackpressure(controller) { if (ReadableStreamDefaultControllerShouldCallPull(controller)) { return false; } return true; } function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { const state = controller._controlledReadableStream._state; if (!controller._closeRequested && state === 'readable') { return true; } return false; } function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { controller._controlledReadableStream = stream; controller._queue = undefined; controller._queueTotalSize = undefined; ResetQueue(controller); controller._started = false; controller._closeRequested = false; controller._pullAgain = false; controller._pulling = false; controller._strategySizeAlgorithm = sizeAlgorithm; controller._strategyHWM = highWaterMark; controller._pullAlgorithm = pullAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; stream._readableStreamController = controller; const startResult = startAlgorithm(); uponPromise(promiseResolvedWith(startResult), () => { controller._started = true; ReadableStreamDefaultControllerCallPullIfNeeded(controller); return null; }, r => { ReadableStreamDefaultControllerError(controller, r); return null; }); } function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { const controller = Object.create(ReadableStreamDefaultController.prototype); let startAlgorithm; let pullAlgorithm; let cancelAlgorithm; if (underlyingSource.start !== undefined) { startAlgorithm = () => underlyingSource.start(controller); } else { startAlgorithm = () => undefined; } if (underlyingSource.pull !== undefined) { pullAlgorithm = () => underlyingSource.pull(controller); } else { pullAlgorithm = () => promiseResolvedWith(undefined); } if (underlyingSource.cancel !== undefined) { cancelAlgorithm = reason => underlyingSource.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(undefined); } SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); } // Helper functions for the ReadableStreamDefaultController. function defaultControllerBrandCheckException$1(name) { return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); } function ReadableStreamTee(stream, cloneForBranch2) { if (IsReadableByteStreamController(stream._readableStreamController)) { return ReadableByteStreamTee(stream); } return ReadableStreamDefaultTee(stream); } function ReadableStreamDefaultTee(stream, cloneForBranch2) { const reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgain = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise(resolve => { resolveCancelPromise = resolve; }); function pullAlgorithm() { if (reading) { readAgain = true; return promiseResolvedWith(undefined); } reading = true; const readRequest = { _chunkSteps: chunk => { // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let // successful synchronously-available reads get ahead of asynchronously-available errors. _queueMicrotask(() => { readAgain = false; const chunk1 = chunk; const chunk2 = chunk; // There is no way to access the cloning code right now in the reference implementation. // If we add one then we'll need an implementation for serializable objects. // if (!canceled2 && cloneForBranch2) { // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); // } if (!canceled1) { ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgain) { pullAlgorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableStreamDefaultControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableStreamDefaultControllerClose(branch2._readableStreamController); } if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); return promiseResolvedWith(undefined); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { // do nothing } branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); uponRejection(reader._closedPromise, (r) => { ReadableStreamDefaultControllerError(branch1._readableStreamController, r); ReadableStreamDefaultControllerError(branch2._readableStreamController, r); if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } return null; }); return [branch1, branch2]; } function ReadableByteStreamTee(stream) { let reader = AcquireReadableStreamDefaultReader(stream); let reading = false; let readAgainForBranch1 = false; let readAgainForBranch2 = false; let canceled1 = false; let canceled2 = false; let reason1; let reason2; let branch1; let branch2; let resolveCancelPromise; const cancelPromise = newPromise(resolve => { resolveCancelPromise = resolve; }); function forwardReaderError(thisReader) { uponRejection(thisReader._closedPromise, r => { if (thisReader !== reader) { return null; } ReadableByteStreamControllerError(branch1._readableStreamController, r); ReadableByteStreamControllerError(branch2._readableStreamController, r); if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } return null; }); } function pullWithDefaultReader() { if (IsReadableStreamBYOBReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamDefaultReader(stream); forwardReaderError(reader); } const readRequest = { _chunkSteps: chunk => { // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let // successful synchronously-available reads get ahead of asynchronously-available errors. _queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const chunk1 = chunk; let chunk2 = chunk; if (!canceled1 && !canceled2) { try { chunk2 = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } } if (!canceled1) { ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); } if (!canceled2) { ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: () => { reading = false; if (!canceled1) { ReadableByteStreamControllerClose(branch1._readableStreamController); } if (!canceled2) { ReadableByteStreamControllerClose(branch2._readableStreamController); } if (branch1._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); } if (branch2._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); } if (!canceled1 || !canceled2) { resolveCancelPromise(undefined); } }, _errorSteps: () => { reading = false; } }; ReadableStreamDefaultReaderRead(reader, readRequest); } function pullWithBYOBReader(view, forBranch2) { if (IsReadableStreamDefaultReader(reader)) { ReadableStreamReaderGenericRelease(reader); reader = AcquireReadableStreamBYOBReader(stream); forwardReaderError(reader); } const byobBranch = forBranch2 ? branch2 : branch1; const otherBranch = forBranch2 ? branch1 : branch2; const readIntoRequest = { _chunkSteps: chunk => { // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let // successful synchronously-available reads get ahead of asynchronously-available errors. _queueMicrotask(() => { readAgainForBranch1 = false; readAgainForBranch2 = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!otherCanceled) { let clonedChunk; try { clonedChunk = CloneAsUint8Array(chunk); } catch (cloneE) { ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); return; } if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); } else if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } reading = false; if (readAgainForBranch1) { pull1Algorithm(); } else if (readAgainForBranch2) { pull2Algorithm(); } }); }, _closeSteps: chunk => { reading = false; const byobCanceled = forBranch2 ? canceled2 : canceled1; const otherCanceled = forBranch2 ? canceled1 : canceled2; if (!byobCanceled) { ReadableByteStreamControllerClose(byobBranch._readableStreamController); } if (!otherCanceled) { ReadableByteStreamControllerClose(otherBranch._readableStreamController); } if (chunk !== undefined) { if (!byobCanceled) { ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); } if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); } } if (!byobCanceled || !otherCanceled) { resolveCancelPromise(undefined); } }, _errorSteps: () => { reading = false; } }; ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); } function pull1Algorithm() { if (reading) { readAgainForBranch1 = true; return promiseResolvedWith(undefined); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, false); } return promiseResolvedWith(undefined); } function pull2Algorithm() { if (reading) { readAgainForBranch2 = true; return promiseResolvedWith(undefined); } reading = true; const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); if (byobRequest === null) { pullWithDefaultReader(); } else { pullWithBYOBReader(byobRequest._view, true); } return promiseResolvedWith(undefined); } function cancel1Algorithm(reason) { canceled1 = true; reason1 = reason; if (canceled2) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function cancel2Algorithm(reason) { canceled2 = true; reason2 = reason; if (canceled1) { const compositeReason = CreateArrayFromList([reason1, reason2]); const cancelResult = ReadableStreamCancel(stream, compositeReason); resolveCancelPromise(cancelResult); } return cancelPromise; } function startAlgorithm() { return; } branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); forwardReaderError(reader); return [branch1, branch2]; } function isReadableStreamLike(stream) { return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; } function ReadableStreamFrom(source) { if (isReadableStreamLike(source)) { return ReadableStreamFromDefaultReader(source.getReader()); } return ReadableStreamFromIterable(source); } function ReadableStreamFromIterable(asyncIterable) { let stream; const iteratorRecord = GetIterator(asyncIterable, 'async'); const startAlgorithm = noop; function pullAlgorithm() { let nextResult; try { nextResult = IteratorNext(iteratorRecord); } catch (e) { return promiseRejectedWith(e); } const nextPromise = promiseResolvedWith(nextResult); return transformPromiseWith(nextPromise, iterResult => { if (!typeIsObject(iterResult)) { throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); } const done = IteratorComplete(iterResult); if (done) { ReadableStreamDefaultControllerClose(stream._readableStreamController); } else { const value = IteratorValue(iterResult); ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); } }); } function cancelAlgorithm(reason) { const iterator = iteratorRecord.iterator; let returnMethod; try { returnMethod = GetMethod(iterator, 'return'); } catch (e) { return promiseRejectedWith(e); } if (returnMethod === undefined) { return promiseResolvedWith(undefined); } let returnResult; try { returnResult = reflectCall(returnMethod, iterator, [reason]); } catch (e) { return promiseRejectedWith(e); } const returnPromise = promiseResolvedWith(returnResult); return transformPromiseWith(returnPromise, iterResult => { if (!typeIsObject(iterResult)) { throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); } return undefined; }); } stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); return stream; } function ReadableStreamFromDefaultReader(reader) { let stream; const startAlgorithm = noop; function pullAlgorithm() { let readPromise; try { readPromise = reader.read(); } catch (e) { return promiseRejectedWith(e); } return transformPromiseWith(readPromise, readResult => { if (!typeIsObject(readResult)) { throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); } if (readResult.done) { ReadableStreamDefaultControllerClose(stream._readableStreamController); } else { const value = readResult.value; ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); } }); } function cancelAlgorithm(reason) { try { return promiseResolvedWith(reader.cancel(reason)); } catch (e) { return promiseRejectedWith(e); } } stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); return stream; } function convertUnderlyingDefaultOrByteSource(source, context) { assertDictionary(source, context); const original = source; const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; const cancel = original === null || original === void 0 ? void 0 : original.cancel; const pull = original === null || original === void 0 ? void 0 : original.pull; const start = original === null || original === void 0 ? void 0 : original.start; const type = original === null || original === void 0 ? void 0 : original.type; return { autoAllocateChunkSize: autoAllocateChunkSize === undefined ? undefined : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), cancel: cancel === undefined ? undefined : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), pull: pull === undefined ? undefined : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), start: start === undefined ? undefined : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) }; } function convertUnderlyingSourceCancelCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } function convertUnderlyingSourcePullCallback(fn, original, context) { assertFunction(fn, context); return (controller) => promiseCall(fn, original, [controller]); } function convertUnderlyingSourceStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertReadableStreamType(type, context) { type = `${type}`; if (type !== 'bytes') { throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); } return type; } function convertIteratorOptions(options, context) { assertDictionary(options, context); const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; return { preventCancel: Boolean(preventCancel) }; } function convertPipeOptions(options, context) { assertDictionary(options, context); const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; const signal = options === null || options === void 0 ? void 0 : options.signal; if (signal !== undefined) { assertAbortSignal(signal, `${context} has member 'signal' that`); } return { preventAbort: Boolean(preventAbort), preventCancel: Boolean(preventCancel), preventClose: Boolean(preventClose), signal }; } function assertAbortSignal(signal, context) { if (!isAbortSignal(signal)) { throw new TypeError(`${context} is not an AbortSignal.`); } } function convertReadableWritablePair(pair, context) { assertDictionary(pair, context); const readable = pair === null || pair === void 0 ? void 0 : pair.readable; assertRequiredField(readable, 'readable', 'ReadableWritablePair'); assertReadableStream(readable, `${context} has member 'readable' that`); const writable = pair === null || pair === void 0 ? void 0 : pair.writable; assertRequiredField(writable, 'writable', 'ReadableWritablePair'); assertWritableStream(writable, `${context} has member 'writable' that`); return { readable, writable }; } /** * A readable stream represents a source of data, from which you can read. * * @public */ class ReadableStream { constructor(rawUnderlyingSource = {}, rawStrategy = {}) { if (rawUnderlyingSource === undefined) { rawUnderlyingSource = null; } else { assertObject(rawUnderlyingSource, 'First parameter'); } const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); InitializeReadableStream(this); if (underlyingSource.type === 'bytes') { if (strategy.size !== undefined) { throw new RangeError('The strategy for a byte stream cannot have a size function'); } const highWaterMark = ExtractHighWaterMark(strategy, 0); SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); } else { const sizeAlgorithm = ExtractSizeAlgorithm(strategy); const highWaterMark = ExtractHighWaterMark(strategy, 1); SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); } } /** * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. */ get locked() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('locked'); } return IsReadableStreamLocked(this); } /** * Cancels the stream, signaling a loss of interest in the stream by a consumer. * * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} * method, which might or might not use it. */ cancel(reason = undefined) { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException$1('cancel')); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); } return ReadableStreamCancel(this, reason); } getReader(rawOptions = undefined) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('getReader'); } const options = convertReaderOptions(rawOptions, 'First parameter'); if (options.mode === undefined) { return AcquireReadableStreamDefaultReader(this); } return AcquireReadableStreamBYOBReader(this); } pipeThrough(rawTransform, rawOptions = {}) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('pipeThrough'); } assertRequiredArgument(rawTransform, 1, 'pipeThrough'); const transform = convertReadableWritablePair(rawTransform, 'First parameter'); const options = convertPipeOptions(rawOptions, 'Second parameter'); if (IsReadableStreamLocked(this)) { throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); } if (IsWritableStreamLocked(transform.writable)) { throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); } const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); setPromiseIsHandledToTrue(promise); return transform.readable; } pipeTo(destination, rawOptions = {}) { if (!IsReadableStream(this)) { return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); } if (destination === undefined) { return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); } if (!IsWritableStream(destination)) { return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); } let options; try { options = convertPipeOptions(rawOptions, 'Second parameter'); } catch (e) { return promiseRejectedWith(e); } if (IsReadableStreamLocked(this)) { return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); } if (IsWritableStreamLocked(destination)) { return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); } return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); } /** * Tees this readable stream, returning a two-element array containing the two resulting branches as * new {@link ReadableStream} instances. * * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be * propagated to the stream's underlying source. * * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, * this could allow interference between the two branches. */ tee() { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('tee'); } const branches = ReadableStreamTee(this); return CreateArrayFromList(branches); } values(rawOptions = undefined) { if (!IsReadableStream(this)) { throw streamBrandCheckException$1('values'); } const options = convertIteratorOptions(rawOptions, 'First parameter'); return AcquireReadableStreamAsyncIterator(this, options.preventCancel); } [SymbolAsyncIterator](options) { // Stub implementation, overridden below return this.values(options); } /** * Creates a new ReadableStream wrapping the provided iterable or async iterable. * * This can be used to adapt various kinds of objects into a readable stream, * such as an array, an async generator, or a Node.js readable stream. */ static from(asyncIterable) { return ReadableStreamFrom(asyncIterable); } } Object.defineProperties(ReadableStream, { from: { enumerable: true } }); Object.defineProperties(ReadableStream.prototype, { cancel: { enumerable: true }, getReader: { enumerable: true }, pipeThrough: { enumerable: true }, pipeTo: { enumerable: true }, tee: { enumerable: true }, values: { enumerable: true }, locked: { enumerable: true } }); setFunctionName(ReadableStream.from, 'from'); setFunctionName(ReadableStream.prototype.cancel, 'cancel'); setFunctionName(ReadableStream.prototype.getReader, 'getReader'); setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); setFunctionName(ReadableStream.prototype.tee, 'tee'); setFunctionName(ReadableStream.prototype.values, 'values'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, { value: 'ReadableStream', configurable: true }); } Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, { value: ReadableStream.prototype.values, writable: true, configurable: true }); // Abstract operations for the ReadableStream. // Throws if and only if startAlgorithm throws. function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { const stream = Object.create(ReadableStream.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableStreamDefaultController.prototype); SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); return stream; } // Throws if and only if startAlgorithm throws. function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { const stream = Object.create(ReadableStream.prototype); InitializeReadableStream(stream); const controller = Object.create(ReadableByteStreamController.prototype); SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); return stream; } function InitializeReadableStream(stream) { stream._state = 'readable'; stream._reader = undefined; stream._storedError = undefined; stream._disturbed = false; } function IsReadableStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { return false; } return x instanceof ReadableStream; } function IsReadableStreamLocked(stream) { if (stream._reader === undefined) { return false; } return true; } // ReadableStream API exposed for controllers. function ReadableStreamCancel(stream, reason) { stream._disturbed = true; if (stream._state === 'closed') { return promiseResolvedWith(undefined); } if (stream._state === 'errored') { return promiseRejectedWith(stream._storedError); } ReadableStreamClose(stream); const reader = stream._reader; if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { const readIntoRequests = reader._readIntoRequests; reader._readIntoRequests = new SimpleQueue(); readIntoRequests.forEach(readIntoRequest => { readIntoRequest._closeSteps(undefined); }); } const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); return transformPromiseWith(sourceCancelPromise, noop); } function ReadableStreamClose(stream) { stream._state = 'closed'; const reader = stream._reader; if (reader === undefined) { return; } defaultReaderClosedPromiseResolve(reader); if (IsReadableStreamDefaultReader(reader)) { const readRequests = reader._readRequests; reader._readRequests = new SimpleQueue(); readRequests.forEach(readRequest => { readRequest._closeSteps(); }); } } function ReadableStreamError(stream, e) { stream._state = 'errored'; stream._storedError = e; const reader = stream._reader; if (reader === undefined) { return; } defaultReaderClosedPromiseReject(reader, e); if (IsReadableStreamDefaultReader(reader)) { ReadableStreamDefaultReaderErrorReadRequests(reader, e); } else { ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); } } // Helper functions for the ReadableStream. function streamBrandCheckException$1(name) { return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); } function convertQueuingStrategyInit(init, context) { assertDictionary(init, context); const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); return { highWaterMark: convertUnrestrictedDouble(highWaterMark) }; } // The size function must not have a prototype property nor be a constructor const byteLengthSizeFunction = (chunk) => { return chunk.byteLength; }; setFunctionName(byteLengthSizeFunction, 'size'); /** * A queuing strategy that counts the number of bytes in each chunk. * * @public */ class ByteLengthQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); options = convertQueuingStrategyInit(options, 'First parameter'); this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException('highWaterMark'); } return this._byteLengthQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by returning the value of its `byteLength` property. */ get size() { if (!IsByteLengthQueuingStrategy(this)) { throw byteLengthBrandCheckException('size'); } return byteLengthSizeFunction; } } Object.defineProperties(ByteLengthQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { value: 'ByteLengthQueuingStrategy', configurable: true }); } // Helper functions for the ByteLengthQueuingStrategy. function byteLengthBrandCheckException(name) { return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); } function IsByteLengthQueuingStrategy(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { return false; } return x instanceof ByteLengthQueuingStrategy; } // The size function must not have a prototype property nor be a constructor const countSizeFunction = () => { return 1; }; setFunctionName(countSizeFunction, 'size'); /** * A queuing strategy that counts the number of chunks. * * @public */ class CountQueuingStrategy { constructor(options) { assertRequiredArgument(options, 1, 'CountQueuingStrategy'); options = convertQueuingStrategyInit(options, 'First parameter'); this._countQueuingStrategyHighWaterMark = options.highWaterMark; } /** * Returns the high water mark provided to the constructor. */ get highWaterMark() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException('highWaterMark'); } return this._countQueuingStrategyHighWaterMark; } /** * Measures the size of `chunk` by always returning 1. * This ensures that the total queue size is a count of the number of chunks in the queue. */ get size() { if (!IsCountQueuingStrategy(this)) { throw countBrandCheckException('size'); } return countSizeFunction; } } Object.defineProperties(CountQueuingStrategy.prototype, { highWaterMark: { enumerable: true }, size: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { value: 'CountQueuingStrategy', configurable: true }); } // Helper functions for the CountQueuingStrategy. function countBrandCheckException(name) { return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); } function IsCountQueuingStrategy(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { return false; } return x instanceof CountQueuingStrategy; } function convertTransformer(original, context) { assertDictionary(original, context); const cancel = original === null || original === void 0 ? void 0 : original.cancel; const flush = original === null || original === void 0 ? void 0 : original.flush; const readableType = original === null || original === void 0 ? void 0 : original.readableType; const start = original === null || original === void 0 ? void 0 : original.start; const transform = original === null || original === void 0 ? void 0 : original.transform; const writableType = original === null || original === void 0 ? void 0 : original.writableType; return { cancel: cancel === undefined ? undefined : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), flush: flush === undefined ? undefined : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), readableType, start: start === undefined ? undefined : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), transform: transform === undefined ? undefined : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), writableType }; } function convertTransformerFlushCallback(fn, original, context) { assertFunction(fn, context); return (controller) => promiseCall(fn, original, [controller]); } function convertTransformerStartCallback(fn, original, context) { assertFunction(fn, context); return (controller) => reflectCall(fn, original, [controller]); } function convertTransformerTransformCallback(fn, original, context) { assertFunction(fn, context); return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); } function convertTransformerCancelCallback(fn, original, context) { assertFunction(fn, context); return (reason) => promiseCall(fn, original, [reason]); } // Class TransformStream /** * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. * In a manner specific to the transform stream in question, writes to the writable side result in new data being * made available for reading from the readable side. * * @public */ class TransformStream { constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { if (rawTransformer === undefined) { rawTransformer = null; } const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); const transformer = convertTransformer(rawTransformer, 'First parameter'); if (transformer.readableType !== undefined) { throw new RangeError('Invalid readableType specified'); } if (transformer.writableType !== undefined) { throw new RangeError('Invalid writableType specified'); } const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); let startPromise_resolve; const startPromise = newPromise(resolve => { startPromise_resolve = resolve; }); InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); if (transformer.start !== undefined) { startPromise_resolve(transformer.start(this._transformStreamController)); } else { startPromise_resolve(undefined); } } /** * The readable side of the transform stream. */ get readable() { if (!IsTransformStream(this)) { throw streamBrandCheckException('readable'); } return this._readable; } /** * The writable side of the transform stream. */ get writable() { if (!IsTransformStream(this)) { throw streamBrandCheckException('writable'); } return this._writable; } } Object.defineProperties(TransformStream.prototype, { readable: { enumerable: true }, writable: { enumerable: true } }); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { value: 'TransformStream', configurable: true }); } function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { function startAlgorithm() { return startPromise; } function writeAlgorithm(chunk) { return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); } function abortAlgorithm(reason) { return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); } function closeAlgorithm() { return TransformStreamDefaultSinkCloseAlgorithm(stream); } stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); function pullAlgorithm() { return TransformStreamDefaultSourcePullAlgorithm(stream); } function cancelAlgorithm(reason) { return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); } stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. stream._backpressure = undefined; stream._backpressureChangePromise = undefined; stream._backpressureChangePromise_resolve = undefined; TransformStreamSetBackpressure(stream, true); stream._transformStreamController = undefined; } function IsTransformStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { return false; } return x instanceof TransformStream; } // This is a no-op if both sides are already errored. function TransformStreamError(stream, e) { ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); TransformStreamErrorWritableAndUnblockWrite(stream, e); } function TransformStreamErrorWritableAndUnblockWrite(stream, e) { TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); TransformStreamUnblockWrite(stream); } function TransformStreamUnblockWrite(stream) { if (stream._backpressure) { // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time // _backpressure is set. TransformStreamSetBackpressure(stream, false); } } function TransformStreamSetBackpressure(stream, backpressure) { // Passes also when called during construction. if (stream._backpressureChangePromise !== undefined) { stream._backpressureChangePromise_resolve(); } stream._backpressureChangePromise = newPromise(resolve => { stream._backpressureChangePromise_resolve = resolve; }); stream._backpressure = backpressure; } // Class TransformStreamDefaultController /** * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. * * @public */ class TransformStreamDefaultController { constructor() { throw new TypeError('Illegal constructor'); } /** * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. */ get desiredSize() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('desiredSize'); } const readableController = this._controlledTransformStream._readable._readableStreamController; return ReadableStreamDefaultControllerGetDesiredSize(readableController); } enqueue(chunk = undefined) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('enqueue'); } TransformStreamDefaultControllerEnqueue(this, chunk); } /** * Errors both the readable side and the writable side of the controlled transform stream, making all future * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. */ error(reason = undefined) { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('error'); } TransformStreamDefaultControllerError(this, reason); } /** * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the * transformer only needs to consume a portion of the chunks written to the writable side. */ terminate() { if (!IsTransformStreamDefaultController(this)) { throw defaultControllerBrandCheckException('terminate'); } TransformStreamDefaultControllerTerminate(this); } } Object.defineProperties(TransformStreamDefaultController.prototype, { enqueue: { enumerable: true }, error: { enumerable: true }, terminate: { enumerable: true }, desiredSize: { enumerable: true } }); setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); if (typeof Symbol.toStringTag === 'symbol') { Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { value: 'TransformStreamDefaultController', configurable: true }); } // Transform Stream Default Controller Abstract Operations function IsTransformStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { return false; } return x instanceof TransformStreamDefaultController; } function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { controller._controlledTransformStream = stream; stream._transformStreamController = controller; controller._transformAlgorithm = transformAlgorithm; controller._flushAlgorithm = flushAlgorithm; controller._cancelAlgorithm = cancelAlgorithm; controller._finishPromise = undefined; controller._finishPromise_resolve = undefined; controller._finishPromise_reject = undefined; } function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { const controller = Object.create(TransformStreamDefaultController.prototype); let transformAlgorithm; let flushAlgorithm; let cancelAlgorithm; if (transformer.transform !== undefined) { transformAlgorithm = chunk => transformer.transform(chunk, controller); } else { transformAlgorithm = chunk => { try { TransformStreamDefaultControllerEnqueue(controller, chunk); return promiseResolvedWith(undefined); } catch (transformResultE) { return promiseRejectedWith(transformResultE); } }; } if (transformer.flush !== undefined) { flushAlgorithm = () => transformer.flush(controller); } else { flushAlgorithm = () => promiseResolvedWith(undefined); } if (transformer.cancel !== undefined) { cancelAlgorithm = reason => transformer.cancel(reason); } else { cancelAlgorithm = () => promiseResolvedWith(undefined); } SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); } function TransformStreamDefaultControllerClearAlgorithms(controller) { controller._transformAlgorithm = undefined; controller._flushAlgorithm = undefined; controller._cancelAlgorithm = undefined; } function TransformStreamDefaultControllerEnqueue(controller, chunk) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { throw new TypeError('Readable side is not in a state that permits enqueue'); } // We throttle transform invocations based on the backpressure of the ReadableStream, but we still // accept TransformStreamDefaultControllerEnqueue() calls. try { ReadableStreamDefaultControllerEnqueue(readableController, chunk); } catch (e) { // This happens when readableStrategy.size() throws. TransformStreamErrorWritableAndUnblockWrite(stream, e); throw stream._readable._storedError; } const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); if (backpressure !== stream._backpressure) { TransformStreamSetBackpressure(stream, true); } } function TransformStreamDefaultControllerError(controller, e) { TransformStreamError(controller._controlledTransformStream, e); } function TransformStreamDefaultControllerPerformTransform(controller, chunk) { const transformPromise = controller._transformAlgorithm(chunk); return transformPromiseWith(transformPromise, undefined, r => { TransformStreamError(controller._controlledTransformStream, r); throw r; }); } function TransformStreamDefaultControllerTerminate(controller) { const stream = controller._controlledTransformStream; const readableController = stream._readable._readableStreamController; ReadableStreamDefaultControllerClose(readableController); const error = new TypeError('TransformStream terminated'); TransformStreamErrorWritableAndUnblockWrite(stream, error); } // TransformStreamDefaultSink Algorithms function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { const controller = stream._transformStreamController; if (stream._backpressure) { const backpressureChangePromise = stream._backpressureChangePromise; return transformPromiseWith(backpressureChangePromise, () => { const writable = stream._writable; const state = writable._state; if (state === 'erroring') { throw writable._storedError; } return TransformStreamDefaultControllerPerformTransform(controller, chunk); }); } return TransformStreamDefaultControllerPerformTransform(controller, chunk); } function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { const controller = stream._transformStreamController; if (controller._finishPromise !== undefined) { return controller._finishPromise; } // stream._readable cannot change after construction, so caching it across a call to user code is safe. const readable = stream._readable; // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, // we don't run the _cancelAlgorithm again. controller._finishPromise = newPromise((resolve, reject) => { controller._finishPromise_resolve = resolve; controller._finishPromise_reject = reject; }); const cancelPromise = controller._cancelAlgorithm(reason); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(cancelPromise, () => { if (readable._state === 'errored') { defaultControllerFinishPromiseReject(controller, readable._storedError); } else { ReadableStreamDefaultControllerError(readable._readableStreamController, reason); defaultControllerFinishPromiseResolve(controller); } return null; }, r => { ReadableStreamDefaultControllerError(readable._readableStreamController, r); defaultControllerFinishPromiseReject(controller, r); return null; }); return controller._finishPromise; } function TransformStreamDefaultSinkCloseAlgorithm(stream) { const controller = stream._transformStreamController; if (controller._finishPromise !== undefined) { return controller._finishPromise; } // stream._readable cannot change after construction, so caching it across a call to user code is safe. const readable = stream._readable; // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, // we don't also run the _cancelAlgorithm. controller._finishPromise = newPromise((resolve, reject) => { controller._finishPromise_resolve = resolve; controller._finishPromise_reject = reject; }); const flushPromise = controller._flushAlgorithm(); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(flushPromise, () => { if (readable._state === 'errored') { defaultControllerFinishPromiseReject(controller, readable._storedError); } else { ReadableStreamDefaultControllerClose(readable._readableStreamController); defaultControllerFinishPromiseResolve(controller); } return null; }, r => { ReadableStreamDefaultControllerError(readable._readableStreamController, r); defaultControllerFinishPromiseReject(controller, r); return null; }); return controller._finishPromise; } // TransformStreamDefaultSource Algorithms function TransformStreamDefaultSourcePullAlgorithm(stream) { // Invariant. Enforced by the promises returned by start() and pull(). TransformStreamSetBackpressure(stream, false); // Prevent the next pull() call until there is backpressure. return stream._backpressureChangePromise; } function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { const controller = stream._transformStreamController; if (controller._finishPromise !== undefined) { return controller._finishPromise; } // stream._writable cannot change after construction, so caching it across a call to user code is safe. const writable = stream._writable; // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the // _flushAlgorithm. controller._finishPromise = newPromise((resolve, reject) => { controller._finishPromise_resolve = resolve; controller._finishPromise_reject = reject; }); const cancelPromise = controller._cancelAlgorithm(reason); TransformStreamDefaultControllerClearAlgorithms(controller); uponPromise(cancelPromise, () => { if (writable._state === 'errored') { defaultControllerFinishPromiseReject(controller, writable._storedError); } else { WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); TransformStreamUnblockWrite(stream); defaultControllerFinishPromiseResolve(controller); } return null; }, r => { WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); TransformStreamUnblockWrite(stream); defaultControllerFinishPromiseReject(controller, r); return null; }); return controller._finishPromise; } // Helper functions for the TransformStreamDefaultController. function defaultControllerBrandCheckException(name) { return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); } function defaultControllerFinishPromiseResolve(controller) { if (controller._finishPromise_resolve === undefined) { return; } controller._finishPromise_resolve(); controller._finishPromise_resolve = undefined; controller._finishPromise_reject = undefined; } function defaultControllerFinishPromiseReject(controller, reason) { if (controller._finishPromise_reject === undefined) { return; } setPromiseIsHandledToTrue(controller._finishPromise); controller._finishPromise_reject(reason); controller._finishPromise_resolve = undefined; controller._finishPromise_reject = undefined; } // Helper functions for the TransformStream. function streamBrandCheckException(name) { return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); } exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; exports.CountQueuingStrategy = CountQueuingStrategy; exports.ReadableByteStreamController = ReadableByteStreamController; exports.ReadableStream = ReadableStream; exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; exports.ReadableStreamDefaultController = ReadableStreamDefaultController; exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; exports.TransformStream = TransformStream; exports.TransformStreamDefaultController = TransformStreamDefaultController; exports.WritableStream = WritableStream; exports.WritableStreamDefaultController = WritableStreamDefaultController; exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; })); //# sourceMappingURL=ponyfill.es2018.js.map /***/ }), /***/ 516: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var isString = __nccwpck_require__(7970); var isNumber = __nccwpck_require__(3670); var isBoolean = __nccwpck_require__(823); var isSymbol = __nccwpck_require__(3927); var isBigInt = __nccwpck_require__(7788); /** @type {import('.')} */ // eslint-disable-next-line consistent-return module.exports = function whichBoxedPrimitive(value) { // eslint-disable-next-line eqeqeq if (value == null || (typeof value !== 'object' && typeof value !== 'function')) { return null; } if (isString(value)) { return 'String'; } if (isNumber(value)) { return 'Number'; } if (isBoolean(value)) { return 'Boolean'; } if (isSymbol(value)) { return 'Symbol'; } if (isBigInt(value)) { return 'BigInt'; } }; /***/ }), /***/ 6260: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var isMap = __nccwpck_require__(9311); var isSet = __nccwpck_require__(6513); var isWeakMap = __nccwpck_require__(3955); var isWeakSet = __nccwpck_require__(2237); /** @type {import('.')} */ module.exports = function whichCollection(/** @type {unknown} */ value) { if (value && typeof value === 'object') { if (isMap(value)) { return 'Map'; } if (isSet(value)) { return 'Set'; } if (isWeakMap(value)) { return 'WeakMap'; } if (isWeakSet(value)) { return 'WeakSet'; } } return false; }; /***/ }), /***/ 4768: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var forEach = __nccwpck_require__(4963); var availableTypedArrays = __nccwpck_require__(1506); var callBind = __nccwpck_require__(3844); var callBound = __nccwpck_require__(3105); var gOPD = __nccwpck_require__(3170); var getProto = __nccwpck_require__(1967); var $toString = callBound('Object.prototype.toString'); var hasToStringTag = __nccwpck_require__(5479)(); var g = typeof globalThis === 'undefined' ? global : globalThis; var typedArrays = availableTypedArrays(); var $slice = callBound('String.prototype.slice'); /** @import { BoundSet, BoundSlice, Cache, Getter } from './types' */ /** @import { TypedArrayName } from '.' */ /** @type {(array: readonly T[], value: unknown) => number} */ var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { for (var i = 0; i < array.length; i += 1) { if (array[i] === value) { return i; } } return -1; }; /** @type {Cache} */ var cache = { __proto__: null }; if (hasToStringTag && gOPD && getProto) { forEach(typedArrays, function (typedArray) { var arr = new g[typedArray](); if (Symbol.toStringTag in arr && getProto) { var proto = getProto(arr); // @ts-expect-error TS won't narrow inside a closure var descriptor = gOPD(proto, Symbol.toStringTag); if (!descriptor && proto) { var superProto = getProto(proto); // @ts-expect-error TS won't narrow inside a closure descriptor = gOPD(superProto, Symbol.toStringTag); } if (descriptor && descriptor.get) { var bound = callBind(descriptor.get); cache[ /** @type {`$${TypedArrayName}`} */ ('$' + typedArray) ] = bound; } } }); } else { forEach(typedArrays, function (typedArray) { var arr = new g[typedArray](); var fn = arr.slice || arr.set; if (fn) { var bound = /** @type {BoundSlice | BoundSet} */ ( // @ts-expect-error TODO FIXME callBind(fn) ); cache[ /** @type {`$${TypedArrayName}`} */ ('$' + typedArray) ] = bound; } }); } /** @type {(value: object) => false | TypedArrayName} */ function tryTypedArrays(value) { /** @type {ReturnType} */ var found = false; forEach( /** @type {Record<`$${TypedArrayName}`, Getter>} */ (cache), /** @param {Getter} getter @param {`$${TypedArrayName}`} typedArray */ function (getter, typedArray) { if (!found) { try { // @ts-expect-error a throw is fine here if ('$' + getter(value) === typedArray) { found = /** @type {TypedArrayName} */ ($slice(typedArray, 1)); } } catch (e) { /**/ } } } ); return found; } /** @type {(value: object) => false | TypedArrayName} */ function trySlices(value) { /** @type {ReturnType} */ var found = false; forEach( /** @type {Record<`$${TypedArrayName}`, Getter>} */(cache), /** @param {Getter} getter @param {`$${TypedArrayName}`} name */ function (getter, name) { if (!found) { try { // @ts-expect-error a throw is fine here getter(value); found = /** @type {TypedArrayName} */ ($slice(name, 1)); } catch (e) { /**/ } } } ); return found; } /** @type {(tag: unknown) => tag is typeof typedArrays[number]} */ function isTATag(tag) { return $indexOf(typedArrays, tag) > -1; } /** * @type {import('.')} * @param {unknown} value */ module.exports = function whichTypedArray(value) { if (!value || typeof value !== 'object') { return false; } if (!hasToStringTag) { var tag = $slice($toString(value), 8, -1); if (isTATag(tag)) { return tag; } if (tag !== 'Object') { return false; } // node < 0.6 hits here on real Typed Arrays return trySlices(value); } if (!gOPD) { return null; } // unknown engine return tryTypedArrays(value); }; /***/ }), /***/ 8408: /***/ ((__unused_webpack_module, exports) => { /* * xpath.js * * An XPath 1.0 library for JavaScript. * * Cameron McCormack * * This work is licensed under the MIT License. * * Revision 20: April 26, 2011 * Fixed a typo resulting in FIRST_ORDERED_NODE_TYPE results being wrong, * thanks to . * * Revision 19: November 29, 2005 * Nodesets now store their nodes in a height balanced tree, increasing * performance for the common case of selecting nodes in document order, * thanks to Sébastien Cramatte . * AVL tree code adapted from Raimund Neumann . * * Revision 18: October 27, 2005 * DOM 3 XPath support. Caveats: * - namespace prefixes aren't resolved in XPathEvaluator.createExpression, * but in XPathExpression.evaluate. * - XPathResult.invalidIteratorState is not implemented. * * Revision 17: October 25, 2005 * Some core XPath function fixes and a patch to avoid crashing certain * versions of MSXML in PathExpr.prototype.getOwnerElement, thanks to * Sébastien Cramatte . * * Revision 16: September 22, 2005 * Workarounds for some IE 5.5 deficiencies. * Fixed problem with prefix node tests on attribute nodes. * * Revision 15: May 21, 2005 * Fixed problem with QName node tests on elements with an xmlns="...". * * Revision 14: May 19, 2005 * Fixed QName node tests on attribute node regression. * * Revision 13: May 3, 2005 * Node tests are case insensitive now if working in an HTML DOM. * * Revision 12: April 26, 2005 * Updated licence. Slight code changes to enable use of Dean * Edwards' script compression, http://dean.edwards.name/packer/ . * * Revision 11: April 23, 2005 * Fixed bug with 'and' and 'or' operators, fix thanks to * Sandy McArthur . * * Revision 10: April 15, 2005 * Added support for a virtual root node, supposedly helpful for * implementing XForms. Fixed problem with QName node tests and * the parent axis. * * Revision 9: March 17, 2005 * Namespace resolver tweaked so using the document node as the context * for namespace lookups is equivalent to using the document element. * * Revision 8: February 13, 2005 * Handle implicit declaration of 'xmlns' namespace prefix. * Fixed bug when comparing nodesets. * Instance data can now be associated with a FunctionResolver, and * workaround for MSXML not supporting 'localName' and 'getElementById', * thanks to Grant Gongaware. * Fix a few problems when the context node is the root node. * * Revision 7: February 11, 2005 * Default namespace resolver fix from Grant Gongaware * . * * Revision 6: February 10, 2005 * Fixed bug in 'number' function. * * Revision 5: February 9, 2005 * Fixed bug where text nodes not getting converted to string values. * * Revision 4: January 21, 2005 * Bug in 'name' function, fix thanks to Bill Edney. * Fixed incorrect processing of namespace nodes. * Fixed NamespaceResolver to resolve 'xml' namespace. * Implemented union '|' operator. * * Revision 3: January 14, 2005 * Fixed bug with nodeset comparisons, bug lexing < and >. * * Revision 2: October 26, 2004 * QName node test namespace handling fixed. Few other bug fixes. * * Revision 1: August 13, 2004 * Bug fixes from William J. Edney . * Added minimal licence. * * Initial version: June 14, 2004 */ // non-node wrapper var xpath = ( false) ? 0 : exports; (function (exports) { "use strict"; // namespace nodes are not part of the DOM spec, so we use a custom nodetype for them. // should NOT be used externally var NAMESPACE_NODE_NODETYPE = '__namespace'; var isNil = function (x) { return x === null || x === undefined; }; var isValidNodeType = function (nodeType) { return nodeType === NAMESPACE_NODE_NODETYPE || (Number.isInteger(nodeType) && nodeType >= 1 && nodeType <= 11 ); }; var isNodeLike = function (value) { return value && isValidNodeType(value.nodeType) && typeof value.nodeName === "string"; }; // functional helpers function curry(func) { var slice = Array.prototype.slice, totalargs = func.length, partial = function (args, fn) { return function () { return fn.apply(this, args.concat(slice.call(arguments))); } }, fn = function () { var args = slice.call(arguments); return (args.length < totalargs) ? partial(args, fn) : func.apply(this, slice.apply(arguments, [0, totalargs])); }; return fn; } var forEach = function (f, xs) { for (var i = 0; i < xs.length; i += 1) { f(xs[i], i, xs); } }; var reduce = function (f, seed, xs) { var acc = seed; forEach(function (x, i) { acc = f(acc, x, i); }, xs); return acc; }; var map = function (f, xs) { var mapped = new Array(xs.length); forEach(function (x, i) { mapped[i] = f(x); }, xs); return mapped; }; var filter = function (f, xs) { var filtered = []; forEach(function (x, i) { if (f(x, i)) { filtered.push(x); } }, xs); return filtered; }; var includes = function (values, value) { for (var i = 0; i < values.length; i += 1) { if (values[i] === value) { return true; } } return false; }; function always(value) { return function () { return value; } } function toString(x) { return x.toString(); } var join = function (s, xs) { return xs.join(s); }; var wrap = function (pref, suf, str) { return pref + str + suf; }; var prototypeConcat = Array.prototype.concat; var sortNodes = function (nodes, reverse) { var ns = new XNodeSet(); ns.addArray(nodes); var sorted = ns.toArray(); return reverse ? sorted.reverse() : sorted; } // .apply() fails above a certain number of arguments - https://github.com/goto100/xpath/pull/98 var MAX_ARGUMENT_LENGTH = 32767; function flatten(arr) { var result = []; for (var start = 0; start < arr.length; start += MAX_ARGUMENT_LENGTH) { var chunk = arr.slice(start, start + MAX_ARGUMENT_LENGTH); result = prototypeConcat.apply(result, chunk); } return result; } function assign(target, varArgs) { // .length of function is 2 var to = Object(target); for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index]; if (nextSource != null) { // Skip over if undefined or null for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; } } } } return to; } var NodeTypes = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NAMESPACE_NODE: NAMESPACE_NODE_NODETYPE, }; // XPathParser /////////////////////////////////////////////////////////////// XPathParser.prototype = new Object(); XPathParser.prototype.constructor = XPathParser; XPathParser.superclass = Object.prototype; function XPathParser() { this.init(); } XPathParser.prototype.init = function () { this.reduceActions = []; this.reduceActions[3] = function (rhs) { return new OrOperation(rhs[0], rhs[2]); }; this.reduceActions[5] = function (rhs) { return new AndOperation(rhs[0], rhs[2]); }; this.reduceActions[7] = function (rhs) { return new EqualsOperation(rhs[0], rhs[2]); }; this.reduceActions[8] = function (rhs) { return new NotEqualOperation(rhs[0], rhs[2]); }; this.reduceActions[10] = function (rhs) { return new LessThanOperation(rhs[0], rhs[2]); }; this.reduceActions[11] = function (rhs) { return new GreaterThanOperation(rhs[0], rhs[2]); }; this.reduceActions[12] = function (rhs) { return new LessThanOrEqualOperation(rhs[0], rhs[2]); }; this.reduceActions[13] = function (rhs) { return new GreaterThanOrEqualOperation(rhs[0], rhs[2]); }; this.reduceActions[15] = function (rhs) { return new PlusOperation(rhs[0], rhs[2]); }; this.reduceActions[16] = function (rhs) { return new MinusOperation(rhs[0], rhs[2]); }; this.reduceActions[18] = function (rhs) { return new MultiplyOperation(rhs[0], rhs[2]); }; this.reduceActions[19] = function (rhs) { return new DivOperation(rhs[0], rhs[2]); }; this.reduceActions[20] = function (rhs) { return new ModOperation(rhs[0], rhs[2]); }; this.reduceActions[22] = function (rhs) { return new UnaryMinusOperation(rhs[1]); }; this.reduceActions[24] = function (rhs) { return new BarOperation(rhs[0], rhs[2]); }; this.reduceActions[25] = function (rhs) { return new PathExpr(undefined, undefined, rhs[0]); }; this.reduceActions[27] = function (rhs) { rhs[0].locationPath = rhs[2]; return rhs[0]; }; this.reduceActions[28] = function (rhs) { rhs[0].locationPath = rhs[2]; rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); return rhs[0]; }; this.reduceActions[29] = function (rhs) { return new PathExpr(rhs[0], [], undefined); }; this.reduceActions[30] = function (rhs) { if (Utilities.instance_of(rhs[0], PathExpr)) { if (rhs[0].filterPredicates == undefined) { rhs[0].filterPredicates = []; } rhs[0].filterPredicates.push(rhs[1]); return rhs[0]; } else { return new PathExpr(rhs[0], [rhs[1]], undefined); } }; this.reduceActions[32] = function (rhs) { return rhs[1]; }; this.reduceActions[33] = function (rhs) { return new XString(rhs[0]); }; this.reduceActions[34] = function (rhs) { return new XNumber(rhs[0]); }; this.reduceActions[36] = function (rhs) { return new FunctionCall(rhs[0], []); }; this.reduceActions[37] = function (rhs) { return new FunctionCall(rhs[0], rhs[2]); }; this.reduceActions[38] = function (rhs) { return [rhs[0]]; }; this.reduceActions[39] = function (rhs) { rhs[2].unshift(rhs[0]); return rhs[2]; }; this.reduceActions[43] = function (rhs) { return new LocationPath(true, []); }; this.reduceActions[44] = function (rhs) { rhs[1].absolute = true; return rhs[1]; }; this.reduceActions[46] = function (rhs) { return new LocationPath(false, [rhs[0]]); }; this.reduceActions[47] = function (rhs) { rhs[0].steps.push(rhs[2]); return rhs[0]; }; this.reduceActions[49] = function (rhs) { return new Step(rhs[0], rhs[1], []); }; this.reduceActions[50] = function (rhs) { return new Step(Step.CHILD, rhs[0], []); }; this.reduceActions[51] = function (rhs) { return new Step(rhs[0], rhs[1], rhs[2]); }; this.reduceActions[52] = function (rhs) { return new Step(Step.CHILD, rhs[0], rhs[1]); }; this.reduceActions[54] = function (rhs) { return [rhs[0]]; }; this.reduceActions[55] = function (rhs) { rhs[1].unshift(rhs[0]); return rhs[1]; }; this.reduceActions[56] = function (rhs) { if (rhs[0] == "ancestor") { return Step.ANCESTOR; } else if (rhs[0] == "ancestor-or-self") { return Step.ANCESTORORSELF; } else if (rhs[0] == "attribute") { return Step.ATTRIBUTE; } else if (rhs[0] == "child") { return Step.CHILD; } else if (rhs[0] == "descendant") { return Step.DESCENDANT; } else if (rhs[0] == "descendant-or-self") { return Step.DESCENDANTORSELF; } else if (rhs[0] == "following") { return Step.FOLLOWING; } else if (rhs[0] == "following-sibling") { return Step.FOLLOWINGSIBLING; } else if (rhs[0] == "namespace") { return Step.NAMESPACE; } else if (rhs[0] == "parent") { return Step.PARENT; } else if (rhs[0] == "preceding") { return Step.PRECEDING; } else if (rhs[0] == "preceding-sibling") { return Step.PRECEDINGSIBLING; } else if (rhs[0] == "self") { return Step.SELF; } return -1; }; this.reduceActions[57] = function (rhs) { return Step.ATTRIBUTE; }; this.reduceActions[59] = function (rhs) { if (rhs[0] == "comment") { return NodeTest.commentTest; } else if (rhs[0] == "text") { return NodeTest.textTest; } else if (rhs[0] == "processing-instruction") { return NodeTest.anyPiTest; } else if (rhs[0] == "node") { return NodeTest.nodeTest; } return new NodeTest(-1, undefined); }; this.reduceActions[60] = function (rhs) { return new NodeTest.PITest(rhs[2]); }; this.reduceActions[61] = function (rhs) { return rhs[1]; }; this.reduceActions[63] = function (rhs) { rhs[1].absolute = true; rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); return rhs[1]; }; this.reduceActions[64] = function (rhs) { rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); rhs[0].steps.push(rhs[2]); return rhs[0]; }; this.reduceActions[65] = function (rhs) { return new Step(Step.SELF, NodeTest.nodeTest, []); }; this.reduceActions[66] = function (rhs) { return new Step(Step.PARENT, NodeTest.nodeTest, []); }; this.reduceActions[67] = function (rhs) { return new VariableReference(rhs[1]); }; this.reduceActions[68] = function (rhs) { return NodeTest.nameTestAny; }; this.reduceActions[69] = function (rhs) { return new NodeTest.NameTestPrefixAny(rhs[0].split(':')[0]); }; this.reduceActions[70] = function (rhs) { return new NodeTest.NameTestQName(rhs[0]); }; }; XPathParser.actionTable = [ " s s sssssssss s ss s ss", " s ", "r rrrrrrrrr rrrrrrr rr r ", " rrrrr ", " s s sssssssss s ss s ss", "rs rrrrrrrr s sssssrrrrrr rrs rs ", " s s sssssssss s ss s ss", " s ", " s ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " s ", " s ", " s s sssss s s ", "r rrrrrrrrr rrrrrrr rr r ", "a ", "r s rr r ", "r sr rr r ", "r s rr s rr r ", "r rssrr rss rr r ", "r rrrrr rrrss rr r ", "r rrrrrsss rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrrs rr r ", "r rrrrrrrr rrrrrr rr r ", "r rrrrrrrr rrrrrr rr r ", "r srrrrrrrr rrrrrrs rr sr ", "r srrrrrrrr rrrrrrs rr r ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrr rrrrrr rr r ", "r rrrrrrrr rrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", " sssss ", "r rrrrrrrrr rrrrrrr rr sr ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " s ", "r srrrrrrrr rrrrrrs rr r ", "r rrrrrrrr rrrrr rr r ", " s ", " s ", " rrrrr ", " s s sssssssss s sss s ss", "r srrrrrrrr rrrrrrs rr r ", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss s ss s ss", " s s sssssssss ss s ss", " s s sssssssss s ss s ss", " s s sssss s s ", " s s sssss s s ", "r rrrrrrrrr rrrrrrr rr rr ", " s s sssss s s ", " s s sssss s s ", "r rrrrrrrrr rrrrrrr rr sr ", "r rrrrrrrrr rrrrrrr rr sr ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr rr ", " s ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " rr ", " s ", " rs ", "r sr rr r ", "r s rr s rr r ", "r rssrr rss rr r ", "r rssrr rss rr r ", "r rrrrr rrrss rr r ", "r rrrrr rrrss rr r ", "r rrrrr rrrss rr r ", "r rrrrr rrrss rr r ", "r rrrrrsss rrrrr rr r ", "r rrrrrsss rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrr rr r ", "r rrrrrrrr rrrrrr rr r ", " r ", " s ", "r srrrrrrrr rrrrrrs rr r ", "r srrrrrrrr rrrrrrs rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr r ", "r rrrrrrrrr rrrrrrr rr rr ", "r rrrrrrrrr rrrrrrr rr rr ", " s s sssssssss s ss s ss", "r rrrrrrrrr rrrrrrr rr rr ", " r " ]; XPathParser.actionTableNumber = [ " 1 0 /.-,+*)(' & %$ # \"!", " J ", "a aaaaaaaaa aaaaaaa aa a ", " YYYYY ", " 1 0 /.-,+*)(' & %$ # \"!", "K1 KKKKKKKK . +*)('KKKKKK KK# K\" ", " 1 0 /.-,+*)(' & %$ # \"!", " N ", " O ", "e eeeeeeeee eeeeeee ee ee ", "f fffffffff fffffff ff ff ", "d ddddddddd ddddddd dd dd ", "B BBBBBBBBB BBBBBBB BB BB ", "A AAAAAAAAA AAAAAAA AA AA ", " P ", " Q ", " 1 . +*)(' # \" ", "b bbbbbbbbb bbbbbbb bb b ", " ", "! S !! ! ", "\" T\" \"\" \" ", "$ V $$ U $$ $ ", "& &ZY&& &XW && & ", ") ))))) )))\\[ )) ) ", ". ....._^] ..... .. . ", "1 11111111 11111 11 1 ", "5 55555555 55555` 55 5 ", "7 77777777 777777 77 7 ", "9 99999999 999999 99 9 ", ": c:::::::: ::::::b :: a: ", "I fIIIIIIII IIIIIIe II I ", "= ========= ======= == == ", "? ????????? ??????? ?? ?? ", "C CCCCCCCCC CCCCCCC CC CC ", "J JJJJJJJJ JJJJJJ JJ J ", "M MMMMMMMM MMMMMM MM M ", "N NNNNNNNNN NNNNNNN NN N ", "P PPPPPPPPP PPPPPPP PP P ", " +*)(' ", "R RRRRRRRRR RRRRRRR RR aR ", "U UUUUUUUUU UUUUUUU UU U ", "Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ", "c ccccccccc ccccccc cc cc ", " j ", "L fLLLLLLLL LLLLLLe LL L ", "6 66666666 66666 66 6 ", " k ", " l ", " XXXXX ", " 1 0 /.-,+*)(' & %$m # \"!", "_ f________ ______e __ _ ", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 0 /.-,+*)(' %$ # \"!", " 1 0 /.-,+*)(' & %$ # \"!", " 1 . +*)(' # \" ", " 1 . +*)(' # \" ", "> >>>>>>>>> >>>>>>> >> >> ", " 1 . +*)(' # \" ", " 1 . +*)(' # \" ", "Q QQQQQQQQQ QQQQQQQ QQ aQ ", "V VVVVVVVVV VVVVVVV VV aV ", "T TTTTTTTTT TTTTTTT TT T ", "@ @@@@@@@@@ @@@@@@@ @@ @@ ", " \x87 ", "[ [[[[[[[[[ [[[[[[[ [[ [[ ", "D DDDDDDDDD DDDDDDD DD DD ", " HH ", " \x88 ", " F\x89 ", "# T# ## # ", "% V %% U %% % ", "' 'ZY'' 'XW '' ' ", "( (ZY(( (XW (( ( ", "+ +++++ +++\\[ ++ + ", "* ***** ***\\[ ** * ", "- ----- ---\\[ -- - ", ", ,,,,, ,,,\\[ ,, , ", "0 00000_^] 00000 00 0 ", "/ /////_^] ///// // / ", "2 22222222 22222 22 2 ", "3 33333333 33333 33 3 ", "4 44444444 44444 44 4 ", "8 88888888 888888 88 8 ", " ^ ", " \x8a ", "; f;;;;;;;; ;;;;;;e ;; ; ", "< f<<<<<<<< <<<<<?@ AB CDEFGH IJ ", " ", " ", " ", "L456789:;<=>?@ AB CDEFGH IJ ", " M EFGH IJ ", " N;<=>?@ AB CDEFGH IJ ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " S EFGH IJ ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " e ", " ", " ", " ", " ", " ", " ", " ", " ", " h J ", " i j ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "o456789:;<=>?@ ABpqCDEFGH IJ ", " ", " r6789:;<=>?@ AB CDEFGH IJ ", " s789:;<=>?@ AB CDEFGH IJ ", " t89:;<=>?@ AB CDEFGH IJ ", " u89:;<=>?@ AB CDEFGH IJ ", " v9:;<=>?@ AB CDEFGH IJ ", " w9:;<=>?@ AB CDEFGH IJ ", " x9:;<=>?@ AB CDEFGH IJ ", " y9:;<=>?@ AB CDEFGH IJ ", " z:;<=>?@ AB CDEFGH IJ ", " {:;<=>?@ AB CDEFGH IJ ", " |;<=>?@ AB CDEFGH IJ ", " };<=>?@ AB CDEFGH IJ ", " ~;<=>?@ AB CDEFGH IJ ", " \x7f=>?@ AB CDEFGH IJ ", "\x80456789:;<=>?@ AB CDEFGH IJ\x81", " \x82 EFGH IJ ", " \x83 EFGH IJ ", " ", " \x84 GH IJ ", " \x85 GH IJ ", " i \x86 ", " i \x87 ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "o456789:;<=>?@ AB\x8cqCDEFGH IJ ", " ", " " ]; XPathParser.productions = [ [1, 1, 2], [2, 1, 3], [3, 1, 4], [3, 3, 3, -9, 4], [4, 1, 5], [4, 3, 4, -8, 5], [5, 1, 6], [5, 3, 5, -22, 6], [5, 3, 5, -5, 6], [6, 1, 7], [6, 3, 6, -23, 7], [6, 3, 6, -24, 7], [6, 3, 6, -6, 7], [6, 3, 6, -7, 7], [7, 1, 8], [7, 3, 7, -25, 8], [7, 3, 7, -26, 8], [8, 1, 9], [8, 3, 8, -12, 9], [8, 3, 8, -11, 9], [8, 3, 8, -10, 9], [9, 1, 10], [9, 2, -26, 9], [10, 1, 11], [10, 3, 10, -27, 11], [11, 1, 12], [11, 1, 13], [11, 3, 13, -28, 14], [11, 3, 13, -4, 14], [13, 1, 15], [13, 2, 13, 16], [15, 1, 17], [15, 3, -29, 2, -30], [15, 1, -15], [15, 1, -16], [15, 1, 18], [18, 3, -13, -29, -30], [18, 4, -13, -29, 19, -30], [19, 1, 20], [19, 3, 20, -31, 19], [20, 1, 2], [12, 1, 14], [12, 1, 21], [21, 1, -28], [21, 2, -28, 14], [21, 1, 22], [14, 1, 23], [14, 3, 14, -28, 23], [14, 1, 24], [23, 2, 25, 26], [23, 1, 26], [23, 3, 25, 26, 27], [23, 2, 26, 27], [23, 1, 28], [27, 1, 16], [27, 2, 16, 27], [25, 2, -14, -3], [25, 1, -32], [26, 1, 29], [26, 3, -20, -29, -30], [26, 4, -21, -29, -15, -30], [16, 3, -33, 30, -34], [30, 1, 2], [22, 2, -4, 14], [24, 3, 14, -4, 23], [28, 1, -35], [28, 1, -2], [17, 2, -36, -18], [29, 1, -17], [29, 1, -19], [29, 1, -18] ]; XPathParser.DOUBLEDOT = 2; XPathParser.DOUBLECOLON = 3; XPathParser.DOUBLESLASH = 4; XPathParser.NOTEQUAL = 5; XPathParser.LESSTHANOREQUAL = 6; XPathParser.GREATERTHANOREQUAL = 7; XPathParser.AND = 8; XPathParser.OR = 9; XPathParser.MOD = 10; XPathParser.DIV = 11; XPathParser.MULTIPLYOPERATOR = 12; XPathParser.FUNCTIONNAME = 13; XPathParser.AXISNAME = 14; XPathParser.LITERAL = 15; XPathParser.NUMBER = 16; XPathParser.ASTERISKNAMETEST = 17; XPathParser.QNAME = 18; XPathParser.NCNAMECOLONASTERISK = 19; XPathParser.NODETYPE = 20; XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21; XPathParser.EQUALS = 22; XPathParser.LESSTHAN = 23; XPathParser.GREATERTHAN = 24; XPathParser.PLUS = 25; XPathParser.MINUS = 26; XPathParser.BAR = 27; XPathParser.SLASH = 28; XPathParser.LEFTPARENTHESIS = 29; XPathParser.RIGHTPARENTHESIS = 30; XPathParser.COMMA = 31; XPathParser.AT = 32; XPathParser.LEFTBRACKET = 33; XPathParser.RIGHTBRACKET = 34; XPathParser.DOT = 35; XPathParser.DOLLAR = 36; XPathParser.prototype.tokenize = function (s1) { var types = []; var values = []; var s = s1 + '\0'; var pos = 0; var c = s.charAt(pos++); while (1) { while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { c = s.charAt(pos++); } if (c == '\0' || pos >= s.length) { break; } if (c == '(') { types.push(XPathParser.LEFTPARENTHESIS); values.push(c); c = s.charAt(pos++); continue; } if (c == ')') { types.push(XPathParser.RIGHTPARENTHESIS); values.push(c); c = s.charAt(pos++); continue; } if (c == '[') { types.push(XPathParser.LEFTBRACKET); values.push(c); c = s.charAt(pos++); continue; } if (c == ']') { types.push(XPathParser.RIGHTBRACKET); values.push(c); c = s.charAt(pos++); continue; } if (c == '@') { types.push(XPathParser.AT); values.push(c); c = s.charAt(pos++); continue; } if (c == ',') { types.push(XPathParser.COMMA); values.push(c); c = s.charAt(pos++); continue; } if (c == '|') { types.push(XPathParser.BAR); values.push(c); c = s.charAt(pos++); continue; } if (c == '+') { types.push(XPathParser.PLUS); values.push(c); c = s.charAt(pos++); continue; } if (c == '-') { types.push(XPathParser.MINUS); values.push(c); c = s.charAt(pos++); continue; } if (c == '=') { types.push(XPathParser.EQUALS); values.push(c); c = s.charAt(pos++); continue; } if (c == '$') { types.push(XPathParser.DOLLAR); values.push(c); c = s.charAt(pos++); continue; } if (c == '.') { c = s.charAt(pos++); if (c == '.') { types.push(XPathParser.DOUBLEDOT); values.push(".."); c = s.charAt(pos++); continue; } if (c >= '0' && c <= '9') { var number = "." + c; c = s.charAt(pos++); while (c >= '0' && c <= '9') { number += c; c = s.charAt(pos++); } types.push(XPathParser.NUMBER); values.push(number); continue; } types.push(XPathParser.DOT); values.push('.'); continue; } if (c == '\'' || c == '"') { var delimiter = c; var literal = ""; while (pos < s.length && (c = s.charAt(pos)) !== delimiter) { literal += c; pos += 1; } if (c !== delimiter) { throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal); } pos += 1; types.push(XPathParser.LITERAL); values.push(literal); c = s.charAt(pos++); continue; } if (c >= '0' && c <= '9') { var number = c; c = s.charAt(pos++); while (c >= '0' && c <= '9') { number += c; c = s.charAt(pos++); } if (c == '.') { if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') { number += c; number += s.charAt(pos++); c = s.charAt(pos++); while (c >= '0' && c <= '9') { number += c; c = s.charAt(pos++); } } } types.push(XPathParser.NUMBER); values.push(number); continue; } if (c == '*') { if (types.length > 0) { var last = types[types.length - 1]; if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) { types.push(XPathParser.MULTIPLYOPERATOR); values.push(c); c = s.charAt(pos++); continue; } } types.push(XPathParser.ASTERISKNAMETEST); values.push(c); c = s.charAt(pos++); continue; } if (c == ':') { if (s.charAt(pos) == ':') { types.push(XPathParser.DOUBLECOLON); values.push("::"); pos++; c = s.charAt(pos++); continue; } } if (c == '/') { c = s.charAt(pos++); if (c == '/') { types.push(XPathParser.DOUBLESLASH); values.push("//"); c = s.charAt(pos++); continue; } types.push(XPathParser.SLASH); values.push('/'); continue; } if (c == '!') { if (s.charAt(pos) == '=') { types.push(XPathParser.NOTEQUAL); values.push("!="); pos++; c = s.charAt(pos++); continue; } } if (c == '<') { if (s.charAt(pos) == '=') { types.push(XPathParser.LESSTHANOREQUAL); values.push("<="); pos++; c = s.charAt(pos++); continue; } types.push(XPathParser.LESSTHAN); values.push('<'); c = s.charAt(pos++); continue; } if (c == '>') { if (s.charAt(pos) == '=') { types.push(XPathParser.GREATERTHANOREQUAL); values.push(">="); pos++; c = s.charAt(pos++); continue; } types.push(XPathParser.GREATERTHAN); values.push('>'); c = s.charAt(pos++); continue; } if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) { var name = c; c = s.charAt(pos++); while (Utilities.isNCNameChar(c.charCodeAt(0))) { name += c; c = s.charAt(pos++); } if (types.length > 0) { var last = types[types.length - 1]; if (last != XPathParser.AT && last != XPathParser.DOUBLECOLON && last != XPathParser.LEFTPARENTHESIS && last != XPathParser.LEFTBRACKET && last != XPathParser.AND && last != XPathParser.OR && last != XPathParser.MOD && last != XPathParser.DIV && last != XPathParser.MULTIPLYOPERATOR && last != XPathParser.SLASH && last != XPathParser.DOUBLESLASH && last != XPathParser.BAR && last != XPathParser.PLUS && last != XPathParser.MINUS && last != XPathParser.EQUALS && last != XPathParser.NOTEQUAL && last != XPathParser.LESSTHAN && last != XPathParser.LESSTHANOREQUAL && last != XPathParser.GREATERTHAN && last != XPathParser.GREATERTHANOREQUAL) { if (name == "and") { types.push(XPathParser.AND); values.push(name); continue; } if (name == "or") { types.push(XPathParser.OR); values.push(name); continue; } if (name == "mod") { types.push(XPathParser.MOD); values.push(name); continue; } if (name == "div") { types.push(XPathParser.DIV); values.push(name); continue; } } } if (c == ':') { if (s.charAt(pos) == '*') { types.push(XPathParser.NCNAMECOLONASTERISK); values.push(name + ":*"); pos++; c = s.charAt(pos++); continue; } if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) { name += ':'; c = s.charAt(pos++); while (Utilities.isNCNameChar(c.charCodeAt(0))) { name += c; c = s.charAt(pos++); } if (c == '(') { types.push(XPathParser.FUNCTIONNAME); values.push(name); continue; } types.push(XPathParser.QNAME); values.push(name); continue; } if (s.charAt(pos) == ':') { types.push(XPathParser.AXISNAME); values.push(name); continue; } } if (c == '(') { if (name == "comment" || name == "text" || name == "node") { types.push(XPathParser.NODETYPE); values.push(name); continue; } if (name == "processing-instruction") { if (s.charAt(pos) == ')') { types.push(XPathParser.NODETYPE); } else { types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL); } values.push(name); continue; } types.push(XPathParser.FUNCTIONNAME); values.push(name); continue; } types.push(XPathParser.QNAME); values.push(name); continue; } throw new Error("Unexpected character " + c); } types.push(1); values.push("[EOF]"); return [types, values]; }; XPathParser.SHIFT = 's'; XPathParser.REDUCE = 'r'; XPathParser.ACCEPT = 'a'; XPathParser.prototype.parse = function (s) { if (!s) { throw new Error('XPath expression unspecified.'); } if (typeof s !== 'string'){ throw new Error('XPath expression must be a string.'); } var types; var values; var res = this.tokenize(s); if (res == undefined) { return undefined; } types = res[0]; values = res[1]; var tokenPos = 0; var state = []; var tokenType = []; var tokenValue = []; var s; var a; var t; state.push(0); tokenType.push(1); tokenValue.push("_S"); a = types[tokenPos]; t = values[tokenPos++]; while (1) { s = state[state.length - 1]; switch (XPathParser.actionTable[s].charAt(a - 1)) { case XPathParser.SHIFT: tokenType.push(-a); tokenValue.push(t); state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32); a = types[tokenPos]; t = values[tokenPos++]; break; case XPathParser.REDUCE: var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1]; var rhs = []; for (var i = 0; i < num; i++) { tokenType.pop(); rhs.unshift(tokenValue.pop()); state.pop(); } var s_ = state[state.length - 1]; tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]); if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) { tokenValue.push(rhs[0]); } else { tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs)); } state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33); break; case XPathParser.ACCEPT: return new XPath(tokenValue.pop()); default: throw new Error("XPath parse error"); } } }; // XPath ///////////////////////////////////////////////////////////////////// XPath.prototype = new Object(); XPath.prototype.constructor = XPath; XPath.superclass = Object.prototype; function XPath(e) { this.expression = e; } XPath.prototype.toString = function () { return this.expression.toString(); }; function setIfUnset(obj, prop, value) { if (!(prop in obj)) { obj[prop] = value; } } XPath.prototype.evaluate = function (c) { var node = c.expressionContextNode; if (!(isNil(node) || isNodeLike(node))) { throw new Error("Context node does not appear to be a valid DOM node."); } c.contextNode = c.expressionContextNode; c.contextSize = 1; c.contextPosition = 1; // [2017-11-25] Removed usage of .implementation.hasFeature() since it does // not reliably detect HTML DOMs (always returns false in xmldom and true in browsers) if (c.isHtml) { setIfUnset(c, 'caseInsensitive', true); setIfUnset(c, 'allowAnyNamespaceForNoPrefix', true); } setIfUnset(c, 'caseInsensitive', false); return this.expression.evaluate(c); }; XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/"; // Expression //////////////////////////////////////////////////////////////// Expression.prototype = new Object(); Expression.prototype.constructor = Expression; Expression.superclass = Object.prototype; function Expression() { } Expression.prototype.init = function () { }; Expression.prototype.toString = function () { return ""; }; Expression.prototype.evaluate = function (c) { throw new Error("Could not evaluate expression."); }; // UnaryOperation //////////////////////////////////////////////////////////// UnaryOperation.prototype = new Expression(); UnaryOperation.prototype.constructor = UnaryOperation; UnaryOperation.superclass = Expression.prototype; function UnaryOperation(rhs) { if (arguments.length > 0) { this.init(rhs); } } UnaryOperation.prototype.init = function (rhs) { this.rhs = rhs; }; // UnaryMinusOperation /////////////////////////////////////////////////////// UnaryMinusOperation.prototype = new UnaryOperation(); UnaryMinusOperation.prototype.constructor = UnaryMinusOperation; UnaryMinusOperation.superclass = UnaryOperation.prototype; function UnaryMinusOperation(rhs) { if (arguments.length > 0) { this.init(rhs); } } UnaryMinusOperation.prototype.init = function (rhs) { UnaryMinusOperation.superclass.init.call(this, rhs); }; UnaryMinusOperation.prototype.evaluate = function (c) { return this.rhs.evaluate(c).number().negate(); }; UnaryMinusOperation.prototype.toString = function () { return "-" + this.rhs.toString(); }; // BinaryOperation /////////////////////////////////////////////////////////// BinaryOperation.prototype = new Expression(); BinaryOperation.prototype.constructor = BinaryOperation; BinaryOperation.superclass = Expression.prototype; function BinaryOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } BinaryOperation.prototype.init = function (lhs, rhs) { this.lhs = lhs; this.rhs = rhs; }; // OrOperation /////////////////////////////////////////////////////////////// OrOperation.prototype = new BinaryOperation(); OrOperation.prototype.constructor = OrOperation; OrOperation.superclass = BinaryOperation.prototype; function OrOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } OrOperation.prototype.init = function (lhs, rhs) { OrOperation.superclass.init.call(this, lhs, rhs); }; OrOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")"; }; OrOperation.prototype.evaluate = function (c) { var b = this.lhs.evaluate(c).bool(); if (b.booleanValue()) { return b; } return this.rhs.evaluate(c).bool(); }; // AndOperation ////////////////////////////////////////////////////////////// AndOperation.prototype = new BinaryOperation(); AndOperation.prototype.constructor = AndOperation; AndOperation.superclass = BinaryOperation.prototype; function AndOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } AndOperation.prototype.init = function (lhs, rhs) { AndOperation.superclass.init.call(this, lhs, rhs); }; AndOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")"; }; AndOperation.prototype.evaluate = function (c) { var b = this.lhs.evaluate(c).bool(); if (!b.booleanValue()) { return b; } return this.rhs.evaluate(c).bool(); }; // EqualsOperation /////////////////////////////////////////////////////////// EqualsOperation.prototype = new BinaryOperation(); EqualsOperation.prototype.constructor = EqualsOperation; EqualsOperation.superclass = BinaryOperation.prototype; function EqualsOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } EqualsOperation.prototype.init = function (lhs, rhs) { EqualsOperation.superclass.init.call(this, lhs, rhs); }; EqualsOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")"; }; EqualsOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).equals(this.rhs.evaluate(c)); }; // NotEqualOperation ///////////////////////////////////////////////////////// NotEqualOperation.prototype = new BinaryOperation(); NotEqualOperation.prototype.constructor = NotEqualOperation; NotEqualOperation.superclass = BinaryOperation.prototype; function NotEqualOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } NotEqualOperation.prototype.init = function (lhs, rhs) { NotEqualOperation.superclass.init.call(this, lhs, rhs); }; NotEqualOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")"; }; NotEqualOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c)); }; // LessThanOperation ///////////////////////////////////////////////////////// LessThanOperation.prototype = new BinaryOperation(); LessThanOperation.prototype.constructor = LessThanOperation; LessThanOperation.superclass = BinaryOperation.prototype; function LessThanOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } LessThanOperation.prototype.init = function (lhs, rhs) { LessThanOperation.superclass.init.call(this, lhs, rhs); }; LessThanOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c)); }; LessThanOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")"; }; // GreaterThanOperation ////////////////////////////////////////////////////// GreaterThanOperation.prototype = new BinaryOperation(); GreaterThanOperation.prototype.constructor = GreaterThanOperation; GreaterThanOperation.superclass = BinaryOperation.prototype; function GreaterThanOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } GreaterThanOperation.prototype.init = function (lhs, rhs) { GreaterThanOperation.superclass.init.call(this, lhs, rhs); }; GreaterThanOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c)); }; GreaterThanOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")"; }; // LessThanOrEqualOperation ////////////////////////////////////////////////// LessThanOrEqualOperation.prototype = new BinaryOperation(); LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation; LessThanOrEqualOperation.superclass = BinaryOperation.prototype; function LessThanOrEqualOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } LessThanOrEqualOperation.prototype.init = function (lhs, rhs) { LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs); }; LessThanOrEqualOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c)); }; LessThanOrEqualOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")"; }; // GreaterThanOrEqualOperation /////////////////////////////////////////////// GreaterThanOrEqualOperation.prototype = new BinaryOperation(); GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation; GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype; function GreaterThanOrEqualOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } GreaterThanOrEqualOperation.prototype.init = function (lhs, rhs) { GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs); }; GreaterThanOrEqualOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c)); }; GreaterThanOrEqualOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")"; }; // PlusOperation ///////////////////////////////////////////////////////////// PlusOperation.prototype = new BinaryOperation(); PlusOperation.prototype.constructor = PlusOperation; PlusOperation.superclass = BinaryOperation.prototype; function PlusOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } PlusOperation.prototype.init = function (lhs, rhs) { PlusOperation.superclass.init.call(this, lhs, rhs); }; PlusOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number()); }; PlusOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")"; }; // MinusOperation //////////////////////////////////////////////////////////// MinusOperation.prototype = new BinaryOperation(); MinusOperation.prototype.constructor = MinusOperation; MinusOperation.superclass = BinaryOperation.prototype; function MinusOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } MinusOperation.prototype.init = function (lhs, rhs) { MinusOperation.superclass.init.call(this, lhs, rhs); }; MinusOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number()); }; MinusOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")"; }; // MultiplyOperation ///////////////////////////////////////////////////////// MultiplyOperation.prototype = new BinaryOperation(); MultiplyOperation.prototype.constructor = MultiplyOperation; MultiplyOperation.superclass = BinaryOperation.prototype; function MultiplyOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } MultiplyOperation.prototype.init = function (lhs, rhs) { MultiplyOperation.superclass.init.call(this, lhs, rhs); }; MultiplyOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number()); }; MultiplyOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")"; }; // DivOperation ////////////////////////////////////////////////////////////// DivOperation.prototype = new BinaryOperation(); DivOperation.prototype.constructor = DivOperation; DivOperation.superclass = BinaryOperation.prototype; function DivOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } DivOperation.prototype.init = function (lhs, rhs) { DivOperation.superclass.init.call(this, lhs, rhs); }; DivOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number()); }; DivOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")"; }; // ModOperation ////////////////////////////////////////////////////////////// ModOperation.prototype = new BinaryOperation(); ModOperation.prototype.constructor = ModOperation; ModOperation.superclass = BinaryOperation.prototype; function ModOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } ModOperation.prototype.init = function (lhs, rhs) { ModOperation.superclass.init.call(this, lhs, rhs); }; ModOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number()); }; ModOperation.prototype.toString = function () { return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")"; }; // BarOperation ////////////////////////////////////////////////////////////// BarOperation.prototype = new BinaryOperation(); BarOperation.prototype.constructor = BarOperation; BarOperation.superclass = BinaryOperation.prototype; function BarOperation(lhs, rhs) { if (arguments.length > 0) { this.init(lhs, rhs); } } BarOperation.prototype.init = function (lhs, rhs) { BarOperation.superclass.init.call(this, lhs, rhs); }; BarOperation.prototype.evaluate = function (c) { return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset()); }; BarOperation.prototype.toString = function () { return map(toString, [this.lhs, this.rhs]).join(' | '); }; // PathExpr ////////////////////////////////////////////////////////////////// PathExpr.prototype = new Expression(); PathExpr.prototype.constructor = PathExpr; PathExpr.superclass = Expression.prototype; function PathExpr(filter, filterPreds, locpath) { if (arguments.length > 0) { this.init(filter, filterPreds, locpath); } } PathExpr.prototype.init = function (filter, filterPreds, locpath) { PathExpr.superclass.init.call(this); this.filter = filter; this.filterPredicates = filterPreds; this.locationPath = locpath; }; /** * Returns the topmost node of the tree containing node */ function findRoot(node) { while (node && node.parentNode) { node = node.parentNode; } return node; } var applyPredicates = function (predicates, c, nodes, reverse) { if (predicates.length === 0) { return nodes; } var ctx = c.extend({}); return reduce( function (inNodes, pred) { ctx.contextSize = inNodes.length; return filter( function (node, i) { ctx.contextNode = node; ctx.contextPosition = i + 1; return PathExpr.predicateMatches(pred, ctx); }, inNodes ); }, sortNodes(nodes, reverse), predicates ); }; PathExpr.getRoot = function (xpc, nodes) { var firstNode = nodes[0]; // xpc.virtualRoot could possibly provide a root even if firstNode is null, // so using a guard here instead of throwing. if (firstNode && firstNode.nodeType === NodeTypes.DOCUMENT_NODE) { return firstNode; } if (xpc.virtualRoot) { return xpc.virtualRoot; } if (!firstNode) { throw new Error('Context node not found when determining document root.'); } var ownerDoc = firstNode.ownerDocument; if (ownerDoc) { return ownerDoc; } // IE 5.5 doesn't have ownerDocument? var n = firstNode; while (n.parentNode != null) { n = n.parentNode; } return n; } var getPrefixForNamespaceNode = function (attrNode) { var nm = String(attrNode.name); if (nm === "xmlns") { return ""; } if (nm.substring(0, 6) === "xmlns:") { return nm.substring(6, nm.length); } return null; }; PathExpr.applyStep = function (step, xpc, node) { if (!node) { throw new Error('Context node not found when evaluating XPath step: ' + step); } var newNodes = []; xpc.contextNode = node; switch (step.axis) { case Step.ANCESTOR: // look at all the ancestor nodes if (xpc.contextNode === xpc.virtualRoot) { break; } var m; if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) { m = PathExpr.getOwnerElement(xpc.contextNode); } else { m = xpc.contextNode.parentNode; } while (m != null) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m === xpc.virtualRoot) { break; } m = m.parentNode; } break; case Step.ANCESTORORSELF: // look at all the ancestor nodes and the current node for (var m = xpc.contextNode; m != null; m = m.nodeType == NodeTypes.ATTRIBUTE_NODE ? PathExpr.getOwnerElement(m) : m.parentNode) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m === xpc.virtualRoot) { break; } } break; case Step.ATTRIBUTE: // look at the attributes var nnm = xpc.contextNode.attributes; if (nnm != null) { for (var k = 0; k < nnm.length; k++) { var m = nnm.item(k); if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } } break; case Step.CHILD: // look at all child elements for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } break; case Step.DESCENDANT: // look at all descendant nodes var st = [xpc.contextNode.firstChild]; while (st.length > 0) { for (var m = st.pop(); m != null;) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } break; case Step.DESCENDANTORSELF: // look at self if (step.nodeTest.matches(xpc.contextNode, xpc)) { newNodes.push(xpc.contextNode); } // look at all descendant nodes var st = [xpc.contextNode.firstChild]; while (st.length > 0) { for (var m = st.pop(); m != null;) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } break; case Step.FOLLOWING: if (xpc.contextNode === xpc.virtualRoot) { break; } var st = []; if (xpc.contextNode.firstChild != null) { st.unshift(xpc.contextNode.firstChild); } else { st.unshift(xpc.contextNode.nextSibling); } for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != NodeTypes.DOCUMENT_NODE && m !== xpc.virtualRoot; m = m.parentNode) { st.unshift(m.nextSibling); } do { for (var m = st.pop(); m != null;) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } while (st.length > 0); break; case Step.FOLLOWINGSIBLING: if (xpc.contextNode === xpc.virtualRoot) { break; } for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } break; case Step.NAMESPACE: var nodes = {}; if (xpc.contextNode.nodeType == NodeTypes.ELEMENT_NODE) { // BUG: This only collects the namespaces on the current node, but seemingly // it should collect all those in scope nodes["xml"] = new XPathNamespace("xml", null, XPath.XML_NAMESPACE_URI, xpc.contextNode); for (var m = xpc.contextNode; m != null && m.nodeType == NodeTypes.ELEMENT_NODE; m = m.parentNode) { for (var k = 0; k < m.attributes.length; k++) { var attr = m.attributes.item(k); var pre = getPrefixForNamespaceNode(attr); if (pre != null && nodes[pre] == undefined) { nodes[pre] = new XPathNamespace(pre, attr, attr.value, xpc.contextNode); } } } for (var pre in nodes) { var node = nodes[pre]; if (step.nodeTest.matches(node, xpc)) { newNodes.push(node); } } } break; case Step.PARENT: m = null; if (xpc.contextNode !== xpc.virtualRoot) { if (xpc.contextNode.nodeType == NodeTypes.ATTRIBUTE_NODE) { m = PathExpr.getOwnerElement(xpc.contextNode); } else { m = xpc.contextNode.parentNode; } } if (m != null && step.nodeTest.matches(m, xpc)) { newNodes.push(m); } break; case Step.PRECEDING: var st; if (xpc.virtualRoot != null) { st = [xpc.virtualRoot]; } else { // cannot rely on .ownerDocument because the node may be in a document fragment st = [findRoot(xpc.contextNode)]; } outer: while (st.length > 0) { for (var m = st.pop(); m != null;) { if (m == xpc.contextNode) { break outer; } if (step.nodeTest.matches(m, xpc)) { newNodes.unshift(m); } if (m.firstChild != null) { st.push(m.nextSibling); m = m.firstChild; } else { m = m.nextSibling; } } } break; case Step.PRECEDINGSIBLING: if (xpc.contextNode === xpc.virtualRoot) { break; } for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) { if (step.nodeTest.matches(m, xpc)) { newNodes.push(m); } } break; case Step.SELF: if (step.nodeTest.matches(xpc.contextNode, xpc)) { newNodes.push(xpc.contextNode); } break; default: } return newNodes; }; function applyStepWithPredicates(step, xpc, node) { return applyPredicates( step.predicates, xpc, PathExpr.applyStep(step, xpc, node), includes(REVERSE_AXES, step.axis) ); } function applyStepToNodes(context, nodes, step) { return flatten( map( applyStepWithPredicates.bind(null, step, context), nodes ) ); } PathExpr.applySteps = function (steps, xpc, nodes) { return reduce( applyStepToNodes.bind(null, xpc), nodes, steps ); } PathExpr.prototype.applyFilter = function (c, xpc) { if (!this.filter) { return { nodes: [c.contextNode] }; } var ns = this.filter.evaluate(c); if (!Utilities.instance_of(ns, XNodeSet)) { if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) { throw new Error("Path expression filter must evaluate to a nodeset if predicates or location path are used"); } return { nonNodes: ns }; } return { nodes: applyPredicates( this.filterPredicates || [], xpc, ns.toUnsortedArray(), false // reverse ) }; }; PathExpr.applyLocationPath = function (locationPath, xpc, nodes) { if (!locationPath) { return nodes; } var startNodes = locationPath.absolute ? [PathExpr.getRoot(xpc, nodes)] : nodes; return PathExpr.applySteps(locationPath.steps, xpc, startNodes); }; PathExpr.prototype.evaluate = function (c) { var xpc = assign(new XPathContext(), c); var filterResult = this.applyFilter(c, xpc); if ('nonNodes' in filterResult) { return filterResult.nonNodes; } var ns = new XNodeSet(); ns.addArray(PathExpr.applyLocationPath(this.locationPath, xpc, filterResult.nodes)); return ns; }; PathExpr.predicateMatches = function (pred, c) { var res = pred.evaluate(c); return Utilities.instance_of(res, XNumber) ? c.contextPosition === res.numberValue() : res.booleanValue(); }; PathExpr.predicateString = function (predicate) { return wrap('[', ']', predicate.toString()); } PathExpr.predicatesString = function (predicates) { return join( '', map(PathExpr.predicateString, predicates) ); } PathExpr.prototype.toString = function () { if (this.filter != undefined) { var filterStr = toString(this.filter); if (Utilities.instance_of(this.filter, XString)) { return wrap("'", "'", filterStr); } if (this.filterPredicates != undefined && this.filterPredicates.length) { return wrap('(', ')', filterStr) + PathExpr.predicatesString(this.filterPredicates); } if (this.locationPath != undefined) { return filterStr + (this.locationPath.absolute ? '' : '/') + toString(this.locationPath); } return filterStr; } return toString(this.locationPath); }; PathExpr.getOwnerElement = function (n) { // DOM 2 has ownerElement if (n.ownerElement) { return n.ownerElement; } // DOM 1 Internet Explorer can use selectSingleNode (ironically) try { if (n.selectSingleNode) { return n.selectSingleNode(".."); } } catch (e) { } // Other DOM 1 implementations must use this egregious search var doc = n.nodeType == NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument; var elts = doc.getElementsByTagName("*"); for (var i = 0; i < elts.length; i++) { var elt = elts.item(i); var nnm = elt.attributes; for (var j = 0; j < nnm.length; j++) { var an = nnm.item(j); if (an === n) { return elt; } } } return null; }; // LocationPath ////////////////////////////////////////////////////////////// LocationPath.prototype = new Object(); LocationPath.prototype.constructor = LocationPath; LocationPath.superclass = Object.prototype; function LocationPath(abs, steps) { if (arguments.length > 0) { this.init(abs, steps); } } LocationPath.prototype.init = function (abs, steps) { this.absolute = abs; this.steps = steps; }; LocationPath.prototype.toString = function () { return ( (this.absolute ? '/' : '') + map(toString, this.steps).join('/') ); }; // Step ////////////////////////////////////////////////////////////////////// Step.prototype = new Object(); Step.prototype.constructor = Step; Step.superclass = Object.prototype; function Step(axis, nodetest, preds) { if (arguments.length > 0) { this.init(axis, nodetest, preds); } } Step.prototype.init = function (axis, nodetest, preds) { this.axis = axis; this.nodeTest = nodetest; this.predicates = preds; }; Step.prototype.toString = function () { return Step.STEPNAMES[this.axis] + "::" + this.nodeTest.toString() + PathExpr.predicatesString(this.predicates); }; Step.ANCESTOR = 0; Step.ANCESTORORSELF = 1; Step.ATTRIBUTE = 2; Step.CHILD = 3; Step.DESCENDANT = 4; Step.DESCENDANTORSELF = 5; Step.FOLLOWING = 6; Step.FOLLOWINGSIBLING = 7; Step.NAMESPACE = 8; Step.PARENT = 9; Step.PRECEDING = 10; Step.PRECEDINGSIBLING = 11; Step.SELF = 12; Step.STEPNAMES = reduce(function (acc, x) { return acc[x[0]] = x[1], acc; }, {}, [ [Step.ANCESTOR, 'ancestor'], [Step.ANCESTORORSELF, 'ancestor-or-self'], [Step.ATTRIBUTE, 'attribute'], [Step.CHILD, 'child'], [Step.DESCENDANT, 'descendant'], [Step.DESCENDANTORSELF, 'descendant-or-self'], [Step.FOLLOWING, 'following'], [Step.FOLLOWINGSIBLING, 'following-sibling'], [Step.NAMESPACE, 'namespace'], [Step.PARENT, 'parent'], [Step.PRECEDING, 'preceding'], [Step.PRECEDINGSIBLING, 'preceding-sibling'], [Step.SELF, 'self'] ]); var REVERSE_AXES = [ Step.ANCESTOR, Step.ANCESTORORSELF, Step.PARENT, Step.PRECEDING, Step.PRECEDINGSIBLING ]; // NodeTest ////////////////////////////////////////////////////////////////// NodeTest.prototype = new Object(); NodeTest.prototype.constructor = NodeTest; NodeTest.superclass = Object.prototype; function NodeTest(type, value) { if (arguments.length > 0) { this.init(type, value); } } NodeTest.prototype.init = function (type, value) { this.type = type; this.value = value; }; NodeTest.prototype.toString = function () { return ""; }; NodeTest.prototype.matches = function (n, xpc) { console.warn('unknown node test type'); }; NodeTest.NAMETESTANY = 0; NodeTest.NAMETESTPREFIXANY = 1; NodeTest.NAMETESTQNAME = 2; NodeTest.COMMENT = 3; NodeTest.TEXT = 4; NodeTest.PI = 5; NodeTest.NODE = 6; NodeTest.isNodeType = function (types) { return function (node) { return includes(types, node.nodeType); }; }; NodeTest.makeNodeTestType = function (type, members, ctor) { var newType = ctor || function () { }; newType.prototype = new NodeTest(type); newType.prototype.constructor = newType; assign(newType.prototype, members); return newType; }; // create invariant node test for certain node types NodeTest.makeNodeTypeTest = function (type, nodeTypes, stringVal) { return new (NodeTest.makeNodeTestType(type, { matches: NodeTest.isNodeType(nodeTypes), toString: always(stringVal) }))(); }; NodeTest.hasPrefix = function (node) { return node.prefix || (node.nodeName || node.tagName).indexOf(':') !== -1; }; NodeTest.isElementOrAttribute = NodeTest.isNodeType([1, 2]); NodeTest.nameSpaceMatches = function (prefix, xpc, n) { var nNamespace = (n.namespaceURI || ''); if (!prefix) { return !nNamespace || (xpc.allowAnyNamespaceForNoPrefix && !NodeTest.hasPrefix(n)); } var ns = xpc.namespaceResolver.getNamespace(prefix, xpc.expressionContextNode); if (ns == null) { throw new Error("Cannot resolve QName " + prefix); } return ns === nNamespace; }; NodeTest.localNameMatches = function (localName, xpc, n) { var nLocalName = (n.localName || n.nodeName); return xpc.caseInsensitive ? localName.toLowerCase() === nLocalName.toLowerCase() : localName === nLocalName; }; NodeTest.NameTestPrefixAny = NodeTest.makeNodeTestType( NodeTest.NAMETESTPREFIXANY, { matches: function (n, xpc) { return NodeTest.isElementOrAttribute(n) && NodeTest.nameSpaceMatches(this.prefix, xpc, n); }, toString: function () { return this.prefix + ":*"; } }, function NameTestPrefixAny(prefix) { this.prefix = prefix; } ); NodeTest.NameTestQName = NodeTest.makeNodeTestType( NodeTest.NAMETESTQNAME, { matches: function (n, xpc) { return NodeTest.isNodeType( [ NodeTypes.ELEMENT_NODE, NodeTypes.ATTRIBUTE_NODE, NodeTypes.NAMESPACE_NODE, ] )(n) && NodeTest.nameSpaceMatches(this.prefix, xpc, n) && NodeTest.localNameMatches(this.localName, xpc, n); }, toString: function () { return this.name; } }, function NameTestQName(name) { var nameParts = name.split(':'); this.name = name; this.prefix = nameParts.length > 1 ? nameParts[0] : null; this.localName = nameParts[nameParts.length > 1 ? 1 : 0]; } ); NodeTest.PITest = NodeTest.makeNodeTestType(NodeTest.PI, { matches: function (n, xpc) { return NodeTest.isNodeType( [NodeTypes.PROCESSING_INSTRUCTION_NODE] )(n) && (n.target || n.nodeName) === this.name; }, toString: function () { return wrap('processing-instruction("', '")', this.name); } }, function (name) { this.name = name; }) // singletons // elements, attributes, namespaces NodeTest.nameTestAny = NodeTest.makeNodeTypeTest( NodeTest.NAMETESTANY, [ NodeTypes.ELEMENT_NODE, NodeTypes.ATTRIBUTE_NODE, NodeTypes.NAMESPACE_NODE, ], '*' ); // text, cdata NodeTest.textTest = NodeTest.makeNodeTypeTest( NodeTest.TEXT, [ NodeTypes.TEXT_NODE, NodeTypes.CDATA_SECTION_NODE, ], 'text()' ); NodeTest.commentTest = NodeTest.makeNodeTypeTest( NodeTest.COMMENT, [NodeTypes.COMMENT_NODE], 'comment()' ); // elements, attributes, text, cdata, PIs, comments, document nodes NodeTest.nodeTest = NodeTest.makeNodeTypeTest( NodeTest.NODE, [ NodeTypes.ELEMENT_NODE, NodeTypes.ATTRIBUTE_NODE, NodeTypes.TEXT_NODE, NodeTypes.CDATA_SECTION_NODE, NodeTypes.PROCESSING_INSTRUCTION_NODE, NodeTypes.COMMENT_NODE, NodeTypes.DOCUMENT_NODE, ], 'node()' ); NodeTest.anyPiTest = NodeTest.makeNodeTypeTest( NodeTest.PI, [NodeTypes.PROCESSING_INSTRUCTION_NODE], 'processing-instruction()' ); // VariableReference ///////////////////////////////////////////////////////// VariableReference.prototype = new Expression(); VariableReference.prototype.constructor = VariableReference; VariableReference.superclass = Expression.prototype; function VariableReference(v) { if (arguments.length > 0) { this.init(v); } } VariableReference.prototype.init = function (v) { this.variable = v; }; VariableReference.prototype.toString = function () { return "$" + this.variable; }; VariableReference.prototype.evaluate = function (c) { var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false); if (parts[0] == null) { throw new Error("Cannot resolve QName " + fn); } var result = c.variableResolver.getVariable(parts[1], parts[0]); if (!result) { throw XPathException.fromMessage("Undeclared variable: " + this.toString()); } return result; }; // FunctionCall ////////////////////////////////////////////////////////////// FunctionCall.prototype = new Expression(); FunctionCall.prototype.constructor = FunctionCall; FunctionCall.superclass = Expression.prototype; function FunctionCall(fn, args) { if (arguments.length > 0) { this.init(fn, args); } } FunctionCall.prototype.init = function (fn, args) { this.functionName = fn; this.arguments = args; }; FunctionCall.prototype.toString = function () { var s = this.functionName + "("; for (var i = 0; i < this.arguments.length; i++) { if (i > 0) { s += ", "; } s += this.arguments[i].toString(); } return s + ")"; }; FunctionCall.prototype.evaluate = function (c) { var f = FunctionResolver.getFunctionFromContext(this.functionName, c); if (!f) { throw new Error("Unknown function " + this.functionName); } var a = [c].concat(this.arguments); return f.apply(c.functionResolver.thisArg, a); }; // Operators ///////////////////////////////////////////////////////////////// var Operators = new Object(); Operators.equals = function (l, r) { return l.equals(r); }; Operators.notequal = function (l, r) { return l.notequal(r); }; Operators.lessthan = function (l, r) { return l.lessthan(r); }; Operators.greaterthan = function (l, r) { return l.greaterthan(r); }; Operators.lessthanorequal = function (l, r) { return l.lessthanorequal(r); }; Operators.greaterthanorequal = function (l, r) { return l.greaterthanorequal(r); }; // XString /////////////////////////////////////////////////////////////////// XString.prototype = new Expression(); XString.prototype.constructor = XString; XString.superclass = Expression.prototype; function XString(s) { if (arguments.length > 0) { this.init(s); } } XString.prototype.init = function (s) { this.str = String(s); }; XString.prototype.toString = function () { return this.str; }; XString.prototype.evaluate = function (c) { return this; }; XString.prototype.string = function () { return this; }; XString.prototype.number = function () { return new XNumber(this.str); }; XString.prototype.bool = function () { return new XBoolean(this.str); }; XString.prototype.nodeset = function () { throw new Error("Cannot convert string to nodeset"); }; XString.prototype.stringValue = function () { return this.str; }; XString.prototype.numberValue = function () { return this.number().numberValue(); }; XString.prototype.booleanValue = function () { return this.bool().booleanValue(); }; XString.prototype.equals = function (r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().equals(r); } if (Utilities.instance_of(r, XNumber)) { return this.number().equals(r); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithString(this, Operators.equals); } return new XBoolean(this.str == r.str); }; XString.prototype.notequal = function (r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().notequal(r); } if (Utilities.instance_of(r, XNumber)) { return this.number().notequal(r); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithString(this, Operators.notequal); } return new XBoolean(this.str != r.str); }; XString.prototype.lessthan = function (r) { return this.number().lessthan(r); }; XString.prototype.greaterthan = function (r) { return this.number().greaterthan(r); }; XString.prototype.lessthanorequal = function (r) { return this.number().lessthanorequal(r); }; XString.prototype.greaterthanorequal = function (r) { return this.number().greaterthanorequal(r); }; // XNumber /////////////////////////////////////////////////////////////////// XNumber.prototype = new Expression(); XNumber.prototype.constructor = XNumber; XNumber.superclass = Expression.prototype; function XNumber(n) { if (arguments.length > 0) { this.init(n); } } XNumber.prototype.init = function (n) { this.num = typeof n === "string" ? this.parse(n) : Number(n); }; XNumber.prototype.numberFormat = /^\s*-?[0-9]*\.?[0-9]+\s*$/; XNumber.prototype.parse = function (s) { // XPath representation of numbers is more restrictive than what Number() or parseFloat() allow return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN; }; function padSmallNumber(numberStr) { var parts = numberStr.split('e-'); var base = parts[0].replace('.', ''); var exponent = Number(parts[1]); for (var i = 0; i < exponent - 1; i += 1) { base = '0' + base; } return '0.' + base; } function padLargeNumber(numberStr) { var parts = numberStr.split('e'); var base = parts[0].replace('.', ''); var exponent = Number(parts[1]); var zerosToAppend = exponent + 1 - base.length; for (var i = 0; i < zerosToAppend; i += 1) { base += '0'; } return base; } XNumber.prototype.toString = function () { var strValue = this.num.toString(); if (strValue.indexOf('e-') !== -1) { return padSmallNumber(strValue); } if (strValue.indexOf('e') !== -1) { return padLargeNumber(strValue); } return strValue; }; XNumber.prototype.evaluate = function (c) { return this; }; XNumber.prototype.string = function () { return new XString(this.toString()); }; XNumber.prototype.number = function () { return this; }; XNumber.prototype.bool = function () { return new XBoolean(this.num); }; XNumber.prototype.nodeset = function () { throw new Error("Cannot convert number to nodeset"); }; XNumber.prototype.stringValue = function () { return this.string().stringValue(); }; XNumber.prototype.numberValue = function () { return this.num; }; XNumber.prototype.booleanValue = function () { return this.bool().booleanValue(); }; XNumber.prototype.negate = function () { return new XNumber(-this.num); }; XNumber.prototype.equals = function (r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().equals(r); } if (Utilities.instance_of(r, XString)) { return this.equals(r.number()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.equals); } return new XBoolean(this.num == r.num); }; XNumber.prototype.notequal = function (r) { if (Utilities.instance_of(r, XBoolean)) { return this.bool().notequal(r); } if (Utilities.instance_of(r, XString)) { return this.notequal(r.number()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.notequal); } return new XBoolean(this.num != r.num); }; XNumber.prototype.lessthan = function (r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.greaterthan); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.lessthan(r.number()); } return new XBoolean(this.num < r.num); }; XNumber.prototype.greaterthan = function (r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.lessthan); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.greaterthan(r.number()); } return new XBoolean(this.num > r.num); }; XNumber.prototype.lessthanorequal = function (r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.greaterthanorequal); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.lessthanorequal(r.number()); } return new XBoolean(this.num <= r.num); }; XNumber.prototype.greaterthanorequal = function (r) { if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithNumber(this, Operators.lessthanorequal); } if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { return this.greaterthanorequal(r.number()); } return new XBoolean(this.num >= r.num); }; XNumber.prototype.plus = function (r) { return new XNumber(this.num + r.num); }; XNumber.prototype.minus = function (r) { return new XNumber(this.num - r.num); }; XNumber.prototype.multiply = function (r) { return new XNumber(this.num * r.num); }; XNumber.prototype.div = function (r) { return new XNumber(this.num / r.num); }; XNumber.prototype.mod = function (r) { return new XNumber(this.num % r.num); }; // XBoolean ////////////////////////////////////////////////////////////////// XBoolean.prototype = new Expression(); XBoolean.prototype.constructor = XBoolean; XBoolean.superclass = Expression.prototype; function XBoolean(b) { if (arguments.length > 0) { this.init(b); } } XBoolean.prototype.init = function (b) { this.b = Boolean(b); }; XBoolean.prototype.toString = function () { return this.b.toString(); }; XBoolean.prototype.evaluate = function (c) { return this; }; XBoolean.prototype.string = function () { return new XString(this.b); }; XBoolean.prototype.number = function () { return new XNumber(this.b); }; XBoolean.prototype.bool = function () { return this; }; XBoolean.prototype.nodeset = function () { throw new Error("Cannot convert boolean to nodeset"); }; XBoolean.prototype.stringValue = function () { return this.string().stringValue(); }; XBoolean.prototype.numberValue = function () { return this.number().numberValue(); }; XBoolean.prototype.booleanValue = function () { return this.b; }; XBoolean.prototype.not = function () { return new XBoolean(!this.b); }; XBoolean.prototype.equals = function (r) { if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { return this.equals(r.bool()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithBoolean(this, Operators.equals); } return new XBoolean(this.b == r.b); }; XBoolean.prototype.notequal = function (r) { if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { return this.notequal(r.bool()); } if (Utilities.instance_of(r, XNodeSet)) { return r.compareWithBoolean(this, Operators.notequal); } return new XBoolean(this.b != r.b); }; XBoolean.prototype.lessthan = function (r) { return this.number().lessthan(r); }; XBoolean.prototype.greaterthan = function (r) { return this.number().greaterthan(r); }; XBoolean.prototype.lessthanorequal = function (r) { return this.number().lessthanorequal(r); }; XBoolean.prototype.greaterthanorequal = function (r) { return this.number().greaterthanorequal(r); }; XBoolean.true_ = new XBoolean(true); XBoolean.false_ = new XBoolean(false); // AVLTree /////////////////////////////////////////////////////////////////// AVLTree.prototype = new Object(); AVLTree.prototype.constructor = AVLTree; AVLTree.superclass = Object.prototype; function AVLTree(n) { this.init(n); } AVLTree.prototype.init = function (n) { this.left = null; this.right = null; this.node = n; this.depth = 1; }; AVLTree.prototype.balance = function () { var ldepth = this.left == null ? 0 : this.left.depth; var rdepth = this.right == null ? 0 : this.right.depth; if (ldepth > rdepth + 1) { // LR or LL rotation var lldepth = this.left.left == null ? 0 : this.left.left.depth; var lrdepth = this.left.right == null ? 0 : this.left.right.depth; if (lldepth < lrdepth) { // LR rotation consists of a RR rotation of the left child this.left.rotateRR(); // plus a LL rotation of this node, which happens anyway } this.rotateLL(); } else if (ldepth + 1 < rdepth) { // RR or RL rorarion var rrdepth = this.right.right == null ? 0 : this.right.right.depth; var rldepth = this.right.left == null ? 0 : this.right.left.depth; if (rldepth > rrdepth) { // RR rotation consists of a LL rotation of the right child this.right.rotateLL(); // plus a RR rotation of this node, which happens anyway } this.rotateRR(); } }; AVLTree.prototype.rotateLL = function () { // the left side is too long => rotate from the left (_not_ leftwards) var nodeBefore = this.node; var rightBefore = this.right; this.node = this.left.node; this.right = this.left; this.left = this.left.left; this.right.left = this.right.right; this.right.right = rightBefore; this.right.node = nodeBefore; this.right.updateInNewLocation(); this.updateInNewLocation(); }; AVLTree.prototype.rotateRR = function () { // the right side is too long => rotate from the right (_not_ rightwards) var nodeBefore = this.node; var leftBefore = this.left; this.node = this.right.node; this.left = this.right; this.right = this.right.right; this.left.right = this.left.left; this.left.left = leftBefore; this.left.node = nodeBefore; this.left.updateInNewLocation(); this.updateInNewLocation(); }; AVLTree.prototype.updateInNewLocation = function () { this.getDepthFromChildren(); }; AVLTree.prototype.getDepthFromChildren = function () { this.depth = this.node == null ? 0 : 1; if (this.left != null) { this.depth = this.left.depth + 1; } if (this.right != null && this.depth <= this.right.depth) { this.depth = this.right.depth + 1; } }; function nodeOrder(n1, n2) { if (n1 === n2) { return 0; } if (n1.compareDocumentPosition) { var cpos = n1.compareDocumentPosition(n2); if (cpos & 0x01) { // not in the same document; return an arbitrary result (is there a better way to do this) return 1; } if (cpos & 0x0A) { // n2 precedes or contains n1 return 1; } if (cpos & 0x14) { // n2 follows or is contained by n1 return -1; } return 0; } var d1 = 0, d2 = 0; for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) { d1++; } for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) { d2++; } // step up to same depth if (d1 > d2) { while (d1 > d2) { n1 = n1.parentNode || n1.ownerElement; d1--; } if (n1 === n2) { return 1; } } else if (d2 > d1) { while (d2 > d1) { n2 = n2.parentNode || n2.ownerElement; d2--; } if (n1 === n2) { return -1; } } var n1Par = n1.parentNode || n1.ownerElement, n2Par = n2.parentNode || n2.ownerElement; // find common parent while (n1Par !== n2Par) { n1 = n1Par; n2 = n2Par; n1Par = n1.parentNode || n1.ownerElement; n2Par = n2.parentNode || n2.ownerElement; } var n1isAttr = isAttributeLike(n1); var n2isAttr = isAttributeLike(n2); if (n1isAttr && !n2isAttr) { return -1; } if (!n1isAttr && n2isAttr) { return 1; } // xml namespace node comes before others. namespace nodes before non-namespace nodes if (n1.isXPathNamespace) { if (n1.nodeValue === XPath.XML_NAMESPACE_URI) { return -1; } if (!n2.isXPathNamespace) { return -1; } if (n2.nodeValue === XPath.XML_NAMESPACE_URI) { return 1; } } else if (n2.isXPathNamespace) { return 1; } if (n1Par) { var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes; var len = cn.length; var n1Compare = n1.baseNode || n1; var n2Compare = n2.baseNode || n2; for (var i = 0; i < len; i += 1) { var n = cn[i]; if (n === n1Compare) { return -1; } if (n === n2Compare) { return 1; } } } throw new Error('Unexpected: could not determine node order'); } AVLTree.prototype.add = function (n) { if (n === this.node) { return false; } var o = nodeOrder(n, this.node); var ret = false; if (o == -1) { if (this.left == null) { this.left = new AVLTree(n); ret = true; } else { ret = this.left.add(n); if (ret) { this.balance(); } } } else if (o == 1) { if (this.right == null) { this.right = new AVLTree(n); ret = true; } else { ret = this.right.add(n); if (ret) { this.balance(); } } } if (ret) { this.getDepthFromChildren(); } return ret; }; // XNodeSet ////////////////////////////////////////////////////////////////// XNodeSet.prototype = new Expression(); XNodeSet.prototype.constructor = XNodeSet; XNodeSet.superclass = Expression.prototype; function XNodeSet() { this.init(); } XNodeSet.prototype.init = function () { this.tree = null; this.nodes = []; this.size = 0; }; XNodeSet.prototype.toString = function () { var p = this.first(); if (p == null) { return ""; } return this.stringForNode(p); }; XNodeSet.prototype.evaluate = function (c) { return this; }; XNodeSet.prototype.string = function () { return new XString(this.toString()); }; XNodeSet.prototype.stringValue = function () { return this.toString(); }; XNodeSet.prototype.number = function () { return new XNumber(this.string()); }; XNodeSet.prototype.numberValue = function () { return Number(this.string()); }; XNodeSet.prototype.bool = function () { return new XBoolean(this.booleanValue()); }; XNodeSet.prototype.booleanValue = function () { return !!this.size; }; XNodeSet.prototype.nodeset = function () { return this; }; XNodeSet.prototype.stringForNode = function (n) { if (n.nodeType == NodeTypes.DOCUMENT_NODE || n.nodeType == NodeTypes.ELEMENT_NODE || n.nodeType === NodeTypes.DOCUMENT_FRAGMENT_NODE) { return this.stringForContainerNode(n); } if (n.nodeType === NodeTypes.ATTRIBUTE_NODE) { return n.value || n.nodeValue; } if (n.isNamespaceNode) { return n.namespace; } return n.nodeValue; }; XNodeSet.prototype.stringForContainerNode = function (n) { var s = ""; for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) { var nt = n2.nodeType; // Element, Text, CDATA, Document, Document Fragment if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) { s += this.stringForNode(n2); } } return s; }; XNodeSet.prototype.buildTree = function () { if (!this.tree && this.nodes.length) { this.tree = new AVLTree(this.nodes[0]); for (var i = 1; i < this.nodes.length; i += 1) { this.tree.add(this.nodes[i]); } } return this.tree; }; XNodeSet.prototype.first = function () { var p = this.buildTree(); if (p == null) { return null; } while (p.left != null) { p = p.left; } return p.node; }; XNodeSet.prototype.add = function (n) { for (var i = 0; i < this.nodes.length; i += 1) { if (n === this.nodes[i]) { return; } } this.tree = null; this.nodes.push(n); this.size += 1; }; XNodeSet.prototype.addArray = function (ns) { var self = this; forEach(function (x) { self.add(x); }, ns); }; /** * Returns an array of the node set's contents in document order */ XNodeSet.prototype.toArray = function () { var a = []; this.toArrayRec(this.buildTree(), a); return a; }; XNodeSet.prototype.toArrayRec = function (t, a) { if (t != null) { this.toArrayRec(t.left, a); a.push(t.node); this.toArrayRec(t.right, a); } }; /** * Returns an array of the node set's contents in arbitrary order */ XNodeSet.prototype.toUnsortedArray = function () { return this.nodes.slice(); }; XNodeSet.prototype.compareWithString = function (r, o) { var a = this.toUnsortedArray(); for (var i = 0; i < a.length; i++) { var n = a[i]; var l = new XString(this.stringForNode(n)); var res = o(l, r); if (res.booleanValue()) { return res; } } return new XBoolean(false); }; XNodeSet.prototype.compareWithNumber = function (r, o) { var a = this.toUnsortedArray(); for (var i = 0; i < a.length; i++) { var n = a[i]; var l = new XNumber(this.stringForNode(n)); var res = o(l, r); if (res.booleanValue()) { return res; } } return new XBoolean(false); }; XNodeSet.prototype.compareWithBoolean = function (r, o) { return o(this.bool(), r); }; XNodeSet.prototype.compareWithNodeSet = function (r, o) { var arr = this.toUnsortedArray(); var oInvert = function (lop, rop) { return o(rop, lop); }; for (var i = 0; i < arr.length; i++) { var l = new XString(this.stringForNode(arr[i])); var res = r.compareWithString(l, oInvert); if (res.booleanValue()) { return res; } } return new XBoolean(false); }; XNodeSet.compareWith = curry(function (o, r) { if (Utilities.instance_of(r, XString)) { return this.compareWithString(r, o); } if (Utilities.instance_of(r, XNumber)) { return this.compareWithNumber(r, o); } if (Utilities.instance_of(r, XBoolean)) { return this.compareWithBoolean(r, o); } return this.compareWithNodeSet(r, o); }); XNodeSet.prototype.equals = XNodeSet.compareWith(Operators.equals); XNodeSet.prototype.notequal = XNodeSet.compareWith(Operators.notequal); XNodeSet.prototype.lessthan = XNodeSet.compareWith(Operators.lessthan); XNodeSet.prototype.greaterthan = XNodeSet.compareWith(Operators.greaterthan); XNodeSet.prototype.lessthanorequal = XNodeSet.compareWith(Operators.lessthanorequal); XNodeSet.prototype.greaterthanorequal = XNodeSet.compareWith(Operators.greaterthanorequal); XNodeSet.prototype.union = function (r) { var ns = new XNodeSet(); ns.addArray(this.toUnsortedArray()); ns.addArray(r.toUnsortedArray()); return ns; }; // XPathNamespace //////////////////////////////////////////////////////////// XPathNamespace.prototype = new Object(); XPathNamespace.prototype.constructor = XPathNamespace; XPathNamespace.superclass = Object.prototype; function XPathNamespace(pre, node, uri, p) { this.isXPathNamespace = true; this.baseNode = node; this.ownerDocument = p.ownerDocument; this.nodeName = pre; this.prefix = pre; this.localName = pre; this.namespaceURI = null; this.nodeValue = uri; this.ownerElement = p; this.nodeType = NodeTypes.NAMESPACE_NODE; } XPathNamespace.prototype.toString = function () { return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }"; }; // XPathContext ////////////////////////////////////////////////////////////// XPathContext.prototype = new Object(); XPathContext.prototype.constructor = XPathContext; XPathContext.superclass = Object.prototype; function XPathContext(vr, nr, fr) { this.variableResolver = vr != null ? vr : new VariableResolver(); this.namespaceResolver = nr != null ? nr : new NamespaceResolver(); this.functionResolver = fr != null ? fr : new FunctionResolver(); } XPathContext.prototype.extend = function (newProps) { return assign(new XPathContext(), this, newProps); }; // VariableResolver ////////////////////////////////////////////////////////// VariableResolver.prototype = new Object(); VariableResolver.prototype.constructor = VariableResolver; VariableResolver.superclass = Object.prototype; function VariableResolver() { } VariableResolver.prototype.getVariable = function (ln, ns) { return null; }; // FunctionResolver ////////////////////////////////////////////////////////// FunctionResolver.prototype = new Object(); FunctionResolver.prototype.constructor = FunctionResolver; FunctionResolver.superclass = Object.prototype; function FunctionResolver(thisArg) { this.thisArg = thisArg != null ? thisArg : Functions; this.functions = new Object(); this.addStandardFunctions(); } FunctionResolver.prototype.addStandardFunctions = function () { this.functions["{}last"] = Functions.last; this.functions["{}position"] = Functions.position; this.functions["{}count"] = Functions.count; this.functions["{}id"] = Functions.id; this.functions["{}local-name"] = Functions.localName; this.functions["{}namespace-uri"] = Functions.namespaceURI; this.functions["{}name"] = Functions.name; this.functions["{}string"] = Functions.string; this.functions["{}concat"] = Functions.concat; this.functions["{}starts-with"] = Functions.startsWith; this.functions["{}contains"] = Functions.contains; this.functions["{}substring-before"] = Functions.substringBefore; this.functions["{}substring-after"] = Functions.substringAfter; this.functions["{}substring"] = Functions.substring; this.functions["{}string-length"] = Functions.stringLength; this.functions["{}normalize-space"] = Functions.normalizeSpace; this.functions["{}translate"] = Functions.translate; this.functions["{}boolean"] = Functions.boolean_; this.functions["{}not"] = Functions.not; this.functions["{}true"] = Functions.true_; this.functions["{}false"] = Functions.false_; this.functions["{}lang"] = Functions.lang; this.functions["{}number"] = Functions.number; this.functions["{}sum"] = Functions.sum; this.functions["{}floor"] = Functions.floor; this.functions["{}ceiling"] = Functions.ceiling; this.functions["{}round"] = Functions.round; }; FunctionResolver.prototype.addFunction = function (ns, ln, f) { this.functions["{" + ns + "}" + ln] = f; }; FunctionResolver.getFunctionFromContext = function (qName, context) { var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false); if (parts[0] === null) { throw new Error("Cannot resolve QName " + name); } return context.functionResolver.getFunction(parts[1], parts[0]); }; FunctionResolver.prototype.getFunction = function (localName, namespace) { return this.functions["{" + namespace + "}" + localName]; }; // NamespaceResolver ///////////////////////////////////////////////////////// NamespaceResolver.prototype = new Object(); NamespaceResolver.prototype.constructor = NamespaceResolver; NamespaceResolver.superclass = Object.prototype; function NamespaceResolver() { } NamespaceResolver.prototype.getNamespace = function (prefix, n) { if (prefix == "xml") { return XPath.XML_NAMESPACE_URI; } else if (prefix == "xmlns") { return XPath.XMLNS_NAMESPACE_URI; } if (n.nodeType == NodeTypes.DOCUMENT_NODE) { n = n.documentElement; } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) { n = PathExpr.getOwnerElement(n); } else if (n.nodeType != NodeTypes.ELEMENT_NODE) { n = n.parentNode; } while (n != null && n.nodeType == NodeTypes.ELEMENT_NODE) { var nnm = n.attributes; for (var i = 0; i < nnm.length; i++) { var a = nnm.item(i); var aname = a.name || a.nodeName; if ((aname === "xmlns" && prefix === "") || aname === "xmlns:" + prefix) { return String(a.value || a.nodeValue); } } n = n.parentNode; } return null; }; // Functions ///////////////////////////////////////////////////////////////// var Functions = new Object(); Functions.last = function (c) { if (arguments.length != 1) { throw new Error("Function last expects ()"); } return new XNumber(c.contextSize); }; Functions.position = function (c) { if (arguments.length != 1) { throw new Error("Function position expects ()"); } return new XNumber(c.contextPosition); }; Functions.count = function () { var c = arguments[0]; var ns; if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) { throw new Error("Function count expects (node-set)"); } return new XNumber(ns.size); }; Functions.id = function () { var c = arguments[0]; var id; if (arguments.length != 2) { throw new Error("Function id expects (object)"); } id = arguments[1].evaluate(c); if (Utilities.instance_of(id, XNodeSet)) { id = id.toArray().join(" "); } else { id = id.stringValue(); } var ids = id.split(/[\x0d\x0a\x09\x20]+/); var count = 0; var ns = new XNodeSet(); var doc = c.contextNode.nodeType == NodeTypes.DOCUMENT_NODE ? c.contextNode : c.contextNode.ownerDocument; for (var i = 0; i < ids.length; i++) { var n; if (doc.getElementById) { n = doc.getElementById(ids[i]); } else { n = Utilities.getElementById(doc, ids[i]); } if (n != null) { ns.add(n); count++; } } return ns; }; Functions.localName = function (c, eNode) { var n; if (arguments.length == 1) { n = c.contextNode; } else if (arguments.length == 2) { n = eNode.evaluate(c).first(); } else { throw new Error("Function local-name expects (node-set?)"); } if (n == null) { return new XString(""); } return new XString( n.localName || // standard elements and attributes n.baseName || // IE n.target || // processing instructions n.nodeName || // DOM1 elements "" // fallback ); }; Functions.namespaceURI = function () { var c = arguments[0]; var n; if (arguments.length == 1) { n = c.contextNode; } else if (arguments.length == 2) { n = arguments[1].evaluate(c).first(); } else { throw new Error("Function namespace-uri expects (node-set?)"); } if (n == null) { return new XString(""); } return new XString(n.namespaceURI || ''); }; Functions.name = function () { var c = arguments[0]; var n; if (arguments.length == 1) { n = c.contextNode; } else if (arguments.length == 2) { n = arguments[1].evaluate(c).first(); } else { throw new Error("Function name expects (node-set?)"); } if (n == null) { return new XString(""); } if (n.nodeType == NodeTypes.ELEMENT_NODE) { return new XString(n.nodeName); } else if (n.nodeType == NodeTypes.ATTRIBUTE_NODE) { return new XString(n.name || n.nodeName); } else if (n.nodeType === NodeTypes.PROCESSING_INSTRUCTION_NODE) { return new XString(n.target || n.nodeName); } else if (n.localName == null) { return new XString(""); } else { return new XString(n.localName); } }; Functions.string = function () { var c = arguments[0]; if (arguments.length == 1) { return new XString(XNodeSet.prototype.stringForNode(c.contextNode)); } else if (arguments.length == 2) { return arguments[1].evaluate(c).string(); } throw new Error("Function string expects (object?)"); }; Functions.concat = function (c) { if (arguments.length < 3) { throw new Error("Function concat expects (string, string[, string]*)"); } var s = ""; for (var i = 1; i < arguments.length; i++) { s += arguments[i].evaluate(c).stringValue(); } return new XString(s); }; Functions.startsWith = function () { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function startsWith expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); return new XBoolean(s1.substring(0, s2.length) == s2); }; Functions.contains = function () { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function contains expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); return new XBoolean(s1.indexOf(s2) !== -1); }; Functions.substringBefore = function () { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function substring-before expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); return new XString(s1.substring(0, s1.indexOf(s2))); }; Functions.substringAfter = function () { var c = arguments[0]; if (arguments.length != 3) { throw new Error("Function substring-after expects (string, string)"); } var s1 = arguments[1].evaluate(c).stringValue(); var s2 = arguments[2].evaluate(c).stringValue(); if (s2.length == 0) { return new XString(s1); } var i = s1.indexOf(s2); if (i == -1) { return new XString(""); } return new XString(s1.substring(i + s2.length)); }; Functions.substring = function () { var c = arguments[0]; if (!(arguments.length == 3 || arguments.length == 4)) { throw new Error("Function substring expects (string, number, number?)"); } var s = arguments[1].evaluate(c).stringValue(); var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1; var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined; return new XString(s.substring(n1, n2)); }; Functions.stringLength = function () { var c = arguments[0]; var s; if (arguments.length == 1) { s = XNodeSet.prototype.stringForNode(c.contextNode); } else if (arguments.length == 2) { s = arguments[1].evaluate(c).stringValue(); } else { throw new Error("Function string-length expects (string?)"); } return new XNumber(s.length); }; Functions.normalizeSpace = function () { var c = arguments[0]; var s; if (arguments.length == 1) { s = XNodeSet.prototype.stringForNode(c.contextNode); } else if (arguments.length == 2) { s = arguments[1].evaluate(c).stringValue(); } else { throw new Error("Function normalize-space expects (string?)"); } var i = 0; var j = s.length - 1; while (Utilities.isSpace(s.charCodeAt(j))) { j--; } var t = ""; while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { i++; } while (i <= j) { if (Utilities.isSpace(s.charCodeAt(i))) { t += " "; while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { i++; } } else { t += s.charAt(i); i++; } } return new XString(t); }; Functions.translate = function (c, eValue, eFrom, eTo) { if (arguments.length != 4) { throw new Error("Function translate expects (string, string, string)"); } var value = eValue.evaluate(c).stringValue(); var from = eFrom.evaluate(c).stringValue(); var to = eTo.evaluate(c).stringValue(); var cMap = reduce(function (acc, ch, i) { if (!(ch in acc)) { acc[ch] = i > to.length ? '' : to[i]; } return acc; }, {}, from); var t = join( '', map(function (ch) { return ch in cMap ? cMap[ch] : ch; }, value) ); return new XString(t); }; Functions.boolean_ = function () { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function boolean expects (object)"); } return arguments[1].evaluate(c).bool(); }; Functions.not = function (c, eValue) { if (arguments.length != 2) { throw new Error("Function not expects (object)"); } return eValue.evaluate(c).bool().not(); }; Functions.true_ = function () { if (arguments.length != 1) { throw new Error("Function true expects ()"); } return XBoolean.true_; }; Functions.false_ = function () { if (arguments.length != 1) { throw new Error("Function false expects ()"); } return XBoolean.false_; }; Functions.lang = function () { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function lang expects (string)"); } var lang; for (var n = c.contextNode; n != null && n.nodeType != NodeTypes.DOCUMENT_NODE; n = n.parentNode) { var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang"); if (a != null) { lang = String(a); break; } } if (lang == null) { return XBoolean.false_; } var s = arguments[1].evaluate(c).stringValue(); return new XBoolean(lang.substring(0, s.length) == s && (lang.length == s.length || lang.charAt(s.length) == '-')); }; Functions.number = function () { var c = arguments[0]; if (!(arguments.length == 1 || arguments.length == 2)) { throw new Error("Function number expects (object?)"); } if (arguments.length == 1) { return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode)); } return arguments[1].evaluate(c).number(); }; Functions.sum = function () { var c = arguments[0]; var ns; if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) { throw new Error("Function sum expects (node-set)"); } ns = ns.toUnsortedArray(); var n = 0; for (var i = 0; i < ns.length; i++) { n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue(); } return new XNumber(n); }; Functions.floor = function () { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function floor expects (number)"); } return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue())); }; Functions.ceiling = function () { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function ceiling expects (number)"); } return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue())); }; Functions.round = function () { var c = arguments[0]; if (arguments.length != 2) { throw new Error("Function round expects (number)"); } return new XNumber(Math.round(arguments[1].evaluate(c).numberValue())); }; // Utilities ///////////////////////////////////////////////////////////////// var Utilities = new Object(); // Returns true if the node is an attribute node or namespace node var isAttributeLike = function (val) { return val && ( val.nodeType === NodeTypes.ATTRIBUTE_NODE || val.ownerElement || val.isXPathNamespace ); } Utilities.splitQName = function (qn) { var i = qn.indexOf(":"); if (i == -1) { return [null, qn]; } return [qn.substring(0, i), qn.substring(i + 1)]; }; Utilities.resolveQName = function (qn, nr, n, useDefault) { var parts = Utilities.splitQName(qn); if (parts[0] != null) { parts[0] = nr.getNamespace(parts[0], n); } else { if (useDefault) { parts[0] = nr.getNamespace("", n); if (parts[0] == null) { parts[0] = ""; } } else { parts[0] = ""; } } return parts; }; Utilities.isSpace = function (c) { return c == 0x9 || c == 0xd || c == 0xa || c == 0x20; }; Utilities.isLetter = function (c) { return c >= 0x0041 && c <= 0x005A || c >= 0x0061 && c <= 0x007A || c >= 0x00C0 && c <= 0x00D6 || c >= 0x00D8 && c <= 0x00F6 || c >= 0x00F8 && c <= 0x00FF || c >= 0x0100 && c <= 0x0131 || c >= 0x0134 && c <= 0x013E || c >= 0x0141 && c <= 0x0148 || c >= 0x014A && c <= 0x017E || c >= 0x0180 && c <= 0x01C3 || c >= 0x01CD && c <= 0x01F0 || c >= 0x01F4 && c <= 0x01F5 || c >= 0x01FA && c <= 0x0217 || c >= 0x0250 && c <= 0x02A8 || c >= 0x02BB && c <= 0x02C1 || c == 0x0386 || c >= 0x0388 && c <= 0x038A || c == 0x038C || c >= 0x038E && c <= 0x03A1 || c >= 0x03A3 && c <= 0x03CE || c >= 0x03D0 && c <= 0x03D6 || c == 0x03DA || c == 0x03DC || c == 0x03DE || c == 0x03E0 || c >= 0x03E2 && c <= 0x03F3 || c >= 0x0401 && c <= 0x040C || c >= 0x040E && c <= 0x044F || c >= 0x0451 && c <= 0x045C || c >= 0x045E && c <= 0x0481 || c >= 0x0490 && c <= 0x04C4 || c >= 0x04C7 && c <= 0x04C8 || c >= 0x04CB && c <= 0x04CC || c >= 0x04D0 && c <= 0x04EB || c >= 0x04EE && c <= 0x04F5 || c >= 0x04F8 && c <= 0x04F9 || c >= 0x0531 && c <= 0x0556 || c == 0x0559 || c >= 0x0561 && c <= 0x0586 || c >= 0x05D0 && c <= 0x05EA || c >= 0x05F0 && c <= 0x05F2 || c >= 0x0621 && c <= 0x063A || c >= 0x0641 && c <= 0x064A || c >= 0x0671 && c <= 0x06B7 || c >= 0x06BA && c <= 0x06BE || c >= 0x06C0 && c <= 0x06CE || c >= 0x06D0 && c <= 0x06D3 || c == 0x06D5 || c >= 0x06E5 && c <= 0x06E6 || c >= 0x0905 && c <= 0x0939 || c == 0x093D || c >= 0x0958 && c <= 0x0961 || c >= 0x0985 && c <= 0x098C || c >= 0x098F && c <= 0x0990 || c >= 0x0993 && c <= 0x09A8 || c >= 0x09AA && c <= 0x09B0 || c == 0x09B2 || c >= 0x09B6 && c <= 0x09B9 || c >= 0x09DC && c <= 0x09DD || c >= 0x09DF && c <= 0x09E1 || c >= 0x09F0 && c <= 0x09F1 || c >= 0x0A05 && c <= 0x0A0A || c >= 0x0A0F && c <= 0x0A10 || c >= 0x0A13 && c <= 0x0A28 || c >= 0x0A2A && c <= 0x0A30 || c >= 0x0A32 && c <= 0x0A33 || c >= 0x0A35 && c <= 0x0A36 || c >= 0x0A38 && c <= 0x0A39 || c >= 0x0A59 && c <= 0x0A5C || c == 0x0A5E || c >= 0x0A72 && c <= 0x0A74 || c >= 0x0A85 && c <= 0x0A8B || c == 0x0A8D || c >= 0x0A8F && c <= 0x0A91 || c >= 0x0A93 && c <= 0x0AA8 || c >= 0x0AAA && c <= 0x0AB0 || c >= 0x0AB2 && c <= 0x0AB3 || c >= 0x0AB5 && c <= 0x0AB9 || c == 0x0ABD || c == 0x0AE0 || c >= 0x0B05 && c <= 0x0B0C || c >= 0x0B0F && c <= 0x0B10 || c >= 0x0B13 && c <= 0x0B28 || c >= 0x0B2A && c <= 0x0B30 || c >= 0x0B32 && c <= 0x0B33 || c >= 0x0B36 && c <= 0x0B39 || c == 0x0B3D || c >= 0x0B5C && c <= 0x0B5D || c >= 0x0B5F && c <= 0x0B61 || c >= 0x0B85 && c <= 0x0B8A || c >= 0x0B8E && c <= 0x0B90 || c >= 0x0B92 && c <= 0x0B95 || c >= 0x0B99 && c <= 0x0B9A || c == 0x0B9C || c >= 0x0B9E && c <= 0x0B9F || c >= 0x0BA3 && c <= 0x0BA4 || c >= 0x0BA8 && c <= 0x0BAA || c >= 0x0BAE && c <= 0x0BB5 || c >= 0x0BB7 && c <= 0x0BB9 || c >= 0x0C05 && c <= 0x0C0C || c >= 0x0C0E && c <= 0x0C10 || c >= 0x0C12 && c <= 0x0C28 || c >= 0x0C2A && c <= 0x0C33 || c >= 0x0C35 && c <= 0x0C39 || c >= 0x0C60 && c <= 0x0C61 || c >= 0x0C85 && c <= 0x0C8C || c >= 0x0C8E && c <= 0x0C90 || c >= 0x0C92 && c <= 0x0CA8 || c >= 0x0CAA && c <= 0x0CB3 || c >= 0x0CB5 && c <= 0x0CB9 || c == 0x0CDE || c >= 0x0CE0 && c <= 0x0CE1 || c >= 0x0D05 && c <= 0x0D0C || c >= 0x0D0E && c <= 0x0D10 || c >= 0x0D12 && c <= 0x0D28 || c >= 0x0D2A && c <= 0x0D39 || c >= 0x0D60 && c <= 0x0D61 || c >= 0x0E01 && c <= 0x0E2E || c == 0x0E30 || c >= 0x0E32 && c <= 0x0E33 || c >= 0x0E40 && c <= 0x0E45 || c >= 0x0E81 && c <= 0x0E82 || c == 0x0E84 || c >= 0x0E87 && c <= 0x0E88 || c == 0x0E8A || c == 0x0E8D || c >= 0x0E94 && c <= 0x0E97 || c >= 0x0E99 && c <= 0x0E9F || c >= 0x0EA1 && c <= 0x0EA3 || c == 0x0EA5 || c == 0x0EA7 || c >= 0x0EAA && c <= 0x0EAB || c >= 0x0EAD && c <= 0x0EAE || c == 0x0EB0 || c >= 0x0EB2 && c <= 0x0EB3 || c == 0x0EBD || c >= 0x0EC0 && c <= 0x0EC4 || c >= 0x0F40 && c <= 0x0F47 || c >= 0x0F49 && c <= 0x0F69 || c >= 0x10A0 && c <= 0x10C5 || c >= 0x10D0 && c <= 0x10F6 || c == 0x1100 || c >= 0x1102 && c <= 0x1103 || c >= 0x1105 && c <= 0x1107 || c == 0x1109 || c >= 0x110B && c <= 0x110C || c >= 0x110E && c <= 0x1112 || c == 0x113C || c == 0x113E || c == 0x1140 || c == 0x114C || c == 0x114E || c == 0x1150 || c >= 0x1154 && c <= 0x1155 || c == 0x1159 || c >= 0x115F && c <= 0x1161 || c == 0x1163 || c == 0x1165 || c == 0x1167 || c == 0x1169 || c >= 0x116D && c <= 0x116E || c >= 0x1172 && c <= 0x1173 || c == 0x1175 || c == 0x119E || c == 0x11A8 || c == 0x11AB || c >= 0x11AE && c <= 0x11AF || c >= 0x11B7 && c <= 0x11B8 || c == 0x11BA || c >= 0x11BC && c <= 0x11C2 || c == 0x11EB || c == 0x11F0 || c == 0x11F9 || c >= 0x1E00 && c <= 0x1E9B || c >= 0x1EA0 && c <= 0x1EF9 || c >= 0x1F00 && c <= 0x1F15 || c >= 0x1F18 && c <= 0x1F1D || c >= 0x1F20 && c <= 0x1F45 || c >= 0x1F48 && c <= 0x1F4D || c >= 0x1F50 && c <= 0x1F57 || c == 0x1F59 || c == 0x1F5B || c == 0x1F5D || c >= 0x1F5F && c <= 0x1F7D || c >= 0x1F80 && c <= 0x1FB4 || c >= 0x1FB6 && c <= 0x1FBC || c == 0x1FBE || c >= 0x1FC2 && c <= 0x1FC4 || c >= 0x1FC6 && c <= 0x1FCC || c >= 0x1FD0 && c <= 0x1FD3 || c >= 0x1FD6 && c <= 0x1FDB || c >= 0x1FE0 && c <= 0x1FEC || c >= 0x1FF2 && c <= 0x1FF4 || c >= 0x1FF6 && c <= 0x1FFC || c == 0x2126 || c >= 0x212A && c <= 0x212B || c == 0x212E || c >= 0x2180 && c <= 0x2182 || c >= 0x3041 && c <= 0x3094 || c >= 0x30A1 && c <= 0x30FA || c >= 0x3105 && c <= 0x312C || c >= 0xAC00 && c <= 0xD7A3 || c >= 0x4E00 && c <= 0x9FA5 || c == 0x3007 || c >= 0x3021 && c <= 0x3029; }; Utilities.isNCNameChar = function (c) { return c >= 0x0030 && c <= 0x0039 || c >= 0x0660 && c <= 0x0669 || c >= 0x06F0 && c <= 0x06F9 || c >= 0x0966 && c <= 0x096F || c >= 0x09E6 && c <= 0x09EF || c >= 0x0A66 && c <= 0x0A6F || c >= 0x0AE6 && c <= 0x0AEF || c >= 0x0B66 && c <= 0x0B6F || c >= 0x0BE7 && c <= 0x0BEF || c >= 0x0C66 && c <= 0x0C6F || c >= 0x0CE6 && c <= 0x0CEF || c >= 0x0D66 && c <= 0x0D6F || c >= 0x0E50 && c <= 0x0E59 || c >= 0x0ED0 && c <= 0x0ED9 || c >= 0x0F20 && c <= 0x0F29 || c == 0x002E || c == 0x002D || c == 0x005F || Utilities.isLetter(c) || c >= 0x0300 && c <= 0x0345 || c >= 0x0360 && c <= 0x0361 || c >= 0x0483 && c <= 0x0486 || c >= 0x0591 && c <= 0x05A1 || c >= 0x05A3 && c <= 0x05B9 || c >= 0x05BB && c <= 0x05BD || c == 0x05BF || c >= 0x05C1 && c <= 0x05C2 || c == 0x05C4 || c >= 0x064B && c <= 0x0652 || c == 0x0670 || c >= 0x06D6 && c <= 0x06DC || c >= 0x06DD && c <= 0x06DF || c >= 0x06E0 && c <= 0x06E4 || c >= 0x06E7 && c <= 0x06E8 || c >= 0x06EA && c <= 0x06ED || c >= 0x0901 && c <= 0x0903 || c == 0x093C || c >= 0x093E && c <= 0x094C || c == 0x094D || c >= 0x0951 && c <= 0x0954 || c >= 0x0962 && c <= 0x0963 || c >= 0x0981 && c <= 0x0983 || c == 0x09BC || c == 0x09BE || c == 0x09BF || c >= 0x09C0 && c <= 0x09C4 || c >= 0x09C7 && c <= 0x09C8 || c >= 0x09CB && c <= 0x09CD || c == 0x09D7 || c >= 0x09E2 && c <= 0x09E3 || c == 0x0A02 || c == 0x0A3C || c == 0x0A3E || c == 0x0A3F || c >= 0x0A40 && c <= 0x0A42 || c >= 0x0A47 && c <= 0x0A48 || c >= 0x0A4B && c <= 0x0A4D || c >= 0x0A70 && c <= 0x0A71 || c >= 0x0A81 && c <= 0x0A83 || c == 0x0ABC || c >= 0x0ABE && c <= 0x0AC5 || c >= 0x0AC7 && c <= 0x0AC9 || c >= 0x0ACB && c <= 0x0ACD || c >= 0x0B01 && c <= 0x0B03 || c == 0x0B3C || c >= 0x0B3E && c <= 0x0B43 || c >= 0x0B47 && c <= 0x0B48 || c >= 0x0B4B && c <= 0x0B4D || c >= 0x0B56 && c <= 0x0B57 || c >= 0x0B82 && c <= 0x0B83 || c >= 0x0BBE && c <= 0x0BC2 || c >= 0x0BC6 && c <= 0x0BC8 || c >= 0x0BCA && c <= 0x0BCD || c == 0x0BD7 || c >= 0x0C01 && c <= 0x0C03 || c >= 0x0C3E && c <= 0x0C44 || c >= 0x0C46 && c <= 0x0C48 || c >= 0x0C4A && c <= 0x0C4D || c >= 0x0C55 && c <= 0x0C56 || c >= 0x0C82 && c <= 0x0C83 || c >= 0x0CBE && c <= 0x0CC4 || c >= 0x0CC6 && c <= 0x0CC8 || c >= 0x0CCA && c <= 0x0CCD || c >= 0x0CD5 && c <= 0x0CD6 || c >= 0x0D02 && c <= 0x0D03 || c >= 0x0D3E && c <= 0x0D43 || c >= 0x0D46 && c <= 0x0D48 || c >= 0x0D4A && c <= 0x0D4D || c == 0x0D57 || c == 0x0E31 || c >= 0x0E34 && c <= 0x0E3A || c >= 0x0E47 && c <= 0x0E4E || c == 0x0EB1 || c >= 0x0EB4 && c <= 0x0EB9 || c >= 0x0EBB && c <= 0x0EBC || c >= 0x0EC8 && c <= 0x0ECD || c >= 0x0F18 && c <= 0x0F19 || c == 0x0F35 || c == 0x0F37 || c == 0x0F39 || c == 0x0F3E || c == 0x0F3F || c >= 0x0F71 && c <= 0x0F84 || c >= 0x0F86 && c <= 0x0F8B || c >= 0x0F90 && c <= 0x0F95 || c == 0x0F97 || c >= 0x0F99 && c <= 0x0FAD || c >= 0x0FB1 && c <= 0x0FB7 || c == 0x0FB9 || c >= 0x20D0 && c <= 0x20DC || c == 0x20E1 || c >= 0x302A && c <= 0x302F || c == 0x3099 || c == 0x309A || c == 0x00B7 || c == 0x02D0 || c == 0x02D1 || c == 0x0387 || c == 0x0640 || c == 0x0E46 || c == 0x0EC6 || c == 0x3005 || c >= 0x3031 && c <= 0x3035 || c >= 0x309D && c <= 0x309E || c >= 0x30FC && c <= 0x30FE; }; Utilities.coalesceText = function (n) { for (var m = n.firstChild; m != null; m = m.nextSibling) { if (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE) { var s = m.nodeValue; var first = m; m = m.nextSibling; while (m != null && (m.nodeType == NodeTypes.TEXT_NODE || m.nodeType == NodeTypes.CDATA_SECTION_NODE)) { s += m.nodeValue; var del = m; m = m.nextSibling; del.parentNode.removeChild(del); } if (first.nodeType == NodeTypes.CDATA_SECTION_NODE) { var p = first.parentNode; if (first.nextSibling == null) { p.removeChild(first); p.appendChild(p.ownerDocument.createTextNode(s)); } else { var next = first.nextSibling; p.removeChild(first); p.insertBefore(p.ownerDocument.createTextNode(s), next); } } else { first.nodeValue = s; } if (m == null) { break; } } else if (m.nodeType == NodeTypes.ELEMENT_NODE) { Utilities.coalesceText(m); } } }; Utilities.instance_of = function (o, c) { while (o != null) { if (o.constructor === c) { return true; } if (o === Object) { return false; } o = o.constructor.superclass; } return false; }; Utilities.getElementById = function (n, id) { // Note that this does not check the DTD to check for actual // attributes of type ID, so this may be a bit wrong. if (n.nodeType == NodeTypes.ELEMENT_NODE) { if (n.getAttribute("id") == id || n.getAttributeNS(null, "id") == id) { return n; } } for (var m = n.firstChild; m != null; m = m.nextSibling) { var res = Utilities.getElementById(m, id); if (res != null) { return res; } } return null; }; // XPathException //////////////////////////////////////////////////////////// var XPathException = (function () { function getMessage(code, exception) { var msg = exception ? ": " + exception.toString() : ""; switch (code) { case XPathException.INVALID_EXPRESSION_ERR: return "Invalid expression" + msg; case XPathException.TYPE_ERR: return "Type error" + msg; } return null; } function XPathException(code, error, message) { var err = Error.call(this, getMessage(code, error) || message); err.code = code; err.exception = error; return err; } XPathException.prototype = Object.create(Error.prototype); XPathException.prototype.constructor = XPathException; XPathException.superclass = Error; XPathException.prototype.toString = function () { return this.message; }; XPathException.fromMessage = function (message, error) { return new XPathException(null, error, message); }; XPathException.INVALID_EXPRESSION_ERR = 51; XPathException.TYPE_ERR = 52; return XPathException; })(); // XPathExpression /////////////////////////////////////////////////////////// XPathExpression.prototype = {}; XPathExpression.prototype.constructor = XPathExpression; XPathExpression.superclass = Object.prototype; function XPathExpression(e, r, p) { this.xpath = p.parse(e); this.context = new XPathContext(); this.context.namespaceResolver = new XPathNSResolverWrapper(r); } XPathExpression.getOwnerDocument = function (n) { return n.nodeType === NodeTypes.DOCUMENT_NODE ? n : n.ownerDocument; } XPathExpression.detectHtmlDom = function (n) { if (!n) { return false; } var doc = XPathExpression.getOwnerDocument(n); try { return doc.implementation.hasFeature("HTML", "2.0"); } catch (e) { return true; } } XPathExpression.prototype.evaluate = function (n, t, res) { this.context.expressionContextNode = n; // backward compatibility - no reliable way to detect whether the DOM is HTML, but // this library has been using this method up until now, so we will continue to use it // ONLY when using an XPathExpression this.context.caseInsensitive = XPathExpression.detectHtmlDom(n); var result = this.xpath.evaluate(this.context); return new XPathResult(result, t); } // XPathNSResolverWrapper //////////////////////////////////////////////////// XPathNSResolverWrapper.prototype = {}; XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper; XPathNSResolverWrapper.superclass = Object.prototype; function XPathNSResolverWrapper(r) { this.xpathNSResolver = r; } XPathNSResolverWrapper.prototype.getNamespace = function (prefix, n) { if (this.xpathNSResolver == null) { return null; } return this.xpathNSResolver.lookupNamespaceURI(prefix); }; // NodeXPathNSResolver /////////////////////////////////////////////////////// NodeXPathNSResolver.prototype = {}; NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver; NodeXPathNSResolver.superclass = Object.prototype; function NodeXPathNSResolver(n) { this.node = n; this.namespaceResolver = new NamespaceResolver(); } NodeXPathNSResolver.prototype.lookupNamespaceURI = function (prefix) { return this.namespaceResolver.getNamespace(prefix, this.node); }; // XPathResult /////////////////////////////////////////////////////////////// XPathResult.prototype = {}; XPathResult.prototype.constructor = XPathResult; XPathResult.superclass = Object.prototype; function XPathResult(v, t) { if (t == XPathResult.ANY_TYPE) { if (v.constructor === XString) { t = XPathResult.STRING_TYPE; } else if (v.constructor === XNumber) { t = XPathResult.NUMBER_TYPE; } else if (v.constructor === XBoolean) { t = XPathResult.BOOLEAN_TYPE; } else if (v.constructor === XNodeSet) { t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE; } } this.resultType = t; switch (t) { case XPathResult.NUMBER_TYPE: this.numberValue = v.numberValue(); return; case XPathResult.STRING_TYPE: this.stringValue = v.stringValue(); return; case XPathResult.BOOLEAN_TYPE: this.booleanValue = v.booleanValue(); return; case XPathResult.ANY_UNORDERED_NODE_TYPE: case XPathResult.FIRST_ORDERED_NODE_TYPE: if (v.constructor === XNodeSet) { this.singleNodeValue = v.first(); return; } break; case XPathResult.UNORDERED_NODE_ITERATOR_TYPE: case XPathResult.ORDERED_NODE_ITERATOR_TYPE: if (v.constructor === XNodeSet) { this.invalidIteratorState = false; this.nodes = v.toArray(); this.iteratorIndex = 0; return; } break; case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE: case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE: if (v.constructor === XNodeSet) { this.nodes = v.toArray(); this.snapshotLength = this.nodes.length; return; } break; } throw new XPathException(XPathException.TYPE_ERR); }; XPathResult.prototype.iterateNext = function () { if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE && this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) { throw new XPathException(XPathException.TYPE_ERR); } return this.nodes[this.iteratorIndex++]; }; XPathResult.prototype.snapshotItem = function (i) { if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE && this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) { throw new XPathException(XPathException.TYPE_ERR); } return this.nodes[i]; }; XPathResult.ANY_TYPE = 0; XPathResult.NUMBER_TYPE = 1; XPathResult.STRING_TYPE = 2; XPathResult.BOOLEAN_TYPE = 3; XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4; XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5; XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6; XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7; XPathResult.ANY_UNORDERED_NODE_TYPE = 8; XPathResult.FIRST_ORDERED_NODE_TYPE = 9; // DOM 3 XPath support /////////////////////////////////////////////////////// function installDOM3XPathSupport(doc, p) { doc.createExpression = function (e, r) { try { return new XPathExpression(e, r, p); } catch (e) { throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e); } }; doc.createNSResolver = function (n) { return new NodeXPathNSResolver(n); }; doc.evaluate = function (e, cn, r, t, res) { if (t < 0 || t > 9) { throw { code: 0, toString: function () { return "Request type not supported"; } }; } return doc.createExpression(e, r, p).evaluate(cn, t, res); }; }; // --------------------------------------------------------------------------- // Install DOM 3 XPath support for the current document. try { var shouldInstall = true; try { if (document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("XPath", null)) { shouldInstall = false; } } catch (e) { } if (shouldInstall) { installDOM3XPathSupport(document, new XPathParser()); } } catch (e) { } // --------------------------------------------------------------------------- // exports for node.js installDOM3XPathSupport(exports, new XPathParser()); (function () { var parser = new XPathParser(); var defaultNSResolver = new NamespaceResolver(); var defaultFunctionResolver = new FunctionResolver(); var defaultVariableResolver = new VariableResolver(); function makeNSResolverFromFunction(func) { return { getNamespace: function (prefix, node) { var ns = func(prefix, node); return ns || defaultNSResolver.getNamespace(prefix, node); } }; } function makeNSResolverFromObject(obj) { return makeNSResolverFromFunction(obj.getNamespace.bind(obj)); } function makeNSResolverFromMap(map) { return makeNSResolverFromFunction(function (prefix) { return map[prefix]; }); } function makeNSResolver(resolver) { if (resolver && typeof resolver.getNamespace === "function") { return makeNSResolverFromObject(resolver); } if (typeof resolver === "function") { return makeNSResolverFromFunction(resolver); } // assume prefix -> uri mapping if (typeof resolver === "object") { return makeNSResolverFromMap(resolver); } return defaultNSResolver; } /** Converts native JavaScript types to their XPath library equivalent */ function convertValue(value) { if (value === null || typeof value === "undefined" || value instanceof XString || value instanceof XBoolean || value instanceof XNumber || value instanceof XNodeSet) { return value; } switch (typeof value) { case "string": return new XString(value); case "boolean": return new XBoolean(value); case "number": return new XNumber(value); } // assume node(s) var ns = new XNodeSet(); ns.addArray([].concat(value)); return ns; } function makeEvaluator(func) { return function (context) { var args = Array.prototype.slice.call(arguments, 1).map(function (arg) { return arg.evaluate(context); }); var result = func.apply(this, [].concat(context, args)); return convertValue(result); }; } function makeFunctionResolverFromFunction(func) { return { getFunction: function (name, namespace) { var found = func(name, namespace); if (found) { return makeEvaluator(found); } return defaultFunctionResolver.getFunction(name, namespace); } }; } function makeFunctionResolverFromObject(obj) { return makeFunctionResolverFromFunction(obj.getFunction.bind(obj)); } function makeFunctionResolverFromMap(map) { return makeFunctionResolverFromFunction(function (name) { return map[name]; }); } function makeFunctionResolver(resolver) { if (resolver && typeof resolver.getFunction === "function") { return makeFunctionResolverFromObject(resolver); } if (typeof resolver === "function") { return makeFunctionResolverFromFunction(resolver); } // assume map if (typeof resolver === "object") { return makeFunctionResolverFromMap(resolver); } return defaultFunctionResolver; } function makeVariableResolverFromFunction(func) { return { getVariable: function (name, namespace) { var value = func(name, namespace); return convertValue(value); } }; } function makeVariableResolver(resolver) { if (resolver) { if (typeof resolver.getVariable === "function") { return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver)); } if (typeof resolver === "function") { return makeVariableResolverFromFunction(resolver); } // assume map if (typeof resolver === "object") { return makeVariableResolverFromFunction(function (name) { return resolver[name]; }); } } return defaultVariableResolver; } function copyIfPresent(prop, dest, source) { if (prop in source) { dest[prop] = source[prop]; } } function makeContext(options) { var context = new XPathContext(); if (options) { context.namespaceResolver = makeNSResolver(options.namespaces); context.functionResolver = makeFunctionResolver(options.functions); context.variableResolver = makeVariableResolver(options.variables); context.expressionContextNode = options.node; copyIfPresent('allowAnyNamespaceForNoPrefix', context, options); copyIfPresent('isHtml', context, options); } else { context.namespaceResolver = defaultNSResolver; } return context; } function evaluate(parsedExpression, options) { var context = makeContext(options); return parsedExpression.evaluate(context); } var evaluatorPrototype = { evaluate: function (options) { return evaluate(this.expression, options); } , evaluateNumber: function (options) { return this.evaluate(options).numberValue(); } , evaluateString: function (options) { return this.evaluate(options).stringValue(); } , evaluateBoolean: function (options) { return this.evaluate(options).booleanValue(); } , evaluateNodeSet: function (options) { return this.evaluate(options).nodeset(); } , select: function (options) { return this.evaluateNodeSet(options).toArray() } , select1: function (options) { return this.select(options)[0]; } }; function parse(xpath) { var parsed = parser.parse(xpath); return Object.create(evaluatorPrototype, { expression: { value: parsed } }); } exports.parse = parse; })(); assign( exports, { XPath: XPath, XPathParser: XPathParser, XPathResult: XPathResult, Step: Step, PathExpr: PathExpr, NodeTest: NodeTest, LocationPath: LocationPath, OrOperation: OrOperation, AndOperation: AndOperation, BarOperation: BarOperation, EqualsOperation: EqualsOperation, NotEqualOperation: NotEqualOperation, LessThanOperation: LessThanOperation, GreaterThanOperation: GreaterThanOperation, LessThanOrEqualOperation: LessThanOrEqualOperation, GreaterThanOrEqualOperation: GreaterThanOrEqualOperation, PlusOperation: PlusOperation, MinusOperation: MinusOperation, MultiplyOperation: MultiplyOperation, DivOperation: DivOperation, ModOperation: ModOperation, UnaryMinusOperation: UnaryMinusOperation, FunctionCall: FunctionCall, VariableReference: VariableReference, XPathContext: XPathContext, XNodeSet: XNodeSet, XBoolean: XBoolean, XString: XString, XNumber: XNumber, NamespaceResolver: NamespaceResolver, FunctionResolver: FunctionResolver, VariableResolver: VariableResolver, Utilities: Utilities, } ); // helper exports.select = function (e, doc, single) { return exports.selectWithResolver(e, doc, null, single); }; exports.useNamespaces = function (mappings) { var resolver = { mappings: mappings || {}, lookupNamespaceURI: function (prefix) { return this.mappings[prefix]; } }; return function (e, doc, single) { return exports.selectWithResolver(e, doc, resolver, single); }; }; exports.selectWithResolver = function (e, doc, resolver, single) { var expression = new XPathExpression(e, resolver, new XPathParser()); var type = XPathResult.ANY_TYPE; var result = expression.evaluate(doc, type, null); if (result.resultType == XPathResult.STRING_TYPE) { result = result.stringValue; } else if (result.resultType == XPathResult.NUMBER_TYPE) { result = result.numberValue; } else if (result.resultType == XPathResult.BOOLEAN_TYPE) { result = result.booleanValue; } else { result = result.nodes; if (single) { result = result[0]; } } return result; }; exports.select1 = function (e, doc) { return exports.select(e, doc, true); }; var isArrayOfNodes = function (value) { return Array.isArray(value) && value.every(isNodeLike); }; var isNodeOfType = function (type) { return function (value) { return isNodeLike(value) && value.nodeType === type; }; }; assign( exports, { isNodeLike: isNodeLike, isArrayOfNodes: isArrayOfNodes, isElement: isNodeOfType(NodeTypes.ELEMENT_NODE), isAttribute: isNodeOfType(NodeTypes.ATTRIBUTE_NODE), isTextNode: isNodeOfType(NodeTypes.TEXT_NODE), isCDATASection: isNodeOfType(NodeTypes.CDATA_SECTION_NODE), isProcessingInstruction: isNodeOfType(NodeTypes.PROCESSING_INSTRUCTION_NODE), isComment: isNodeOfType(NodeTypes.COMMENT_NODE), isDocumentNode: isNodeOfType(NodeTypes.DOCUMENT_NODE), isDocumentTypeNode: isNodeOfType(NodeTypes.DOCUMENT_TYPE_NODE), isDocumentFragment: isNodeOfType(NodeTypes.DOCUMENT_FRAGMENT_NODE), } ); // end non-node wrapper })(xpath); /***/ }), /***/ 2613: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); /***/ }), /***/ 181: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); /***/ }), /***/ 4434: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); /***/ }), /***/ 9896: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); /***/ }), /***/ 8611: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); /***/ }), /***/ 5692: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); /***/ }), /***/ 9278: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); /***/ }), /***/ 4589: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:assert"); /***/ }), /***/ 6698: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks"); /***/ }), /***/ 4573: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer"); /***/ }), /***/ 7540: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:console"); /***/ }), /***/ 7598: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); /***/ }), /***/ 3053: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:diagnostics_channel"); /***/ }), /***/ 610: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:dns"); /***/ }), /***/ 8474: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); /***/ }), /***/ 7067: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http"); /***/ }), /***/ 2467: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http2"); /***/ }), /***/ 7030: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net"); /***/ }), /***/ 643: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:perf_hooks"); /***/ }), /***/ 1708: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process"); /***/ }), /***/ 1792: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring"); /***/ }), /***/ 7075: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); /***/ }), /***/ 7830: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream/web"); /***/ }), /***/ 1692: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls"); /***/ }), /***/ 3136: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url"); /***/ }), /***/ 7975: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); /***/ }), /***/ 3429: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util/types"); /***/ }), /***/ 5919: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:worker_threads"); /***/ }), /***/ 8522: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib"); /***/ }), /***/ 857: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); /***/ }), /***/ 6928: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); /***/ }), /***/ 3193: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); /***/ }), /***/ 4756: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); /***/ }), /***/ 9023: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); /***/ }), /***/ 8167: /***/ ((module) => { module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); /***/ }), /***/ 1506: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { var possibleNames = __nccwpck_require__(8879); var g = typeof globalThis === 'undefined' ? global : globalThis; /** @type {import('.')} */ module.exports = function availableTypedArrays() { var /** @type {ReturnType} */ out = []; for (var i = 0; i < possibleNames.length; i++) { if (typeof g[possibleNames[i]] === 'function') { // @ts-expect-error out[out.length] = possibleNames[i]; } } return out; }; /***/ }), /***/ 8517: /***/ ((module) => { // this should only run in node >= 13.2, so it // does not need any of the intense fallbacks that old node/browsers do var $iterator = Symbol.iterator; module.exports = function getIterator(iterable) { // alternatively, `iterable[$iterator]?.()` if (iterable != null && typeof iterable[$iterator] !== 'undefined') { return iterable[$iterator](); } }; /***/ }), /***/ 1204: /***/ ((__unused_webpack_module, __unused_webpack_exports, __nccwpck_require__) => { /* c8 ignore start */ // 64 KiB (same size chrome slice theirs blob into Uint8array's) const POOL_SIZE = 65536 if (!globalThis.ReadableStream) { // `node:stream/web` got introduced in v16.5.0 as experimental // and it's preferred over the polyfilled version. So we also // suppress the warning that gets emitted by NodeJS for using it. try { const process = __nccwpck_require__(1708) const { emitWarning } = process try { process.emitWarning = () => {} Object.assign(globalThis, __nccwpck_require__(7830)) process.emitWarning = emitWarning } catch (error) { process.emitWarning = emitWarning throw error } } catch (error) { // fallback to polyfill implementation Object.assign(globalThis, __nccwpck_require__(3585)) } } try { // Don't use node: prefix for this, require+node: is not supported until node v14.14 // Only `import()` can use prefix in 12.20 and later const { Blob } = __nccwpck_require__(181) if (Blob && !Blob.prototype.stream) { Blob.prototype.stream = function name (params) { let position = 0 const blob = this return new ReadableStream({ type: 'bytes', async pull (ctrl) { const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)) const buffer = await chunk.arrayBuffer() position += buffer.byteLength ctrl.enqueue(new Uint8Array(buffer)) if (position === blob.size) { ctrl.close() } } }) } } } catch (error) {} /* c8 ignore end */ /***/ }), /***/ 9584: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { V4: () => (/* binding */ getInput), C1: () => (/* binding */ setFailed), uH: () => (/* binding */ setOutput) }); // UNUSED EXPORTS: ExitCode, addPath, debug, endGroup, error, exportVariable, getBooleanInput, getIDToken, getMultilineInput, getState, group, info, isDebug, markdownSummary, notice, platform, saveState, setCommandEcho, setSecret, startGroup, summary, toPlatformPath, toPosixPath, toWin32Path, warning // EXTERNAL MODULE: external "os" var external_os_ = __nccwpck_require__(857); ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/utils.js // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function utils_toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } /** * * @param annotationProperties * @returns The command properties to send with the actual annotation command * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ function utils_toCommandProperties(annotationProperties) { if (!Object.keys(annotationProperties).length) { return {}; } return { title: annotationProperties.title, file: annotationProperties.file, line: annotationProperties.startLine, endLine: annotationProperties.endLine, col: annotationProperties.startColumn, endColumn: annotationProperties.endColumn }; } //# sourceMappingURL=utils.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/command.js /** * Issues a command to the GitHub Actions runner * * @param command - The command name to issue * @param properties - Additional properties for the command (key-value pairs) * @param message - The message to include with the command * @remarks * This function outputs a specially formatted string to stdout that the Actions * runner interprets as a command. These commands can control workflow behavior, * set outputs, create annotations, mask values, and more. * * Command Format: * ::name key=value,key=value::message * * @example * ```typescript * // Issue a warning annotation * issueCommand('warning', {}, 'This is a warning message'); * // Output: ::warning::This is a warning message * * // Set an environment variable * issueCommand('set-env', { name: 'MY_VAR' }, 'some value'); * // Output: ::set-env name=MY_VAR::some value * * // Add a secret mask * issueCommand('add-mask', {}, 'secretValue123'); * // Output: ::add-mask::secretValue123 * ``` * * @internal * This is an internal utility function that powers the public API functions * such as setSecret, warning, error, and exportVariable. */ function command_issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + external_os_.EOL); } function command_issue(name, message = '') { command_issueCommand(name, {}, message); } const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return utils_toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return utils_toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map ;// CONCATENATED MODULE: external "crypto" const external_crypto_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); // EXTERNAL MODULE: external "fs" var external_fs_ = __nccwpck_require__(9896); ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/file-command.js // For internal use, subject to change. // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ function file_command_issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } if (!external_fs_.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } external_fs_.appendFileSync(filePath, `${utils_toCommandValue(message)}${external_os_.EOL}`, { encoding: 'utf8' }); } function file_command_prepareKeyValueMessage(key, value) { const delimiter = `ghadelimiter_${external_crypto_namespaceObject.randomUUID()}`; const convertedValue = utils_toCommandValue(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. if (key.includes(delimiter)) { throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } return `${key}<<${delimiter}${external_os_.EOL}${convertedValue}${external_os_.EOL}${delimiter}`; } //# sourceMappingURL=file-command.js.map // EXTERNAL MODULE: external "path" var external_path_ = __nccwpck_require__(6928); // EXTERNAL MODULE: ./node_modules/@actions/http-client/lib/index.js + 1 modules var lib = __nccwpck_require__(4942); ;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/auth.js var __awaiter = (undefined && undefined.__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()); }); }; class BasicCredentialHandler { constructor(username, password) { this.username = username; this.password = password; } prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } class auth_BearerCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Bearer ${this.token}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } class PersonalAccessTokenCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } //# sourceMappingURL=auth.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/oidc-utils.js var oidc_utils_awaiter = (undefined && undefined.__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()); }); }; class oidc_utils_OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { allowRetries: allowRetry, maxRetries: maxRetry }; return new HttpClient('actions/oidc-client', [new BearerCredentialHandler(oidc_utils_OidcClient.getRequestToken())], requestOptions); } static getRequestToken() { const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; if (!token) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } return token; } static getIDTokenUrl() { const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; if (!runtimeUrl) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } return runtimeUrl; } static getCall(id_token_url) { return oidc_utils_awaiter(this, void 0, void 0, function* () { var _a; const httpclient = oidc_utils_OidcClient.createHttpClient(); const res = yield httpclient .getJson(id_token_url) .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { throw new Error('Response json body do not have ID Token field'); } return id_token; }); } static getIDToken(audience) { return oidc_utils_awaiter(this, void 0, void 0, function* () { try { // New ID Token is requested from action service let id_token_url = oidc_utils_OidcClient.getIDTokenUrl(); if (audience) { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } debug(`ID token url is ${id_token_url}`); const id_token = yield oidc_utils_OidcClient.getCall(id_token_url); setSecret(id_token); return id_token; } catch (error) { throw new Error(`Error message: ${error.message}`); } }); } } //# sourceMappingURL=oidc-utils.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/summary.js var summary_awaiter = (undefined && undefined.__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()); }); }; const { access, appendFile, writeFile } = external_fs_.promises; const SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; const SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; class Summary { constructor() { this._buffer = ''; } /** * Finds the summary file path from the environment, rejects if env var is not found or file does not exist * Also checks r/w permissions. * * @returns step summary file path */ filePath() { return summary_awaiter(this, void 0, void 0, function* () { if (this._filePath) { return this._filePath; } const pathFromEnv = process.env[SUMMARY_ENV_VAR]; if (!pathFromEnv) { throw new Error(`Unable to find environment variable for $${SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } try { yield access(pathFromEnv, external_fs_.constants.R_OK | external_fs_.constants.W_OK); } catch (_a) { throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } this._filePath = pathFromEnv; return this._filePath; }); } /** * Wraps content in an HTML tag, adding any HTML attributes * * @param {string} tag HTML tag to wrap * @param {string | null} content content within the tag * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add * * @returns {string} content wrapped in HTML element */ wrap(tag, content, attrs = {}) { const htmlAttrs = Object.entries(attrs) .map(([key, value]) => ` ${key}="${value}"`) .join(''); if (!content) { return `<${tag}${htmlAttrs}>`; } return `<${tag}${htmlAttrs}>${content}`; } /** * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. * * @param {SummaryWriteOptions} [options] (optional) options for write operation * * @returns {Promise} summary instance */ write(options) { return summary_awaiter(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); const writeFunc = overwrite ? writeFile : appendFile; yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); return this.emptyBuffer(); }); } /** * Clears the summary buffer and wipes the summary file * * @returns {Summary} summary instance */ clear() { return summary_awaiter(this, void 0, void 0, function* () { return this.emptyBuffer().write({ overwrite: true }); }); } /** * Returns the current summary buffer as a string * * @returns {string} string of summary buffer */ stringify() { return this._buffer; } /** * If the summary buffer is empty * * @returns {boolen} true if the buffer is empty */ isEmptyBuffer() { return this._buffer.length === 0; } /** * Resets the summary buffer without writing to summary file * * @returns {Summary} summary instance */ emptyBuffer() { this._buffer = ''; return this; } /** * Adds raw text to the summary buffer * * @param {string} text content to add * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) * * @returns {Summary} summary instance */ addRaw(text, addEOL = false) { this._buffer += text; return addEOL ? this.addEOL() : this; } /** * Adds the operating system-specific end-of-line marker to the buffer * * @returns {Summary} summary instance */ addEOL() { return this.addRaw(external_os_.EOL); } /** * Adds an HTML codeblock to the summary buffer * * @param {string} code content to render within fenced code block * @param {string} lang (optional) language to syntax highlight code * * @returns {Summary} summary instance */ addCodeBlock(code, lang) { const attrs = Object.assign({}, (lang && { lang })); const element = this.wrap('pre', this.wrap('code', code), attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML list to the summary buffer * * @param {string[]} items list of items to render * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) * * @returns {Summary} summary instance */ addList(items, ordered = false) { const tag = ordered ? 'ol' : 'ul'; const listItems = items.map(item => this.wrap('li', item)).join(''); const element = this.wrap(tag, listItems); return this.addRaw(element).addEOL(); } /** * Adds an HTML table to the summary buffer * * @param {SummaryTableCell[]} rows table rows * * @returns {Summary} summary instance */ addTable(rows) { const tableBody = rows .map(row => { const cells = row .map(cell => { if (typeof cell === 'string') { return this.wrap('td', cell); } const { header, data, colspan, rowspan } = cell; const tag = header ? 'th' : 'td'; const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); return this.wrap(tag, data, attrs); }) .join(''); return this.wrap('tr', cells); }) .join(''); const element = this.wrap('table', tableBody); return this.addRaw(element).addEOL(); } /** * Adds a collapsable HTML details element to the summary buffer * * @param {string} label text for the closed state * @param {string} content collapsable content * * @returns {Summary} summary instance */ addDetails(label, content) { const element = this.wrap('details', this.wrap('summary', label) + content); return this.addRaw(element).addEOL(); } /** * Adds an HTML image tag to the summary buffer * * @param {string} src path to the image you to embed * @param {string} alt text description of the image * @param {SummaryImageOptions} options (optional) addition image attributes * * @returns {Summary} summary instance */ addImage(src, alt, options) { const { width, height } = options || {}; const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); return this.addRaw(element).addEOL(); } /** * Adds an HTML section heading element * * @param {string} text heading text * @param {number | string} [level=1] (optional) the heading level, default: 1 * * @returns {Summary} summary instance */ addHeading(text, level) { const tag = `h${level}`; const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) ? tag : 'h1'; const element = this.wrap(allowedTag, text); return this.addRaw(element).addEOL(); } /** * Adds an HTML thematic break (
) to the summary buffer * * @returns {Summary} summary instance */ addSeparator() { const element = this.wrap('hr', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML line break (
) to the summary buffer * * @returns {Summary} summary instance */ addBreak() { const element = this.wrap('br', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML blockquote to the summary buffer * * @param {string} text quote text * @param {string} cite (optional) citation url * * @returns {Summary} summary instance */ addQuote(text, cite) { const attrs = Object.assign({}, (cite && { cite })); const element = this.wrap('blockquote', text, attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML anchor tag to the summary buffer * * @param {string} text link text/content * @param {string} href hyperlink * * @returns {Summary} summary instance */ addLink(text, href) { const element = this.wrap('a', text, { href }); return this.addRaw(element).addEOL(); } } const _summary = new Summary(); /** * @deprecated use `core.summary` */ const markdownSummary = (/* unused pure expression or super */ null && (_summary)); const summary = (/* unused pure expression or super */ null && (_summary)); //# sourceMappingURL=summary.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/path-utils.js /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. * * @param pth. Path to transform. * @return string Posix path. */ function toPosixPath(pth) { return pth.replace(/[\\]/g, '/'); } /** * toWin32Path converts the given path to the win32 form. On Linux, / will be * replaced with \\. * * @param pth. Path to transform. * @return string Win32 path. */ function toWin32Path(pth) { return pth.replace(/[/]/g, '\\'); } /** * toPlatformPath converts the given path to a platform-specific path. It does * this by replacing instances of / and \ with the platform-specific path * separator. * * @param pth The path to platformize. * @return string The platform-specific path. */ function toPlatformPath(pth) { return pth.replace(/[/\\]/g, path.sep); } //# sourceMappingURL=path-utils.js.map // EXTERNAL MODULE: ./node_modules/@actions/exec/lib/exec.js + 5 modules var lib_exec = __nccwpck_require__(2876); ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/platform.js var platform_awaiter = (undefined && undefined.__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()); }); }; const getWindowsInfo = () => platform_awaiter(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { silent: true }); const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { silent: true }); return { name: name.trim(), version: version.trim() }; }); const getMacOsInfo = () => platform_awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c, _d; const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { silent: true }); const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; return { name, version }; }); const getLinuxInfo = () => platform_awaiter(void 0, void 0, void 0, function* () { const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { silent: true }); const [name, version] = stdout.trim().split('\n'); return { name, version }; }); const platform = external_os_.platform(); const arch = external_os_.arch(); const isWindows = platform === 'win32'; const isMacOS = platform === 'darwin'; const isLinux = platform === 'linux'; function getDetails() { return platform_awaiter(this, void 0, void 0, function* () { return Object.assign(Object.assign({}, (yield (isWindows ? getWindowsInfo() : isMacOS ? getMacOsInfo() : getLinuxInfo()))), { platform, arch, isWindows, isMacOS, isLinux }); }); } //# sourceMappingURL=platform.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/core/lib/core.js var core_awaiter = (undefined && undefined.__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()); }); }; /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode || (ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = toCommandValue(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { return issueFileCommand('ENV', prepareKeyValueMessage(name, val)); } issueCommand('set-env', { name }, convertedVal); } /** * Registers a secret which will get masked from logs * * @param secret - Value of the secret to be masked * @remarks * This function instructs the Actions runner to mask the specified value in any * logs produced during the workflow run. Once registered, the secret value will * be replaced with asterisks (***) whenever it appears in console output, logs, * or error messages. * * This is useful for protecting sensitive information such as: * - API keys * - Access tokens * - Authentication credentials * - URL parameters containing signatures (SAS tokens) * * Note that masking only affects future logs; any previous appearances of the * secret in logs before calling this function will remain unmasked. * * @example * ```typescript * // Register an API token as a secret * const apiToken = "abc123xyz456"; * setSecret(apiToken); * * // Now any logs containing this value will show *** instead * console.log(`Using token: ${apiToken}`); // Outputs: "Using token: ***" * ``` */ function core_setSecret(secret) { issueCommand('add-mask', {}, secret); } /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { issueFileCommand('PATH', inputPath); } else { issueCommand('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } /** * Gets the value of an input. * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { return val; } return val.trim(); } /** * Gets the values of an multiline input. Each value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string[] * */ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); if (options && options.trimWhitespace === false) { return inputs; } return inputs.map(input => input.trim()); } /** * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. * Support boolean input list: `true | True | TRUE | false | False | FALSE` . * The return value is also in boolean type. * ref: https://yaml.org/spec/1.2/spec.html#id2804923 * * @param name name of the input to get * @param options optional. See InputOptions. * @returns boolean */ function getBooleanInput(name, options) { const trueValue = ['true', 'True', 'TRUE']; const falseValue = ['false', 'False', 'FALSE']; const val = getInput(name, options); if (trueValue.includes(val)) return true; if (falseValue.includes(val)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { return file_command_issueFileCommand('OUTPUT', file_command_prepareKeyValueMessage(name, value)); } process.stdout.write(external_os_.EOL); command_issueCommand('set-output', { name }, utils_toCommandValue(value)); } /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { issue('echo', enabled ? 'on' : 'off'); } //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } /** * Writes debug message to user log * @param message debug message */ function core_debug(message) { issueCommand('debug', {}, message); } /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { command_issueCommand('error', utils_toCommandProperties(properties), message instanceof Error ? message.toString() : message); } /** * Adds a warning issue * @param message warning issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { issueCommand('warning', toCommandProperties(properties), message instanceof Error ? message.toString() : message); } /** * Adds a notice issue * @param message notice issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { issueCommand('notice', toCommandProperties(properties), message instanceof Error ? message.toString() : message); } /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { issue('group', name); } /** * End an output group. */ function endGroup() { issue('endgroup'); } /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return core_awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { return issueFileCommand('STATE', prepareKeyValueMessage(name, value)); } issueCommand('save-state', { name }, toCommandValue(value)); } /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } function getIDToken(aud) { return core_awaiter(this, void 0, void 0, function* () { return yield OidcClient.getIDToken(aud); }); } /** * Summary exports */ /** * @deprecated use core.summary */ /** * Path exports */ /** * Platform utilities exports */ //# sourceMappingURL=core.js.map /***/ }), /***/ 2876: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { H: () => (/* binding */ getExecOutput) }); // UNUSED EXPORTS: exec // EXTERNAL MODULE: external "string_decoder" var external_string_decoder_ = __nccwpck_require__(3193); // EXTERNAL MODULE: external "os" var external_os_ = __nccwpck_require__(857); // EXTERNAL MODULE: external "events" var external_events_ = __nccwpck_require__(4434); ;// CONCATENATED MODULE: external "child_process" const external_child_process_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); // EXTERNAL MODULE: external "path" var external_path_ = __nccwpck_require__(6928); // EXTERNAL MODULE: external "assert" var external_assert_ = __nccwpck_require__(2613); // EXTERNAL MODULE: external "fs" var external_fs_ = __nccwpck_require__(9896); ;// CONCATENATED MODULE: ./node_modules/@actions/io/lib/io-util.js var __awaiter = (undefined && undefined.__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()); }); }; const { chmod, copyFile, lstat, mkdir, open: io_util_open, readdir, rename, rm, rmdir, stat, symlink, unlink } = external_fs_.promises; // export const {open} = 'fs' const IS_WINDOWS = process.platform === 'win32'; /** * Custom implementation of readlink to ensure Windows junctions * maintain trailing backslash for backward compatibility with Node.js < 24 * * In Node.js 20, Windows junctions (directory symlinks) always returned paths * with trailing backslashes. Node.js 24 removed this behavior, which breaks * code that relied on this format for path operations. * * This implementation restores the Node 20 behavior by adding a trailing * backslash to all junction results on Windows. */ function readlink(fsPath) { return __awaiter(this, void 0, void 0, function* () { const result = yield fs.promises.readlink(fsPath); // On Windows, restore Node 20 behavior: add trailing backslash to all results // since junctions on Windows are always directory links if (IS_WINDOWS && !result.endsWith('\\')) { return `${result}\\`; } return result; }); } // See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 const UV_FS_O_EXLOCK = 0x10000000; const READONLY = external_fs_.constants.O_RDONLY; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { yield stat(fsPath); } catch (err) { if (err.code === 'ENOENT') { return false; } throw err; } return true; }); } function isDirectory(fsPath_1) { return __awaiter(this, arguments, void 0, function* (fsPath, useStat = false) { const stats = useStat ? yield stat(fsPath) : yield lstat(fsPath); return stats.isDirectory(); }); } /** * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). */ function isRooted(p) { p = normalizeSeparators(p); if (!p) { throw new Error('isRooted() parameter "p" cannot be empty'); } if (IS_WINDOWS) { return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello ); // e.g. C: or C:\hello } return p.startsWith('/'); } /** * Best effort attempt to determine whether a file exists and is executable. * @param filePath file path to check * @param extensions additional file extensions to try * @return if file exists and is executable, returns the file path. otherwise empty string. */ function tryGetExecutablePath(filePath, extensions) { return __awaiter(this, void 0, void 0, function* () { let stats = undefined; try { // test file exists stats = yield stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (IS_WINDOWS) { // on Windows, test for valid extension const upperExt = external_path_.extname(filePath).toUpperCase(); if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { return filePath; } } else { if (isUnixExecutable(stats)) { return filePath; } } } // try each extension const originalFilePath = filePath; for (const extension of extensions) { filePath = originalFilePath + extension; stats = undefined; try { stats = yield stat(filePath); } catch (err) { if (err.code !== 'ENOENT') { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); } } if (stats && stats.isFile()) { if (IS_WINDOWS) { // preserve the case of the actual file (since an extension was appended) try { const directory = external_path_.dirname(filePath); const upperName = external_path_.basename(filePath).toUpperCase(); for (const actualName of yield readdir(directory)) { if (upperName === actualName.toUpperCase()) { filePath = external_path_.join(directory, actualName); break; } } } catch (err) { // eslint-disable-next-line no-console console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); } return filePath; } else { if (isUnixExecutable(stats)) { return filePath; } } } } return ''; }); } function normalizeSeparators(p) { p = p || ''; if (IS_WINDOWS) { // convert slashes on Windows p = p.replace(/\//g, '\\'); // remove redundant slashes return p.replace(/\\\\+/g, '\\'); } // remove redundant slashes return p.replace(/\/\/+/g, '/'); } // on Mac/Linux, test the execute bit // R W X R W X R W X // 256 128 64 32 16 8 4 2 1 function isUnixExecutable(stats) { return ((stats.mode & 1) > 0 || ((stats.mode & 8) > 0 && process.getgid !== undefined && stats.gid === process.getgid()) || ((stats.mode & 64) > 0 && process.getuid !== undefined && stats.uid === process.getuid())); } // Get the path of cmd.exe in windows function getCmdPath() { var _a; return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; } //# sourceMappingURL=io-util.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/io/lib/io.js var io_awaiter = (undefined && undefined.__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()); }); }; /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js * * @param source source path * @param dest destination path * @param options optional. See CopyOptions. */ function cp(source_1, dest_1) { return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) { const { force, recursive, copySourceDirectory } = readCopyOptions(options); const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; // Dest is an existing file, but not forcing if (destStat && destStat.isFile() && !force) { return; } // If dest is an existing directory, should copy inside. const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path.join(dest, path.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } const sourceStat = yield ioUtil.stat(source); if (sourceStat.isDirectory()) { if (!recursive) { throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); } else { yield cpDirRecursive(source, newDest, 0, force); } } else { if (path.relative(source, newDest) === '') { // a file cannot be copied to itself throw new Error(`'${newDest}' and '${source}' are the same file`); } yield io_copyFile(source, newDest, force); } }); } /** * Moves a path. * * @param source source path * @param dest destination path * @param options optional. See MoveOptions. */ function mv(source_1, dest_1) { return io_awaiter(this, arguments, void 0, function* (source, dest, options = {}) { if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { // If dest is directory copy src into dest dest = path.join(dest, path.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { if (options.force == null || options.force) { yield rmRF(dest); } else { throw new Error('Destination already exists'); } } } yield mkdirP(path.dirname(dest)); yield ioUtil.rename(source, dest); }); } /** * Remove a path recursively with force * * @param inputPath path to remove */ function rmRF(inputPath) { return io_awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { // Check for invalid characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } } try { // note if path does not exist, error is silent yield ioUtil.rm(inputPath, { force: true, maxRetries: 3, recursive: true, retryDelay: 300 }); } catch (err) { throw new Error(`File was unable to be removed ${err}`); } }); } /** * Make a directory. Creates the full path with folders in between * Will throw if it fails * * @param fsPath path to create * @returns Promise */ function mkdirP(fsPath) { return io_awaiter(this, void 0, void 0, function* () { ok(fsPath, 'a path argument must be provided'); yield ioUtil.mkdir(fsPath, { recursive: true }); }); } /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, it will throw. * * @param tool name of the tool * @param check whether to check if tool exists * @returns Promise path to tool */ function which(tool, check) { return io_awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // recursive when check=true if (check) { const result = yield which(tool, false); if (!result) { if (IS_WINDOWS) { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); } else { throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); } } return result; } const matches = yield findInPath(tool); if (matches && matches.length > 0) { return matches[0]; } return ''; }); } /** * Returns a list of all occurrences of the given tool on the system path. * * @returns Promise the paths of the tool */ function findInPath(tool) { return io_awaiter(this, void 0, void 0, function* () { if (!tool) { throw new Error("parameter 'tool' is required"); } // build the list of extensions to try const extensions = []; if (IS_WINDOWS && process.env['PATHEXT']) { for (const extension of process.env['PATHEXT'].split(external_path_.delimiter)) { if (extension) { extensions.push(extension); } } } // if it's rooted, return it if exists. otherwise return empty. if (isRooted(tool)) { const filePath = yield tryGetExecutablePath(tool, extensions); if (filePath) { return [filePath]; } return []; } // if any path separators, return empty if (tool.includes(external_path_.sep)) { return []; } // build the list of directories // // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, // it feels like we should not do this. Checking the current directory seems like more of a use // case of a shell, and the which() function exposed by the toolkit should strive for consistency // across platforms. const directories = []; if (process.env.PATH) { for (const p of process.env.PATH.split(external_path_.delimiter)) { if (p) { directories.push(p); } } } // find all matches const matches = []; for (const directory of directories) { const filePath = yield tryGetExecutablePath(external_path_.join(directory, tool), extensions); if (filePath) { matches.push(filePath); } } return matches; }); } function readCopyOptions(options) { const force = options.force == null ? true : options.force; const recursive = Boolean(options.recursive); const copySourceDirectory = options.copySourceDirectory == null ? true : Boolean(options.copySourceDirectory); return { force, recursive, copySourceDirectory }; } function cpDirRecursive(sourceDir, destDir, currentDepth, force) { return io_awaiter(this, void 0, void 0, function* () { // Ensure there is not a run away recursive copy if (currentDepth >= 255) return; currentDepth++; yield mkdirP(destDir); const files = yield ioUtil.readdir(sourceDir); for (const fileName of files) { const srcFile = `${sourceDir}/${fileName}`; const destFile = `${destDir}/${fileName}`; const srcFileStat = yield ioUtil.lstat(srcFile); if (srcFileStat.isDirectory()) { // Recurse yield cpDirRecursive(srcFile, destFile, currentDepth, force); } else { yield io_copyFile(srcFile, destFile, force); } } // Change the mode for the newly created directory yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); }); } // Buffered file copy function io_copyFile(srcFile, destFile, force) { return io_awaiter(this, void 0, void 0, function* () { if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { // unlink/re-link it try { yield ioUtil.lstat(destFile); yield ioUtil.unlink(destFile); } catch (e) { // Try to override file permission if (e.code === 'EPERM') { yield ioUtil.chmod(destFile, '0666'); yield ioUtil.unlink(destFile); } // other errors = it doesn't exist, no work to do } // Copy over symlink const symlinkFull = yield ioUtil.readlink(srcFile); yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); } else if (!(yield ioUtil.exists(destFile)) || force) { yield ioUtil.copyFile(srcFile, destFile); } }); } //# sourceMappingURL=io.js.map ;// CONCATENATED MODULE: external "timers" const external_timers_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); ;// CONCATENATED MODULE: ./node_modules/@actions/exec/lib/toolrunner.js var toolrunner_awaiter = (undefined && undefined.__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()); }); }; /* eslint-disable @typescript-eslint/unbound-method */ const toolrunner_IS_WINDOWS = process.platform === 'win32'; /* * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. */ class ToolRunner extends external_events_.EventEmitter { constructor(toolPath, args, options) { super(); if (!toolPath) { throw new Error("Parameter 'toolPath' cannot be null or empty."); } this.toolPath = toolPath; this.args = args || []; this.options = options || {}; } _debug(message) { if (this.options.listeners && this.options.listeners.debug) { this.options.listeners.debug(message); } } _getCommandString(options, noPrefix) { const toolPath = this._getSpawnFileName(); const args = this._getSpawnArgs(options); let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool if (toolrunner_IS_WINDOWS) { // Windows + cmd file if (this._isCmdFile()) { cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } // Windows + verbatim else if (options.windowsVerbatimArguments) { cmd += `"${toolPath}"`; for (const a of args) { cmd += ` ${a}`; } } // Windows (regular) else { cmd += this._windowsQuoteCmdArg(toolPath); for (const a of args) { cmd += ` ${this._windowsQuoteCmdArg(a)}`; } } } else { // OSX/Linux - this can likely be improved with some form of quoting. // creating processes on Unix is fundamentally different than Windows. // on Unix, execvp() takes an arg array. cmd += toolPath; for (const a of args) { cmd += ` ${a}`; } } return cmd; } _processLineBuffer(data, strBuffer, onLine) { try { let s = strBuffer + data.toString(); let n = s.indexOf(external_os_.EOL); while (n > -1) { const line = s.substring(0, n); onLine(line); // the rest of the string ... s = s.substring(n + external_os_.EOL.length); n = s.indexOf(external_os_.EOL); } return s; } catch (err) { // streaming lines to console is best effort. Don't fail a build. this._debug(`error processing line. Failed with error ${err}`); return ''; } } _getSpawnFileName() { if (toolrunner_IS_WINDOWS) { if (this._isCmdFile()) { return process.env['COMSPEC'] || 'cmd.exe'; } } return this.toolPath; } _getSpawnArgs(options) { if (toolrunner_IS_WINDOWS) { if (this._isCmdFile()) { let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; for (const a of this.args) { argline += ' '; argline += options.windowsVerbatimArguments ? a : this._windowsQuoteCmdArg(a); } argline += '"'; return [argline]; } } return this.args; } _endsWith(str, end) { return str.endsWith(end); } _isCmdFile() { const upperToolPath = this.toolPath.toUpperCase(); return (this._endsWith(upperToolPath, '.CMD') || this._endsWith(upperToolPath, '.BAT')); } _windowsQuoteCmdArg(arg) { // for .exe, apply the normal quoting rules that libuv applies if (!this._isCmdFile()) { return this._uvQuoteCmdArg(arg); } // otherwise apply quoting rules specific to the cmd.exe command line parser. // the libuv rules are generic and are not designed specifically for cmd.exe // command line parser. // // for a detailed description of the cmd.exe command line parser, refer to // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 // need quotes for empty arg if (!arg) { return '""'; } // determine whether the arg needs to be quoted const cmdSpecialChars = [ ' ', '\t', '&', '(', ')', '[', ']', '{', '}', '^', '=', ';', '!', "'", '+', ',', '`', '~', '|', '<', '>', '"' ]; let needsQuotes = false; for (const char of arg) { if (cmdSpecialChars.some(x => x === char)) { needsQuotes = true; break; } } // short-circuit if quotes not needed if (!needsQuotes) { return arg; } // the following quoting rules are very similar to the rules that by libuv applies. // // 1) wrap the string in quotes // // 2) double-up quotes - i.e. " => "" // // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately // doesn't work well with a cmd.exe command line. // // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. // for example, the command line: // foo.exe "myarg:""my val""" // is parsed by a .NET console app into an arg array: // [ "myarg:\"my val\"" ] // which is the same end result when applying libuv quoting rules. although the actual // command line from libuv quoting rules would look like: // foo.exe "myarg:\"my val\"" // // 3) double-up slashes that precede a quote, // e.g. hello \world => "hello \world" // hello\"world => "hello\\""world" // hello\\"world => "hello\\\\""world" // hello world\ => "hello world\\" // // technically this is not required for a cmd.exe command line, or the batch argument parser. // the reasons for including this as a .cmd quoting rule are: // // a) this is optimized for the scenario where the argument is passed from the .cmd file to an // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. // // b) it's what we've been doing previously (by deferring to node default behavior) and we // haven't heard any complaints about that aspect. // // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be // escaped when used on the command line directly - even though within a .cmd file % can be escaped // by using %%. // // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. // // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args // to an external program. // // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. // % can be escaped within a .cmd file. let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; // double the slash } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '"'; // double the quote } else { quoteHit = false; } } reverse += '"'; return reverse.split('').reverse().join(''); } _uvQuoteCmdArg(arg) { // Tool runner wraps child_process.spawn() and needs to apply the same quoting as // Node in certain cases where the undocumented spawn option windowsVerbatimArguments // is used. // // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), // pasting copyright notice from Node within this function: // // Copyright Joyent, Inc. and other Node contributors. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. if (!arg) { // Need double quotation for empty argument return '""'; } if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { // No quotation needed return arg; } if (!arg.includes('"') && !arg.includes('\\')) { // No embedded double quotes or backslashes, so I can just wrap // quote marks around the whole thing. return `"${arg}"`; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" - note the comment in libuv actually reads "hello world\" // but it appears the comment is wrong, it should be "hello world\\" let reverse = '"'; let quoteHit = true; for (let i = arg.length; i > 0; i--) { // walk the string in reverse reverse += arg[i - 1]; if (quoteHit && arg[i - 1] === '\\') { reverse += '\\'; } else if (arg[i - 1] === '"') { quoteHit = true; reverse += '\\'; } else { quoteHit = false; } } reverse += '"'; return reverse.split('').reverse().join(''); } _cloneExecOptions(options) { options = options || {}; const result = { cwd: options.cwd || process.cwd(), env: options.env || process.env, silent: options.silent || false, windowsVerbatimArguments: options.windowsVerbatimArguments || false, failOnStdErr: options.failOnStdErr || false, ignoreReturnCode: options.ignoreReturnCode || false, delay: options.delay || 10000 }; result.outStream = options.outStream || process.stdout; result.errStream = options.errStream || process.stderr; return result; } _getSpawnOptions(options, toolPath) { options = options || {}; const result = {}; result.cwd = options.cwd; result.env = options.env; result['windowsVerbatimArguments'] = options.windowsVerbatimArguments || this._isCmdFile(); if (options.windowsVerbatimArguments) { result.argv0 = `"${toolPath}"`; } return result; } /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See ExecOptions * @returns number */ exec() { return toolrunner_awaiter(this, void 0, void 0, function* () { // root the tool path if it is unrooted and contains relative pathing if (!isRooted(this.toolPath) && (this.toolPath.includes('/') || (toolrunner_IS_WINDOWS && this.toolPath.includes('\\')))) { // prefer options.cwd if it is specified, however options.cwd may also need to be rooted this.toolPath = external_path_.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } // if the tool is only a file name, then resolve it from the PATH // otherwise verify it exists (add extension on Windows if necessary) this.toolPath = yield which(this.toolPath, true); return new Promise((resolve, reject) => toolrunner_awaiter(this, void 0, void 0, function* () { this._debug(`exec tool: ${this.toolPath}`); this._debug('arguments:'); for (const arg of this.args) { this._debug(` ${arg}`); } const optionsNonNull = this._cloneExecOptions(this.options); if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + external_os_.EOL); } const state = new ExecState(optionsNonNull, this.toolPath); state.on('debug', (message) => { this._debug(message); }); if (this.options.cwd && !(yield exists(this.options.cwd))) { return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); } const fileName = this._getSpawnFileName(); const cp = external_child_process_namespaceObject.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); let stdbuffer = ''; if (cp.stdout) { cp.stdout.on('data', (data) => { if (this.options.listeners && this.options.listeners.stdout) { this.options.listeners.stdout(data); } if (!optionsNonNull.silent && optionsNonNull.outStream) { optionsNonNull.outStream.write(data); } stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { if (this.options.listeners && this.options.listeners.stdline) { this.options.listeners.stdline(line); } }); }); } let errbuffer = ''; if (cp.stderr) { cp.stderr.on('data', (data) => { state.processStderr = true; if (this.options.listeners && this.options.listeners.stderr) { this.options.listeners.stderr(data); } if (!optionsNonNull.silent && optionsNonNull.errStream && optionsNonNull.outStream) { const s = optionsNonNull.failOnStdErr ? optionsNonNull.errStream : optionsNonNull.outStream; s.write(data); } errbuffer = this._processLineBuffer(data, errbuffer, (line) => { if (this.options.listeners && this.options.listeners.errline) { this.options.listeners.errline(line); } }); }); } cp.on('error', (err) => { state.processError = err.message; state.processExited = true; state.processClosed = true; state.CheckComplete(); }); cp.on('exit', (code) => { state.processExitCode = code; state.processExited = true; this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); state.CheckComplete(); }); cp.on('close', (code) => { state.processExitCode = code; state.processExited = true; state.processClosed = true; this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); state.CheckComplete(); }); state.on('done', (error, exitCode) => { if (stdbuffer.length > 0) { this.emit('stdline', stdbuffer); } if (errbuffer.length > 0) { this.emit('errline', errbuffer); } cp.removeAllListeners(); if (error) { reject(error); } else { resolve(exitCode); } }); if (this.options.input) { if (!cp.stdin) { throw new Error('child process missing stdin'); } cp.stdin.end(this.options.input); } })); }); } } /** * Convert an arg string to an array of args. Handles escaping * * @param argString string of arguments * @returns string[] array of arguments */ function argStringToArray(argString) { const args = []; let inQuotes = false; let escaped = false; let arg = ''; function append(c) { // we only escape double quotes. if (escaped && c !== '"') { arg += '\\'; } arg += c; escaped = false; } for (let i = 0; i < argString.length; i++) { const c = argString.charAt(i); if (c === '"') { if (!escaped) { inQuotes = !inQuotes; } else { append(c); } continue; } if (c === '\\' && escaped) { append(c); continue; } if (c === '\\' && inQuotes) { escaped = true; continue; } if (c === ' ' && !inQuotes) { if (arg.length > 0) { args.push(arg); arg = ''; } continue; } append(c); } if (arg.length > 0) { args.push(arg.trim()); } return args; } class ExecState extends external_events_.EventEmitter { constructor(options, toolPath) { super(); this.processClosed = false; // tracks whether the process has exited and stdio is closed this.processError = ''; this.processExitCode = 0; this.processExited = false; // tracks whether the process has exited this.processStderr = false; // tracks whether stderr was written to this.delay = 10000; // 10 seconds this.done = false; this.timeout = null; if (!toolPath) { throw new Error('toolPath must not be empty'); } this.options = options; this.toolPath = toolPath; if (options.delay) { this.delay = options.delay; } } CheckComplete() { if (this.done) { return; } if (this.processClosed) { this._setResult(); } else if (this.processExited) { this.timeout = (0,external_timers_namespaceObject.setTimeout)(ExecState.HandleTimeout, this.delay, this); } } _debug(message) { this.emit('debug', message); } _setResult() { // determine whether there is an error let error; if (this.processExited) { if (this.processError) { error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); } else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); } else if (this.processStderr && this.options.failOnStdErr) { error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); } } // clear the timeout if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } this.done = true; this.emit('done', error, this.processExitCode); } static HandleTimeout(state) { if (state.done) { return; } if (!state.processClosed && state.processExited) { const message = `The STDIO streams did not close within ${state.delay / 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; state._debug(message); } state._setResult(); } } //# sourceMappingURL=toolrunner.js.map ;// CONCATENATED MODULE: ./node_modules/@actions/exec/lib/exec.js var exec_awaiter = (undefined && undefined.__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()); }); }; /** * Exec a command. * Output will be streamed to the live console. * Returns promise with return code * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code */ function exec(commandLine, args, options) { return exec_awaiter(this, void 0, void 0, function* () { const commandArgs = argStringToArray(commandLine); if (commandArgs.length === 0) { throw new Error(`Parameter 'commandLine' cannot be null or empty.`); } // Path to tool to execute should be first arg const toolPath = commandArgs[0]; args = commandArgs.slice(1).concat(args || []); const runner = new ToolRunner(toolPath, args, options); return runner.exec(); }); } /** * Exec a command and get the output. * Output will be streamed to the live console. * Returns promise with the exit code and collected stdout and stderr * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param args optional arguments for tool. Escaping is handled by the lib. * @param options optional exec options. See ExecOptions * @returns Promise exit code, stdout, and stderr */ function getExecOutput(commandLine, args, options) { return exec_awaiter(this, void 0, void 0, function* () { var _a, _b; let stdout = ''; let stderr = ''; //Using string decoder covers the case where a mult-byte character is split const stdoutDecoder = new external_string_decoder_.StringDecoder('utf8'); const stderrDecoder = new external_string_decoder_.StringDecoder('utf8'); const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; const stdErrListener = (data) => { stderr += stderrDecoder.write(data); if (originalStdErrListener) { originalStdErrListener(data); } }; const stdOutListener = (data) => { stdout += stdoutDecoder.write(data); if (originalStdoutListener) { originalStdoutListener(data); } }; const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); //flush any remaining characters stdout += stdoutDecoder.end(); stderr += stderrDecoder.end(); return { exitCode, stdout, stderr }; }); } //# sourceMappingURL=exec.js.map /***/ }), /***/ 4942: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { Qq: () => (/* binding */ HttpClient) }); // UNUSED EXPORTS: Headers, HttpClientError, HttpClientResponse, HttpCodes, MediaTypes, getProxyUrl, isHttps // EXTERNAL MODULE: external "http" var external_http_ = __nccwpck_require__(8611); var external_http_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(external_http_, 2); // EXTERNAL MODULE: external "https" var external_https_ = __nccwpck_require__(5692); var external_https_namespaceObject = /*#__PURE__*/__nccwpck_require__.t(external_https_, 2); ;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/proxy.js function getProxyUrl(reqUrl) { const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { return undefined; } const proxyVar = (() => { if (usingSsl) { return process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { return process.env['http_proxy'] || process.env['HTTP_PROXY']; } })(); if (proxyVar) { try { return new DecodedURL(proxyVar); } catch (_a) { if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) return new DecodedURL(`http://${proxyVar}`); } } else { return undefined; } } function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } const reqHost = reqUrl.hostname; if (isLoopbackAddress(reqHost)) { return true; } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (const upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperNoProxyItem === '*' || upperReqHosts.some(x => x === upperNoProxyItem || x.endsWith(`.${upperNoProxyItem}`) || (upperNoProxyItem.startsWith('.') && x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } function isLoopbackAddress(host) { const hostLower = host.toLowerCase(); return (hostLower === 'localhost' || hostLower.startsWith('127.') || hostLower.startsWith('[::1]') || hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } class DecodedURL extends URL { constructor(url, base) { super(url, base); this._decodedUsername = decodeURIComponent(super.username); this._decodedPassword = decodeURIComponent(super.password); } get username() { return this._decodedUsername; } get password() { return this._decodedPassword; } } //# sourceMappingURL=proxy.js.map // EXTERNAL MODULE: ./node_modules/tunnel/index.js var tunnel = __nccwpck_require__(770); // EXTERNAL MODULE: ./node_modules/undici/index.js var undici = __nccwpck_require__(6752); ;// CONCATENATED MODULE: ./node_modules/@actions/http-client/lib/index.js /* eslint-disable @typescript-eslint/no-explicit-any */ var __awaiter = (undefined && undefined.__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 HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes || (HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers || (Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes || (MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function lib_getProxyUrl(serverUrl) { const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientError extends Error { constructor(message, statusCode) { super(message); this.name = 'HttpClientError'; this.statusCode = statusCode; Object.setPrototypeOf(this, HttpClientError.prototype); } } class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); })); }); } readBodyBuffer() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { const chunks = []; this.message.on('data', (chunk) => { chunks.push(chunk); }); this.message.on('end', () => { resolve(Buffer.concat(chunks)); }); })); }); } } function isHttps(requestUrl) { const parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = this._getUserAgentWithOrchestrationId(userAgent); this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('GET', requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('POST', requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PUT', requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request(verb, requestUrl, stream, additionalHeaders); }); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ getJson(requestUrl_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl_1, obj_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } putJson(requestUrl_1, obj_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } patchJson(requestUrl_1, obj_1) { return __awaiter(this, arguments, void 0, function* (requestUrl, obj, additionalHeaders = {}) { const data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultContentTypeHeader(additionalHeaders, MediaTypes.ApplicationJson); const res = yield this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error('Client has already been disposed.'); } const parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (const handler of this.handlers) { if (handler.canHandleAuthentication(response)) { authenticationHandler = handler; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } const parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol === 'https:' && parsedUrl.protocol !== parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. yield response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (const header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = yield this.requestRaw(info, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } while (numTries < maxTries); return response; }); } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { // If `err` is not passed, then `res` must be passed. reject(new Error('Unknown error')); } else { resolve(res); } } this.requestRawWithCallback(info, data, callbackForResult); }); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { if (typeof data === 'string') { if (!info.options.headers) { info.options.headers = {}; } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } } const req = info.httpModule.request(info.options, (msg) => { const res = new HttpClientResponse(msg); handleResult(undefined, res); }); let socket; req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error(`Request timeout: ${info.options.path}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } getAgentDispatcher(serverUrl) { const parsedUrl = new URL(serverUrl); const proxyUrl = getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (!useProxy) { return; } return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? external_https_namespaceObject : external_http_namespaceObject; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { for (const handler of this.handlers) { handler.prepareRequest(info.options); } } return info; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } /** * Gets an existing header value or returns a default. * Handles converting number header values to strings since HTTP headers must be strings. * Note: This returns string | string[] since some headers can have multiple values. * For headers that must always be a single string (like Content-Type), use the * specialized _getExistingOrDefaultContentTypeHeader method instead. */ _getExistingOrDefaultHeader(additionalHeaders, header, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { const headerValue = lowercaseKeys(this.requestOptions.headers)[header]; if (headerValue) { clientHeader = typeof headerValue === 'number' ? headerValue.toString() : headerValue; } } const additionalValue = additionalHeaders[header]; if (additionalValue !== undefined) { return typeof additionalValue === 'number' ? additionalValue.toString() : additionalValue; } if (clientHeader !== undefined) { return clientHeader; } return _default; } /** * Specialized version of _getExistingOrDefaultHeader for Content-Type header. * Always returns a single string (not an array) since Content-Type should be a single value. * Converts arrays to comma-separated strings and numbers to strings to ensure type safety. * This was split from _getExistingOrDefaultHeader to provide stricter typing for callers * that assign the result to places expecting a string (e.g., additionalHeaders[Headers.ContentType]). */ _getExistingOrDefaultContentTypeHeader(additionalHeaders, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { const headerValue = lowercaseKeys(this.requestOptions.headers)[Headers.ContentType]; if (headerValue) { if (typeof headerValue === 'number') { clientHeader = String(headerValue); } else if (Array.isArray(headerValue)) { clientHeader = headerValue.join(', '); } else { clientHeader = headerValue; } } } const additionalValue = additionalHeaders[Headers.ContentType]; // Return the first non-undefined value, converting numbers or arrays to strings if necessary if (additionalValue !== undefined) { if (typeof additionalValue === 'number') { return String(additionalValue); } else if (Array.isArray(additionalValue)) { return additionalValue.join(', '); } else { return additionalValue; } } if (clientHeader !== undefined) { return clientHeader; } return _default; } _getAgent(parsedUrl) { let agent; const proxyUrl = getProxyUrl(parsedUrl); const useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (this.requestOptions) { maxSockets = this.requestOptions.maxSockets || external_http_.globalAgent.maxSockets; } // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. if (proxyUrl && proxyUrl.hostname) { const agentOptions = { maxSockets, keepAlive: this._keepAlive, proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` })), { host: proxyUrl.hostname, port: proxyUrl.port }) }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if tunneling agent isn't assigned create a new agent if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new external_https_.Agent(options) : new external_http_.Agent(options); this._agent = agent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _getProxyAgentDispatcher(parsedUrl, proxyUrl) { let proxyAgent; if (this._keepAlive) { proxyAgent = this._proxyAgentDispatcher; } // if agent is already assigned use that agent. if (proxyAgent) { return proxyAgent; } const usingSsl = parsedUrl.protocol === 'https:'; proxyAgent = new undici/* ProxyAgent */.kT(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` }))); this._proxyAgentDispatcher = proxyAgent; if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { rejectUnauthorized: false }); } return proxyAgent; } _getUserAgentWithOrchestrationId(userAgent) { const baseUserAgent = userAgent || 'actions/http-client'; const orchId = process.env['ACTIONS_ORCHESTRATION_ID']; if (orchId) { // Sanitize the orchestration ID to ensure it contains only valid characters // Valid characters: 0-9, a-z, _, -, . const sanitizedId = orchId.replace(/[^a-z0-9_.-]/gi, '_'); return `${baseUserAgent} actions_orchestration_id/${sanitizedId}`; } return baseUserAgent; } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); }); } _processResponse(res, options) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode === HttpCodes.NotFound) { resolve(response); } // get the result from the body function dateTimeDeserializer(key, value) { if (typeof value === 'string') { const a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } let obj; let contents; try { contents = yield res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = `Failed request: (${statusCode})`; } const err = new HttpClientError(msg, statusCode); err.result = response.result; reject(err); } else { resolve(response); } })); }); } } const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); //# sourceMappingURL=index.js.map /***/ }), /***/ 4645: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* unused harmony export File */ /* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(6327); const _File = class File extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A { #lastModified = 0 #name = '' /** * @param {*[]} fileBits * @param {string} fileName * @param {{lastModified?: number, type?: string}} options */// @ts-ignore constructor (fileBits, fileName, options = {}) { if (arguments.length < 2) { throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`) } super(fileBits, options) if (options === null) options = {} // Simulate WebIDL type casting for NaN value in lastModified option. const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified) if (!Number.isNaN(lastModified)) { this.#lastModified = lastModified } this.#name = String(fileName) } get name () { return this.#name } get lastModified () { return this.#lastModified } get [Symbol.toStringTag] () { return 'File' } static [Symbol.hasInstance] (object) { return !!object && object instanceof _index_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A && /^(File)$/.test(object[Symbol.toStringTag]) } } /** @type {typeof globalThis.File} */// @ts-ignore const File = _File /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (File); /***/ }), /***/ 9802: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { ZH: () => (/* reexport */ file/* default */.A) }); // UNUSED EXPORTS: Blob, blobFrom, blobFromSync, default, fileFrom, fileFromSync ;// CONCATENATED MODULE: external "node:fs" const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); ;// CONCATENATED MODULE: external "node:path" const external_node_path_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path"); // EXTERNAL MODULE: ./node_modules/node-domexception/index.js var node_domexception = __nccwpck_require__(7666); // EXTERNAL MODULE: ./node_modules/fetch-blob/file.js var file = __nccwpck_require__(4645); // EXTERNAL MODULE: ./node_modules/fetch-blob/index.js var fetch_blob = __nccwpck_require__(6327); ;// CONCATENATED MODULE: ./node_modules/fetch-blob/from.js const { stat } = external_node_fs_namespaceObject.promises /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use */ const blobFromSync = (path, type) => fromBlob(statSync(path), path, type) /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use * @returns {Promise} */ const blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type)) /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use * @returns {Promise} */ const fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type)) /** * @param {string} path filepath on the disk * @param {string} [type] mimetype to use */ const fileFromSync = (path, type) => fromFile(statSync(path), path, type) // @ts-ignore const fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({ path, size: stat.size, lastModified: stat.mtimeMs, start: 0 })], { type }) // @ts-ignore const fromFile = (stat, path, type = '') => new File([new BlobDataItem({ path, size: stat.size, lastModified: stat.mtimeMs, start: 0 })], basename(path), { type, lastModified: stat.mtimeMs }) /** * This is a blob backed up by a file on the disk * with minium requirement. Its wrapped around a Blob as a blobPart * so you have no direct access to this. * * @private */ class BlobDataItem { #path #start constructor (options) { this.#path = options.path this.#start = options.start this.size = options.size this.lastModified = options.lastModified } /** * Slicing arguments is first validated and formatted * to not be out of range by Blob.prototype.slice */ slice (start, end) { return new BlobDataItem({ path: this.#path, lastModified: this.lastModified, size: end - start, start: this.#start + start }) } async * stream () { const { mtimeMs } = await stat(this.#path) if (mtimeMs > this.lastModified) { throw new node_domexception('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError') } yield * (0,external_node_fs_namespaceObject.createReadStream)(this.#path, { start: this.#start, end: this.#start + this.size - 1 }) } get [Symbol.toStringTag] () { return 'Blob' } } /* harmony default export */ const from = ((/* unused pure expression or super */ null && (blobFromSync))); /***/ }), /***/ 6327: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* unused harmony export Blob */ /* harmony import */ var _streams_cjs__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(1204); /*! fetch-blob. MIT License. Jimmy Wärting */ // TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x) // Node has recently added whatwg stream into core // 64 KiB (same size chrome slice theirs blob into Uint8array's) const POOL_SIZE = 65536 /** @param {(Blob | Uint8Array)[]} parts */ async function * toIterator (parts, clone = true) { for (const part of parts) { if ('stream' in part) { yield * (/** @type {AsyncIterableIterator} */ (part.stream())) } else if (ArrayBuffer.isView(part)) { if (clone) { let position = part.byteOffset const end = part.byteOffset + part.byteLength while (position !== end) { const size = Math.min(end - position, POOL_SIZE) const chunk = part.buffer.slice(position, position + size) position += chunk.byteLength yield new Uint8Array(chunk) } } else { yield part } /* c8 ignore next 10 */ } else { // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob) let position = 0, b = (/** @type {Blob} */ (part)) while (position !== b.size) { const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)) const buffer = await chunk.arrayBuffer() position += buffer.byteLength yield new Uint8Array(buffer) } } } } const _Blob = class Blob { /** @type {Array.<(Blob|Uint8Array)>} */ #parts = [] #type = '' #size = 0 #endings = 'transparent' /** * The Blob() constructor returns a new Blob object. The content * of the blob consists of the concatenation of the values given * in the parameter array. * * @param {*} blobParts * @param {{ type?: string, endings?: string }} [options] */ constructor (blobParts = [], options = {}) { if (typeof blobParts !== 'object' || blobParts === null) { throw new TypeError('Failed to construct \'Blob\': The provided value cannot be converted to a sequence.') } if (typeof blobParts[Symbol.iterator] !== 'function') { throw new TypeError('Failed to construct \'Blob\': The object must have a callable @@iterator property.') } if (typeof options !== 'object' && typeof options !== 'function') { throw new TypeError('Failed to construct \'Blob\': parameter 2 cannot convert to dictionary.') } if (options === null) options = {} const encoder = new TextEncoder() for (const element of blobParts) { let part if (ArrayBuffer.isView(element)) { part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)) } else if (element instanceof ArrayBuffer) { part = new Uint8Array(element.slice(0)) } else if (element instanceof Blob) { part = element } else { part = encoder.encode(`${element}`) } this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size this.#parts.push(part) } this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}` const type = options.type === undefined ? '' : String(options.type) this.#type = /^[\x20-\x7E]*$/.test(type) ? type : '' } /** * The Blob interface's size property returns the * size of the Blob in bytes. */ get size () { return this.#size } /** * The type property of a Blob object returns the MIME type of the file. */ get type () { return this.#type } /** * The text() method in the Blob interface returns a Promise * that resolves with a string containing the contents of * the blob, interpreted as UTF-8. * * @return {Promise} */ async text () { // More optimized than using this.arrayBuffer() // that requires twice as much ram const decoder = new TextDecoder() let str = '' for await (const part of toIterator(this.#parts, false)) { str += decoder.decode(part, { stream: true }) } // Remaining str += decoder.decode() return str } /** * The arrayBuffer() method in the Blob interface returns a * Promise that resolves with the contents of the blob as * binary data contained in an ArrayBuffer. * * @return {Promise} */ async arrayBuffer () { // Easier way... Just a unnecessary overhead // const view = new Uint8Array(this.size); // await this.stream().getReader({mode: 'byob'}).read(view); // return view.buffer; const data = new Uint8Array(this.size) let offset = 0 for await (const chunk of toIterator(this.#parts, false)) { data.set(chunk, offset) offset += chunk.length } return data.buffer } stream () { const it = toIterator(this.#parts, true) return new globalThis.ReadableStream({ // @ts-ignore type: 'bytes', async pull (ctrl) { const chunk = await it.next() chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value) }, async cancel () { await it.return() } }) } /** * The Blob interface's slice() method creates and returns a * new Blob object which contains data from a subset of the * blob on which it's called. * * @param {number} [start] * @param {number} [end] * @param {string} [type] */ slice (start = 0, end = this.size, type = '') { const { size } = this let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size) let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size) const span = Math.max(relativeEnd - relativeStart, 0) const parts = this.#parts const blobParts = [] let added = 0 for (const part of parts) { // don't add the overflow to new blobParts if (added >= span) { break } const size = ArrayBuffer.isView(part) ? part.byteLength : part.size if (relativeStart && size <= relativeStart) { // Skip the beginning and change the relative // start & end position as we skip the unwanted parts relativeStart -= size relativeEnd -= size } else { let chunk if (ArrayBuffer.isView(part)) { chunk = part.subarray(relativeStart, Math.min(size, relativeEnd)) added += chunk.byteLength } else { chunk = part.slice(relativeStart, Math.min(size, relativeEnd)) added += chunk.size } relativeEnd -= size blobParts.push(chunk) relativeStart = 0 // All next sequential parts should start at 0 } } const blob = new Blob([], { type: String(type).toLowerCase() }) blob.#size = span blob.#parts = blobParts return blob } get [Symbol.toStringTag] () { return 'Blob' } static [Symbol.hasInstance] (object) { return ( object && typeof object === 'object' && typeof object.constructor === 'function' && ( typeof object.stream === 'function' || typeof object.arrayBuffer === 'function' ) && /^(Blob|File)$/.test(object[Symbol.toStringTag]) ) } } Object.defineProperties(_Blob.prototype, { size: { enumerable: true }, type: { enumerable: true }, slice: { enumerable: true } }) /** @type {typeof globalThis.Blob} */ const Blob = _Blob /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Blob); /***/ }), /***/ 3018: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ $n: () => (/* binding */ formDataToBlob), /* harmony export */ fS: () => (/* binding */ FormData) /* harmony export */ }); /* unused harmony export File */ /* harmony import */ var fetch_blob__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(6327); /* harmony import */ var fetch_blob_file_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(4645); /*! formdata-polyfill. MIT License. Jimmy Wärting */ var {toStringTag:t,iterator:i,hasInstance:h}=Symbol, r=Math.random, m='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','), f=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new fetch_blob_file_js__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A([b],c,b):b]:[a,b+'']), e=(c,f)=>(f?c:c.replace(/\r?\n|\r/g,'\r\n')).replace(/\n/g,'%0A').replace(/\r/g,'%0D').replace(/"/g,'%22'), x=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')} append(...a){x('append',arguments,2);this.#d.push(f(...a))} delete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)} get(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b} has(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)} forEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)} set(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b} *entries(){yield*this.#d} *keys(){for(var[a]of this)yield a} *values(){for(var[,a]of this)yield a}} /** @param {FormData} F */ function formDataToBlob (F,B=fetch_blob__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A){ var b=`${r()}${r()}`.replace(/\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\r\nContent-Disposition: form-data; name="` F.forEach((v,n)=>typeof v=='string' ?c.push(p+e(n)+`"\r\n\r\n${v.replace(/\r(?!\n)|(? { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (/* binding */ isUrl) /* harmony export */ }); function isUrl(string, {lenient = false} = {}) { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } string = string.trim(); if (string.includes(' ')) { return false; } try { new URL(string); // eslint-disable-line no-new return true; } catch { if (lenient) { return isUrl(`https://${string}`); } return false; } } /***/ }), /***/ 2027: /***/ ((__webpack_module__, __webpack_exports__, __nccwpck_require__) => { __nccwpck_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(5634); /* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(7557); /* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(6169); /* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(348); /* harmony import */ var abort_controller__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(7413); /* harmony import */ var ky__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(2263); const TEN_MEGABYTES = 1000 * 1000 * 10; if (!globalThis.fetch) { globalThis.fetch = (url, options) => (0,node_fetch__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Ay)(url, {highWaterMark: TEN_MEGABYTES, ...options}); } if (!globalThis.Headers) { globalThis.Headers = node_fetch__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .A; } if (!globalThis.Request) { globalThis.Request = node_fetch__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A; } if (!globalThis.Response) { globalThis.Response = node_fetch__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A; } if (!globalThis.AbortController) { globalThis.AbortController = abort_controller__WEBPACK_IMPORTED_MODULE_0__; } if (!globalThis.ReadableStream) { try { // eslint-disable-next-line node/file-extension-in-import, node/no-unsupported-features/es-syntax globalThis.ReadableStream = await __nccwpck_require__.e(/* import() */ 241).then(__nccwpck_require__.t.bind(__nccwpck_require__, 9241, 19)); } catch {} } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ky__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .A); __webpack_async_result__(); } catch(e) { __webpack_async_result__(e); } }, 1); /***/ }), /***/ 2263: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /*! MIT License © Sindre Sorhus */ const isObject = value => value !== null && typeof value === 'object'; const supportsAbortController = typeof globalThis.AbortController === 'function'; const supportsStreams = typeof globalThis.ReadableStream === 'function'; const supportsFormData = typeof globalThis.FormData === 'function'; const mergeHeaders = (source1, source2) => { const result = new globalThis.Headers(source1 || {}); const isHeadersInstance = source2 instanceof globalThis.Headers; const source = new globalThis.Headers(source2 || {}); for (const [key, value] of source) { if ((isHeadersInstance && value === 'undefined') || value === undefined) { result.delete(key); } else { result.set(key, value); } } return result; }; const deepMerge = (...sources) => { let returnValue = {}; let headers = {}; for (const source of sources) { if (Array.isArray(source)) { if (!(Array.isArray(returnValue))) { returnValue = []; } returnValue = [...returnValue, ...source]; } else if (isObject(source)) { for (let [key, value] of Object.entries(source)) { if (isObject(value) && (key in returnValue)) { value = deepMerge(returnValue[key], value); } returnValue = {...returnValue, [key]: value}; } if (isObject(source.headers)) { headers = mergeHeaders(headers, source.headers); } } returnValue.headers = headers; } return returnValue; }; const requestMethods = [ 'get', 'post', 'put', 'patch', 'head', 'delete' ]; const responseTypes = { json: 'application/json', text: 'text/*', formData: 'multipart/form-data', arrayBuffer: '*/*', blob: '*/*' }; const retryMethods = [ 'get', 'put', 'head', 'delete', 'options', 'trace' ]; const retryStatusCodes = [ 408, 413, 429, 500, 502, 503, 504 ]; const retryAfterStatusCodes = [ 413, 429, 503 ]; const stop = Symbol('stop'); class HTTPError extends Error { constructor(response, request, options) { // Set the message to the status text, such as Unauthorized, // with some fallbacks. This message should never be undefined. super( response.statusText || String( (response.status === 0 || response.status) ? response.status : 'Unknown response error' ) ); this.name = 'HTTPError'; this.response = response; this.request = request; this.options = options; } } class TimeoutError extends Error { constructor(request) { super('Request timed out'); this.name = 'TimeoutError'; this.request = request; } } const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); // `Promise.race()` workaround (#91) const timeout = (request, abortController, options) => new Promise((resolve, reject) => { const timeoutID = setTimeout(() => { if (abortController) { abortController.abort(); } reject(new TimeoutError(request)); }, options.timeout); /* eslint-disable promise/prefer-await-to-then */ options.fetch(request) .then(resolve) .catch(reject) .then(() => { clearTimeout(timeoutID); }); /* eslint-enable promise/prefer-await-to-then */ }); const normalizeRequestMethod = input => requestMethods.includes(input) ? input.toUpperCase() : input; const defaultRetryOptions = { limit: 2, methods: retryMethods, statusCodes: retryStatusCodes, afterStatusCodes: retryAfterStatusCodes }; const normalizeRetryOptions = (retry = {}) => { if (typeof retry === 'number') { return { ...defaultRetryOptions, limit: retry }; } if (retry.methods && !Array.isArray(retry.methods)) { throw new Error('retry.methods must be an array'); } if (retry.statusCodes && !Array.isArray(retry.statusCodes)) { throw new Error('retry.statusCodes must be an array'); } return { ...defaultRetryOptions, ...retry, afterStatusCodes: retryAfterStatusCodes }; }; // The maximum value of a 32bit int (see issue #117) const maxSafeTimeout = 2147483647; class Ky { constructor(input, options = {}) { this._retryCount = 0; this._input = input; this._options = { // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208 credentials: this._input.credentials || 'same-origin', ...options, headers: mergeHeaders(this._input.headers, options.headers), hooks: deepMerge({ beforeRequest: [], beforeRetry: [], afterResponse: [] }, options.hooks), method: normalizeRequestMethod(options.method || this._input.method), prefixUrl: String(options.prefixUrl || ''), retry: normalizeRetryOptions(options.retry), throwHttpErrors: options.throwHttpErrors !== false, timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout, fetch: options.fetch || globalThis.fetch.bind(globalThis) }; if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) { throw new TypeError('`input` must be a string, URL, or Request'); } if (this._options.prefixUrl && typeof this._input === 'string') { if (this._input.startsWith('/')) { throw new Error('`input` must not begin with a slash when using `prefixUrl`'); } if (!this._options.prefixUrl.endsWith('/')) { this._options.prefixUrl += '/'; } this._input = this._options.prefixUrl + this._input; } if (supportsAbortController) { this.abortController = new globalThis.AbortController(); if (this._options.signal) { this._options.signal.addEventListener('abort', () => { this.abortController.abort(); }); } this._options.signal = this.abortController.signal; } this.request = new globalThis.Request(this._input, this._options); if (this._options.searchParams) { const textSearchParams = typeof this._options.searchParams === 'string' ? this._options.searchParams.replace(/^\?/, '') : new URLSearchParams(this._options.searchParams).toString(); const searchParams = '?' + textSearchParams; const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams); // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one if (((supportsFormData && this._options.body instanceof globalThis.FormData) || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) { this.request.headers.delete('content-type'); } this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options); } if (this._options.json !== undefined) { this._options.body = JSON.stringify(this._options.json); this.request.headers.set('content-type', 'application/json'); this.request = new globalThis.Request(this.request, {body: this._options.body}); } const fn = async () => { if (this._options.timeout > maxSafeTimeout) { throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`); } await delay(1); let response = await this._fetch(); for (const hook of this._options.hooks.afterResponse) { // eslint-disable-next-line no-await-in-loop const modifiedResponse = await hook( this.request, this._options, this._decorateResponse(response.clone()) ); if (modifiedResponse instanceof globalThis.Response) { response = modifiedResponse; } } this._decorateResponse(response); if (!response.ok && this._options.throwHttpErrors) { throw new HTTPError(response, this.request, this._options); } // If `onDownloadProgress` is passed, it uses the stream API internally /* istanbul ignore next */ if (this._options.onDownloadProgress) { if (typeof this._options.onDownloadProgress !== 'function') { throw new TypeError('The `onDownloadProgress` option must be a function'); } if (!supportsStreams) { throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.'); } return this._stream(response.clone(), this._options.onDownloadProgress); } return response; }; const isRetriableMethod = this._options.retry.methods.includes(this.request.method.toLowerCase()); const result = isRetriableMethod ? this._retry(fn) : fn(); for (const [type, mimeType] of Object.entries(responseTypes)) { result[type] = async () => { this.request.headers.set('accept', this.request.headers.get('accept') || mimeType); const response = (await result).clone(); if (type === 'json') { if (response.status === 204) { return ''; } if (options.parseJson) { return options.parseJson(await response.text()); } } return response[type](); }; } return result; } _calculateRetryDelay(error) { this._retryCount++; if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) { if (error instanceof HTTPError) { if (!this._options.retry.statusCodes.includes(error.response.status)) { return 0; } const retryAfter = error.response.headers.get('Retry-After'); if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) { let after = Number(retryAfter); if (Number.isNaN(after)) { after = Date.parse(retryAfter) - Date.now(); } else { after *= 1000; } if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) { return 0; } return after; } if (error.response.status === 413) { return 0; } } const BACKOFF_FACTOR = 0.3; return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000; } return 0; } _decorateResponse(response) { if (this._options.parseJson) { response.json = async () => { return this._options.parseJson(await response.text()); }; } return response; } async _retry(fn) { try { return await fn(); } catch (error) { const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout); if (ms !== 0 && this._retryCount > 0) { await delay(ms); for (const hook of this._options.hooks.beforeRetry) { // eslint-disable-next-line no-await-in-loop const hookResult = await hook({ request: this.request, options: this._options, error, retryCount: this._retryCount }); // If `stop` is returned from the hook, the retry process is stopped if (hookResult === stop) { return; } } return this._retry(fn); } if (this._options.throwHttpErrors) { throw error; } } } async _fetch() { for (const hook of this._options.hooks.beforeRequest) { // eslint-disable-next-line no-await-in-loop const result = await hook(this.request, this._options); if (result instanceof Request) { this.request = result; break; } if (result instanceof Response) { return result; } } if (this._options.timeout === false) { return this._options.fetch(this.request.clone()); } return timeout(this.request.clone(), this.abortController, this._options); } /* istanbul ignore next */ _stream(response, onDownloadProgress) { const totalBytes = Number(response.headers.get('content-length')) || 0; let transferredBytes = 0; return new globalThis.Response( new globalThis.ReadableStream({ async start(controller) { const reader = response.body.getReader(); if (onDownloadProgress) { onDownloadProgress({percent: 0, transferredBytes: 0, totalBytes}, new Uint8Array()); } async function read() { const {done, value} = await reader.read(); if (done) { controller.close(); return; } if (onDownloadProgress) { transferredBytes += value.byteLength; const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes; onDownloadProgress({percent, transferredBytes, totalBytes}, value); } controller.enqueue(value); await read(); } await read(); } }) ); } } const validateAndMerge = (...sources) => { for (const source of sources) { if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') { throw new TypeError('The `options` argument must be an object'); } } return deepMerge({}, ...sources); }; const createInstance = defaults => { const ky = (input, options) => new Ky(input, validateAndMerge(defaults, options)); for (const method of requestMethods) { ky[method] = (input, options) => new Ky(input, validateAndMerge(defaults, options, {method})); } ky.HTTPError = HTTPError; ky.TimeoutError = TimeoutError; ky.create = newDefaults => createInstance(validateAndMerge(newDefaults)); ky.extend = newDefaults => createInstance(validateAndMerge(defaults, newDefaults)); ky.stop = stop; return ky; }; const ky = createInstance(); /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ky); /***/ }), /***/ 4931: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ Ay: () => (/* binding */ Body), /* harmony export */ Or: () => (/* binding */ getTotalBytes), /* harmony export */ jY: () => (/* binding */ extractContentType), /* harmony export */ nR: () => (/* binding */ writeToStream), /* harmony export */ o8: () => (/* binding */ clone) /* harmony export */ }); /* harmony import */ var node_stream__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(7075); /* harmony import */ var node_util__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(7975); /* harmony import */ var node_buffer__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(4573); /* harmony import */ var fetch_blob__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(6327); /* harmony import */ var formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(3018); /* harmony import */ var _errors_fetch_error_js__WEBPACK_IMPORTED_MODULE_7__ = __nccwpck_require__(5156); /* harmony import */ var _errors_base_js__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(750); /* harmony import */ var _utils_is_js__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(1613); /** * Body.js * * Body interface provides common methods for Request and Response */ const pipeline = (0,node_util__WEBPACK_IMPORTED_MODULE_1__.promisify)(node_stream__WEBPACK_IMPORTED_MODULE_0__.pipeline); const INTERNALS = Symbol('Body internals'); /** * Body mixin * * Ref: https://fetch.spec.whatwg.org/#body * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Body { constructor(body, { size = 0 } = {}) { let boundary = null; if (body === null) { // Body is undefined or null body = null; } else if ((0,_utils_is_js__WEBPACK_IMPORTED_MODULE_5__/* .isURLSearchParameters */ .Od)(body)) { // Body is a URLSearchParams body = node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.from(body.toString()); } else if ((0,_utils_is_js__WEBPACK_IMPORTED_MODULE_5__/* .isBlob */ .qf)(body)) { // Body is blob } else if (node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.isBuffer(body)) { // Body is Buffer } else if (node_util__WEBPACK_IMPORTED_MODULE_1__.types.isAnyArrayBuffer(body)) { // Body is ArrayBuffer body = node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.from(body); } else if (ArrayBuffer.isView(body)) { // Body is ArrayBufferView body = node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.from(body.buffer, body.byteOffset, body.byteLength); } else if (body instanceof node_stream__WEBPACK_IMPORTED_MODULE_0__) { // Body is stream } else if (body instanceof formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_4__/* .FormData */ .fS) { // Body is FormData body = (0,formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_4__/* .formDataToBlob */ .$n)(body); boundary = body.type.split('=')[1]; } else { // None of the above // coerce to string then buffer body = node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.from(String(body)); } let stream = body; if (node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.isBuffer(body)) { stream = node_stream__WEBPACK_IMPORTED_MODULE_0__.Readable.from(body); } else if ((0,_utils_is_js__WEBPACK_IMPORTED_MODULE_5__/* .isBlob */ .qf)(body)) { stream = node_stream__WEBPACK_IMPORTED_MODULE_0__.Readable.from(body.stream()); } this[INTERNALS] = { body, stream, boundary, disturbed: false, error: null }; this.size = size; if (body instanceof node_stream__WEBPACK_IMPORTED_MODULE_0__) { body.on('error', error_ => { const error = error_ instanceof _errors_base_js__WEBPACK_IMPORTED_MODULE_6__/* .FetchBaseError */ .o ? error_ : new _errors_fetch_error_js__WEBPACK_IMPORTED_MODULE_7__/* .FetchError */ .f(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_); this[INTERNALS].error = error; }); } } get body() { return this[INTERNALS].stream; } get bodyUsed() { return this[INTERNALS].disturbed; } /** * Decode response as ArrayBuffer * * @return Promise */ async arrayBuffer() { const {buffer, byteOffset, byteLength} = await consumeBody(this); return buffer.slice(byteOffset, byteOffset + byteLength); } async formData() { const ct = this.headers.get('content-type'); if (ct.startsWith('application/x-www-form-urlencoded')) { const formData = new formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_4__/* .FormData */ .fS(); const parameters = new URLSearchParams(await this.text()); for (const [name, value] of parameters) { formData.append(name, value); } return formData; } const {toFormData} = await __nccwpck_require__.e(/* import() */ 101).then(__nccwpck_require__.bind(__nccwpck_require__, 9101)); return toFormData(this.body, ct); } /** * Return raw response as Blob * * @return Promise */ async blob() { const ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || ''; const buf = await this.arrayBuffer(); return new fetch_blob__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .A([buf], { type: ct }); } /** * Decode response as json * * @return Promise */ async json() { const text = await this.text(); return JSON.parse(text); } /** * Decode response as text * * @return Promise */ async text() { const buffer = await consumeBody(this); return new TextDecoder().decode(buffer); } /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody(this); } } Body.prototype.buffer = (0,node_util__WEBPACK_IMPORTED_MODULE_1__.deprecate)(Body.prototype.buffer, 'Please use \'response.arrayBuffer()\' instead of \'response.buffer()\'', 'node-fetch#buffer'); // In browsers, all properties are enumerable. Object.defineProperties(Body.prototype, { body: {enumerable: true}, bodyUsed: {enumerable: true}, arrayBuffer: {enumerable: true}, blob: {enumerable: true}, json: {enumerable: true}, text: {enumerable: true}, data: {get: (0,node_util__WEBPACK_IMPORTED_MODULE_1__.deprecate)(() => {}, 'data doesn\'t exist, use json(), text(), arrayBuffer(), or body instead', 'https://github.com/node-fetch/node-fetch/issues/1000 (response)')} }); /** * Consume and convert an entire Body to a Buffer. * * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body * * @return Promise */ async function consumeBody(data) { if (data[INTERNALS].disturbed) { throw new TypeError(`body used already for: ${data.url}`); } data[INTERNALS].disturbed = true; if (data[INTERNALS].error) { throw data[INTERNALS].error; } const {body} = data; // Body is null if (body === null) { return node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.alloc(0); } /* c8 ignore next 3 */ if (!(body instanceof node_stream__WEBPACK_IMPORTED_MODULE_0__)) { return node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.alloc(0); } // Body is stream // get ready to actually consume the body const accum = []; let accumBytes = 0; try { for await (const chunk of body) { if (data.size > 0 && accumBytes + chunk.length > data.size) { const error = new _errors_fetch_error_js__WEBPACK_IMPORTED_MODULE_7__/* .FetchError */ .f(`content size at ${data.url} over limit: ${data.size}`, 'max-size'); body.destroy(error); throw error; } accumBytes += chunk.length; accum.push(chunk); } } catch (error) { const error_ = error instanceof _errors_base_js__WEBPACK_IMPORTED_MODULE_6__/* .FetchBaseError */ .o ? error : new _errors_fetch_error_js__WEBPACK_IMPORTED_MODULE_7__/* .FetchError */ .f(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error); throw error_; } if (body.readableEnded === true || body._readableState.ended === true) { try { if (accum.every(c => typeof c === 'string')) { return node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.from(accum.join('')); } return node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.concat(accum, accumBytes); } catch (error) { throw new _errors_fetch_error_js__WEBPACK_IMPORTED_MODULE_7__/* .FetchError */ .f(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error); } } else { throw new _errors_fetch_error_js__WEBPACK_IMPORTED_MODULE_7__/* .FetchError */ .f(`Premature close of server response while trying to fetch ${data.url}`); } } /** * Clone body given Res/Req instance * * @param Mixed instance Response or Request instance * @param String highWaterMark highWaterMark for both PassThrough body streams * @return Mixed */ const clone = (instance, highWaterMark) => { let p1; let p2; let {body} = instance[INTERNALS]; // Don't allow cloning a used body if (instance.bodyUsed) { throw new Error('cannot clone body after it is used'); } // Check that body is a stream and not form-data object // note: we can't clone the form-data object without having it as a dependency if ((body instanceof node_stream__WEBPACK_IMPORTED_MODULE_0__) && (typeof body.getBoundary !== 'function')) { // Tee instance body p1 = new node_stream__WEBPACK_IMPORTED_MODULE_0__.PassThrough({highWaterMark}); p2 = new node_stream__WEBPACK_IMPORTED_MODULE_0__.PassThrough({highWaterMark}); body.pipe(p1); body.pipe(p2); // Set instance body to teed body and return the other teed body instance[INTERNALS].stream = p1; body = p2; } return body; }; const getNonSpecFormDataBoundary = (0,node_util__WEBPACK_IMPORTED_MODULE_1__.deprecate)( body => body.getBoundary(), 'form-data doesn\'t follow the spec and requires special treatment. Use alternative package', 'https://github.com/node-fetch/node-fetch/issues/1167' ); /** * Performs the operation "extract a `Content-Type` value from |object|" as * specified in the specification: * https://fetch.spec.whatwg.org/#concept-bodyinit-extract * * This function assumes that instance.body is present. * * @param {any} body Any options.body input * @returns {string | null} */ const extractContentType = (body, request) => { // Body is null or undefined if (body === null) { return null; } // Body is string if (typeof body === 'string') { return 'text/plain;charset=UTF-8'; } // Body is a URLSearchParams if ((0,_utils_is_js__WEBPACK_IMPORTED_MODULE_5__/* .isURLSearchParameters */ .Od)(body)) { return 'application/x-www-form-urlencoded;charset=UTF-8'; } // Body is blob if ((0,_utils_is_js__WEBPACK_IMPORTED_MODULE_5__/* .isBlob */ .qf)(body)) { return body.type || null; } // Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView) if (node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.isBuffer(body) || node_util__WEBPACK_IMPORTED_MODULE_1__.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { return null; } if (body instanceof formdata_polyfill_esm_min_js__WEBPACK_IMPORTED_MODULE_4__/* .FormData */ .fS) { return `multipart/form-data; boundary=${request[INTERNALS].boundary}`; } // Detect form data input from form-data module if (body && typeof body.getBoundary === 'function') { return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; } // Body is stream - can't really do much about this if (body instanceof node_stream__WEBPACK_IMPORTED_MODULE_0__) { return null; } // Body constructor defaults other things to string return 'text/plain;charset=UTF-8'; }; /** * The Fetch Standard treats this as if "total bytes" is a property on the body. * For us, we have to explicitly get it with a function. * * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes * * @param {any} obj.body Body object from the Body instance. * @returns {number | null} */ const getTotalBytes = request => { const {body} = request[INTERNALS]; // Body is null or undefined if (body === null) { return 0; } // Body is Blob if ((0,_utils_is_js__WEBPACK_IMPORTED_MODULE_5__/* .isBlob */ .qf)(body)) { return body.size; } // Body is Buffer if (node_buffer__WEBPACK_IMPORTED_MODULE_2__.Buffer.isBuffer(body)) { return body.length; } // Detect form data input from form-data module if (body && typeof body.getLengthSync === 'function') { return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; } // Body is stream return null; }; /** * Write a Body to a Node.js WritableStream (e.g. http.Request) object. * * @param {Stream.Writable} dest The stream to write to. * @param obj.body Body object from the Body instance. * @returns {Promise} */ const writeToStream = async (dest, {body}) => { if (body === null) { // Body is null dest.end(); } else { // Body is stream await pipeline(body, dest); } }; /***/ }), /***/ 750: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ o: () => (/* binding */ FetchBaseError) /* harmony export */ }); class FetchBaseError extends Error { constructor(message, type) { super(message); // Hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); this.type = type; } get name() { return this.constructor.name; } get [Symbol.toStringTag]() { return this.constructor.name; } } /***/ }), /***/ 5156: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ f: () => (/* binding */ FetchError) /* harmony export */ }); /* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(750); /** * @typedef {{ address?: string, code: string, dest?: string, errno: number, info?: object, message: string, path?: string, port?: number, syscall: string}} SystemError */ /** * FetchError interface for operational errors */ class FetchError extends _base_js__WEBPACK_IMPORTED_MODULE_0__/* .FetchBaseError */ .o { /** * @param {string} message - Error message for human * @param {string} [type] - Error type for machine * @param {SystemError} [systemError] - For Node.js system error */ constructor(message, type, systemError) { super(message, type); // When err.type is `system`, err.erroredSysCall contains system error and err.code contains system error code if (systemError) { // eslint-disable-next-line no-multi-assign this.code = this.errno = systemError.code; this.erroredSysCall = systemError.syscall; } } } /***/ }), /***/ 7557: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ $: () => (/* binding */ fromRawHeaders), /* harmony export */ A: () => (/* binding */ Headers) /* harmony export */ }); /* harmony import */ var node_util__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(7975); /* harmony import */ var node_http__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(7067); /** * Headers.js * * Headers class offers convenient helpers */ /* c8 ignore next 9 */ const validateHeaderName = typeof node_http__WEBPACK_IMPORTED_MODULE_1__.validateHeaderName === 'function' ? node_http__WEBPACK_IMPORTED_MODULE_1__.validateHeaderName : name => { if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); Object.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'}); throw error; } }; /* c8 ignore next 9 */ const validateHeaderValue = typeof node_http__WEBPACK_IMPORTED_MODULE_1__.validateHeaderValue === 'function' ? node_http__WEBPACK_IMPORTED_MODULE_1__.validateHeaderValue : (name, value) => { if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { const error = new TypeError(`Invalid character in header content ["${name}"]`); Object.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'}); throw error; } }; /** * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit */ /** * This Fetch API interface allows you to perform various actions on HTTP request and response headers. * These actions include retrieving, setting, adding to, and removing. * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. * You can add to this using methods like append() (see Examples.) * In all methods of this interface, header names are matched by case-insensitive byte sequence. * */ class Headers extends URLSearchParams { /** * Headers class * * @constructor * @param {HeadersInit} [init] - Response headers */ constructor(init) { // Validate and normalize init object in [name, value(s)][] /** @type {string[][]} */ let result = []; if (init instanceof Headers) { const raw = init.raw(); for (const [name, values] of Object.entries(raw)) { result.push(...values.map(value => [name, value])); } } else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq // No op } else if (typeof init === 'object' && !node_util__WEBPACK_IMPORTED_MODULE_0__.types.isBoxedPrimitive(init)) { const method = init[Symbol.iterator]; // eslint-disable-next-line no-eq-null, eqeqeq if (method == null) { // Record result.push(...Object.entries(init)); } else { if (typeof method !== 'function') { throw new TypeError('Header pairs must be iterable'); } // Sequence> // Note: per spec we have to first exhaust the lists then process them result = [...init] .map(pair => { if ( typeof pair !== 'object' || node_util__WEBPACK_IMPORTED_MODULE_0__.types.isBoxedPrimitive(pair) ) { throw new TypeError('Each header pair must be an iterable object'); } return [...pair]; }).map(pair => { if (pair.length !== 2) { throw new TypeError('Each header pair must be a name/value tuple'); } return [...pair]; }); } } else { throw new TypeError('Failed to construct \'Headers\': The provided value is not of type \'(sequence> or record)'); } // Validate and lowercase result = result.length > 0 ? result.map(([name, value]) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return [String(name).toLowerCase(), String(value)]; }) : undefined; super(result); // Returning a Proxy that will lowercase key names, validate parameters and sort keys // eslint-disable-next-line no-constructor-return return new Proxy(this, { get(target, p, receiver) { switch (p) { case 'append': case 'set': return (name, value) => { validateHeaderName(name); validateHeaderValue(name, String(value)); return URLSearchParams.prototype[p].call( target, String(name).toLowerCase(), String(value) ); }; case 'delete': case 'has': case 'getAll': return name => { validateHeaderName(name); return URLSearchParams.prototype[p].call( target, String(name).toLowerCase() ); }; case 'keys': return () => { target.sort(); return new Set(URLSearchParams.prototype.keys.call(target)).keys(); }; default: return Reflect.get(target, p, receiver); } } }); /* c8 ignore next */ } get [Symbol.toStringTag]() { return this.constructor.name; } toString() { return Object.prototype.toString.call(this); } get(name) { const values = this.getAll(name); if (values.length === 0) { return null; } let value = values.join(', '); if (/^content-encoding$/i.test(name)) { value = value.toLowerCase(); } return value; } forEach(callback, thisArg = undefined) { for (const name of this.keys()) { Reflect.apply(callback, thisArg, [this.get(name), name, this]); } } * values() { for (const name of this.keys()) { yield this.get(name); } } /** * @type {() => IterableIterator<[string, string]>} */ * entries() { for (const name of this.keys()) { yield [name, this.get(name)]; } } [Symbol.iterator]() { return this.entries(); } /** * Node-fetch non-spec method * returning all headers and their values as array * @returns {Record} */ raw() { return [...this.keys()].reduce((result, key) => { result[key] = this.getAll(key); return result; }, {}); } /** * For better console.log(headers) and also to convert Headers into Node.js Request compatible format */ [Symbol.for('nodejs.util.inspect.custom')]() { return [...this.keys()].reduce((result, key) => { const values = this.getAll(key); // Http.request() only supports string as Host header. // This hack makes specifying custom Host header possible. if (key === 'host') { result[key] = values[0]; } else { result[key] = values.length > 1 ? values : values[0]; } return result; }, {}); } } /** * Re-shaping object for Web IDL tests * Only need to do it for overridden methods */ Object.defineProperties( Headers.prototype, ['get', 'entries', 'forEach', 'values'].reduce((result, property) => { result[property] = {enumerable: true}; return result; }, {}) ); /** * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do * not conform to HTTP grammar productions. * @param {import('http').IncomingMessage['rawHeaders']} headers */ function fromRawHeaders(headers = []) { return new Headers( headers // Split into pairs .reduce((result, value, index, array) => { if (index % 2 === 0) { result.push(array.slice(index, index + 2)); } return result; }, []) .filter(([name, value]) => { try { validateHeaderName(name); validateHeaderValue(name, String(value)); return true; } catch { return false; } }) ); } /***/ }), /***/ 5634: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { Ay: () => (/* binding */ fetch) }); // UNUSED EXPORTS: AbortError, Blob, FetchError, File, FormData, Headers, Request, Response, blobFrom, blobFromSync, fileFrom, fileFromSync, isRedirect // EXTERNAL MODULE: external "node:http" var external_node_http_ = __nccwpck_require__(7067); ;// CONCATENATED MODULE: external "node:https" const external_node_https_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https"); // EXTERNAL MODULE: external "node:zlib" var external_node_zlib_ = __nccwpck_require__(8522); // EXTERNAL MODULE: external "node:stream" var external_node_stream_ = __nccwpck_require__(7075); // EXTERNAL MODULE: external "node:buffer" var external_node_buffer_ = __nccwpck_require__(4573); ;// CONCATENATED MODULE: ./node_modules/data-uri-to-buffer/dist/index.js /** * Returns a `Buffer` instance from the given data URI `uri`. * * @param {String} uri Data URI to turn into a Buffer instance * @returns {Buffer} Buffer instance from Data URI * @api public */ function dataUriToBuffer(uri) { if (!/^data:/i.test(uri)) { throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); } // strip newlines uri = uri.replace(/\r?\n/g, ''); // split the URI up into the "metadata" and the "data" portions const firstComma = uri.indexOf(','); if (firstComma === -1 || firstComma <= 4) { throw new TypeError('malformed data: URI'); } // remove the "data:" scheme and parse the metadata const meta = uri.substring(5, firstComma).split(';'); let charset = ''; let base64 = false; const type = meta[0] || 'text/plain'; let typeFull = type; for (let i = 1; i < meta.length; i++) { if (meta[i] === 'base64') { base64 = true; } else if (meta[i]) { typeFull += `;${meta[i]}`; if (meta[i].indexOf('charset=') === 0) { charset = meta[i].substring(8); } } } // defaults to US-ASCII only if type is not provided if (!meta[0] && !charset.length) { typeFull += ';charset=US-ASCII'; charset = 'US-ASCII'; } // get the encoded data portion and decode URI-encoded chars const encoding = base64 ? 'base64' : 'ascii'; const data = unescape(uri.substring(firstComma + 1)); const buffer = Buffer.from(data, encoding); // set `.type` and `.typeFull` properties to MIME type buffer.type = type; buffer.typeFull = typeFull; // set the `.charset` property buffer.charset = charset; return buffer; } /* harmony default export */ const dist = (dataUriToBuffer); //# sourceMappingURL=index.js.map // EXTERNAL MODULE: ./node_modules/node-fetch/src/body.js var src_body = __nccwpck_require__(4931); // EXTERNAL MODULE: ./node_modules/node-fetch/src/response.js var src_response = __nccwpck_require__(348); // EXTERNAL MODULE: ./node_modules/node-fetch/src/headers.js var src_headers = __nccwpck_require__(7557); // EXTERNAL MODULE: ./node_modules/node-fetch/src/request.js + 1 modules var src_request = __nccwpck_require__(6169); // EXTERNAL MODULE: ./node_modules/node-fetch/src/errors/fetch-error.js var fetch_error = __nccwpck_require__(5156); // EXTERNAL MODULE: ./node_modules/node-fetch/src/errors/base.js var base = __nccwpck_require__(750); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/errors/abort-error.js /** * AbortError interface for cancelled requests */ class AbortError extends base/* FetchBaseError */.o { constructor(message, type = 'aborted') { super(message, type); } } // EXTERNAL MODULE: ./node_modules/node-fetch/src/utils/is-redirect.js var is_redirect = __nccwpck_require__(5418); // EXTERNAL MODULE: ./node_modules/formdata-polyfill/esm.min.js var esm_min = __nccwpck_require__(3018); // EXTERNAL MODULE: ./node_modules/node-fetch/src/utils/is.js var is = __nccwpck_require__(1613); // EXTERNAL MODULE: ./node_modules/node-fetch/src/utils/referrer.js var referrer = __nccwpck_require__(478); // EXTERNAL MODULE: ./node_modules/fetch-blob/from.js + 2 modules var from = __nccwpck_require__(9802); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/index.js /** * Index.js * * a request API compatible with window.fetch * * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. */ const supportedSchemas = new Set(['data:', 'http:', 'https:']); /** * Fetch function * * @param {string | URL | import('./request').default} url - Absolute url or Request instance * @param {*} [options_] - Fetch options * @return {Promise} */ async function fetch(url, options_) { return new Promise((resolve, reject) => { // Build request object const request = new src_request/* default */.A(url, options_); const {parsedURL, options} = (0,src_request/* getNodeRequestOptions */.E)(request); if (!supportedSchemas.has(parsedURL.protocol)) { throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, '')}" is not supported.`); } if (parsedURL.protocol === 'data:') { const data = dist(request.url); const response = new src_response/* default */.A(data, {headers: {'Content-Type': data.typeFull}}); resolve(response); return; } // Wrap http.request into fetch const send = (parsedURL.protocol === 'https:' ? external_node_https_namespaceObject : external_node_http_).request; const {signal} = request; let response = null; const abort = () => { const error = new AbortError('The operation was aborted.'); reject(error); if (request.body && request.body instanceof external_node_stream_.Readable) { request.body.destroy(error); } if (!response || !response.body) { return; } response.body.emit('error', error); }; if (signal && signal.aborted) { abort(); return; } const abortAndFinalize = () => { abort(); finalize(); }; // Send request const request_ = send(parsedURL.toString(), options); if (signal) { signal.addEventListener('abort', abortAndFinalize); } const finalize = () => { request_.abort(); if (signal) { signal.removeEventListener('abort', abortAndFinalize); } }; request_.on('error', error => { reject(new fetch_error/* FetchError */.f(`request to ${request.url} failed, reason: ${error.message}`, 'system', error)); finalize(); }); fixResponseChunkedTransferBadEnding(request_, error => { if (response && response.body) { response.body.destroy(error); } }); /* c8 ignore next 18 */ if (process.version < 'v14') { // Before Node.js 14, pipeline() does not fully support async iterators and does not always // properly handle when the socket close/end events are out of order. request_.on('socket', s => { let endedWithEventsCount; s.prependListener('end', () => { endedWithEventsCount = s._eventsCount; }); s.prependListener('close', hadError => { // if end happened before close but the socket didn't emit an error, do it now if (response && endedWithEventsCount < s._eventsCount && !hadError) { const error = new Error('Premature close'); error.code = 'ERR_STREAM_PREMATURE_CLOSE'; response.body.emit('error', error); } }); }); } request_.on('response', response_ => { request_.setTimeout(0); const headers = (0,src_headers/* fromRawHeaders */.$)(response_.rawHeaders); // HTTP fetch step 5 if ((0,is_redirect/* isRedirect */.N)(response_.statusCode)) { // HTTP fetch step 5.2 const location = headers.get('Location'); // HTTP fetch step 5.3 let locationURL = null; try { locationURL = location === null ? null : new URL(location, request.url); } catch { // error here can only be invalid URL in Location: header // do not throw when options.redirect == manual // let the user extract the errorneous redirect URL if (request.redirect !== 'manual') { reject(new fetch_error/* FetchError */.f(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); finalize(); return; } } // HTTP fetch step 5.5 switch (request.redirect) { case 'error': reject(new fetch_error/* FetchError */.f(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); finalize(); return; case 'manual': // Nothing to do break; case 'follow': { // HTTP-redirect fetch step 2 if (locationURL === null) { break; } // HTTP-redirect fetch step 5 if (request.counter >= request.follow) { reject(new fetch_error/* FetchError */.f(`maximum redirect reached at: ${request.url}`, 'max-redirect')); finalize(); return; } // HTTP-redirect fetch step 6 (counter increment) // Create a new Request object. const requestOptions = { headers: new src_headers/* default */.A(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, compress: request.compress, method: request.method, body: (0,src_body/* clone */.o8)(request), signal: request.signal, size: request.size, referrer: request.referrer, referrerPolicy: request.referrerPolicy }; // when forwarding sensitive headers like "Authorization", // "WWW-Authenticate", and "Cookie" to untrusted targets, // headers will be ignored when following a redirect to a domain // that is not a subdomain match or exact match of the initial domain. // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" // will forward the sensitive headers, but a redirect to "bar.com" will not. // headers will also be ignored when following a redirect to a domain using // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com" // will not forward the sensitive headers if (!(0,is/* isDomainOrSubdomain */.MM)(request.url, locationURL) || !(0,is/* isSameProtocol */.Zh)(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOptions.headers.delete(name); } } // HTTP-redirect fetch step 9 if (response_.statusCode !== 303 && request.body && options_.body instanceof external_node_stream_.Readable) { reject(new fetch_error/* FetchError */.f('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); finalize(); return; } // HTTP-redirect fetch step 11 if (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) { requestOptions.method = 'GET'; requestOptions.body = undefined; requestOptions.headers.delete('content-length'); } // HTTP-redirect fetch step 14 const responseReferrerPolicy = (0,referrer/* parseReferrerPolicyFromHeader */.gn)(headers); if (responseReferrerPolicy) { requestOptions.referrerPolicy = responseReferrerPolicy; } // HTTP-redirect fetch step 15 resolve(fetch(new src_request/* default */.A(locationURL, requestOptions))); finalize(); return; } default: return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`)); } } // Prepare response if (signal) { response_.once('end', () => { signal.removeEventListener('abort', abortAndFinalize); }); } let body = (0,external_node_stream_.pipeline)(response_, new external_node_stream_.PassThrough(), error => { if (error) { reject(error); } }); // see https://github.com/nodejs/node/pull/29376 /* c8 ignore next 3 */ if (process.version < 'v12.10') { response_.on('aborted', abortAndFinalize); } const responseOptions = { url: request.url, status: response_.statusCode, statusText: response_.statusMessage, headers, size: request.size, counter: request.counter, highWaterMark: request.highWaterMark }; // HTTP-network fetch step 12.1.1.3 const codings = headers.get('Content-Encoding'); // HTTP-network fetch step 12.1.1.4: handle content codings // in following scenarios we ignore compression support // 1. compression support is disabled // 2. HEAD request // 3. no Content-Encoding header // 4. no content response (204) // 5. content not modified response (304) if (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { response = new src_response/* default */.A(body, responseOptions); resolve(response); return; } // For Node v6+ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. const zlibOptions = { flush: external_node_zlib_.Z_SYNC_FLUSH, finishFlush: external_node_zlib_.Z_SYNC_FLUSH }; // For gzip if (codings === 'gzip' || codings === 'x-gzip') { body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createGunzip(zlibOptions), error => { if (error) { reject(error); } }); response = new src_response/* default */.A(body, responseOptions); resolve(response); return; } // For deflate if (codings === 'deflate' || codings === 'x-deflate') { // Handle the infamous raw deflate response from old servers // a hack for old IIS and Apache servers const raw = (0,external_node_stream_.pipeline)(response_, new external_node_stream_.PassThrough(), error => { if (error) { reject(error); } }); raw.once('data', chunk => { // See http://stackoverflow.com/questions/37519828 if ((chunk[0] & 0x0F) === 0x08) { body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createInflate(), error => { if (error) { reject(error); } }); } else { body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createInflateRaw(), error => { if (error) { reject(error); } }); } response = new src_response/* default */.A(body, responseOptions); resolve(response); }); raw.once('end', () => { // Some old IIS servers return zero-length OK deflate responses, so // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903 if (!response) { response = new src_response/* default */.A(body, responseOptions); resolve(response); } }); return; } // For br if (codings === 'br') { body = (0,external_node_stream_.pipeline)(body, external_node_zlib_.createBrotliDecompress(), error => { if (error) { reject(error); } }); response = new src_response/* default */.A(body, responseOptions); resolve(response); return; } // Otherwise, use response as-is response = new src_response/* default */.A(body, responseOptions); resolve(response); }); // eslint-disable-next-line promise/prefer-await-to-then (0,src_body/* writeToStream */.nR)(request_, request).catch(reject); }); } function fixResponseChunkedTransferBadEnding(request, errorCallback) { const LAST_CHUNK = external_node_buffer_.Buffer.from('0\r\n\r\n'); let isChunkedTransfer = false; let properLastChunkReceived = false; let previousChunk; request.on('response', response => { const {headers} = response; isChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length']; }); request.on('socket', socket => { const onSocketClose = () => { if (isChunkedTransfer && !properLastChunkReceived) { const error = new Error('Premature close'); error.code = 'ERR_STREAM_PREMATURE_CLOSE'; errorCallback(error); } }; const onData = buf => { properLastChunkReceived = external_node_buffer_.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; // Sometimes final 0-length chunk and end of message code are in separate packets if (!properLastChunkReceived && previousChunk) { properLastChunkReceived = ( external_node_buffer_.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && external_node_buffer_.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0 ); } previousChunk = buf; }; socket.prependListener('close', onSocketClose); socket.on('data', onData); request.on('close', () => { socket.removeListener('close', onSocketClose); socket.removeListener('data', onData); }); }); } /***/ }), /***/ 6169: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { // EXPORTS __nccwpck_require__.d(__webpack_exports__, { A: () => (/* binding */ Request), E: () => (/* binding */ getNodeRequestOptions) }); // EXTERNAL MODULE: external "node:url" var external_node_url_ = __nccwpck_require__(3136); // EXTERNAL MODULE: external "node:util" var external_node_util_ = __nccwpck_require__(7975); // EXTERNAL MODULE: ./node_modules/node-fetch/src/headers.js var src_headers = __nccwpck_require__(7557); // EXTERNAL MODULE: ./node_modules/node-fetch/src/body.js var body = __nccwpck_require__(4931); // EXTERNAL MODULE: ./node_modules/node-fetch/src/utils/is.js var is = __nccwpck_require__(1613); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/utils/get-search.js const getSearch = parsedURL => { if (parsedURL.search) { return parsedURL.search; } const lastOffset = parsedURL.href.length - 1; const hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : ''); return parsedURL.href[lastOffset - hash.length] === '?' ? '?' : ''; }; // EXTERNAL MODULE: ./node_modules/node-fetch/src/utils/referrer.js var referrer = __nccwpck_require__(478); ;// CONCATENATED MODULE: ./node_modules/node-fetch/src/request.js /** * Request.js * * Request class contains server only options * * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. */ const INTERNALS = Symbol('Request internals'); /** * Check if `obj` is an instance of Request. * * @param {*} object * @return {boolean} */ const isRequest = object => { return ( typeof object === 'object' && typeof object[INTERNALS] === 'object' ); }; const doBadDataWarn = (0,external_node_util_.deprecate)(() => {}, '.data is not a valid RequestInit property, use .body instead', 'https://github.com/node-fetch/node-fetch/issues/1000 (request)'); /** * Request class * * Ref: https://fetch.spec.whatwg.org/#request-class * * @param Mixed input Url or Request instance * @param Object init Custom options * @return Void */ class Request extends body/* default */.Ay { constructor(input, init = {}) { let parsedURL; // Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245) if (isRequest(input)) { parsedURL = new URL(input.url); } else { parsedURL = new URL(input); input = {}; } if (parsedURL.username !== '' || parsedURL.password !== '') { throw new TypeError(`${parsedURL} is an url with embedded credentials.`); } let method = init.method || input.method || 'GET'; if (/^(delete|get|head|options|post|put)$/i.test(method)) { method = method.toUpperCase(); } if (!isRequest(init) && 'data' in init) { doBadDataWarn(); } // eslint-disable-next-line no-eq-null, eqeqeq if ((init.body != null || (isRequest(input) && input.body !== null)) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } const inputBody = init.body ? init.body : (isRequest(input) && input.body !== null ? (0,body/* clone */.o8)(input) : null); super(inputBody, { size: init.size || input.size || 0 }); const headers = new src_headers/* default */.A(init.headers || input.headers || {}); if (inputBody !== null && !headers.has('Content-Type')) { const contentType = (0,body/* extractContentType */.jY)(inputBody, this); if (contentType) { headers.set('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) { signal = init.signal; } // eslint-disable-next-line no-eq-null, eqeqeq if (signal != null && !(0,is/* isAbortSignal */.L3)(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget'); } // §5.4, Request constructor steps, step 15.1 // eslint-disable-next-line no-eq-null, eqeqeq let referrer = init.referrer == null ? input.referrer : init.referrer; if (referrer === '') { // §5.4, Request constructor steps, step 15.2 referrer = 'no-referrer'; } else if (referrer) { // §5.4, Request constructor steps, step 15.3.1, 15.3.2 const parsedReferrer = new URL(referrer); // §5.4, Request constructor steps, step 15.3.3, 15.3.4 referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer; } else { referrer = undefined; } this[INTERNALS] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal, referrer }; // Node-fetch-only options this.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow; this.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; // §5.4, Request constructor steps, step 16. // Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ''; } /** @returns {string} */ get method() { return this[INTERNALS].method; } /** @returns {string} */ get url() { return (0,external_node_url_.format)(this[INTERNALS].parsedURL); } /** @returns {Headers} */ get headers() { return this[INTERNALS].headers; } get redirect() { return this[INTERNALS].redirect; } /** @returns {AbortSignal} */ get signal() { return this[INTERNALS].signal; } // https://fetch.spec.whatwg.org/#dom-request-referrer get referrer() { if (this[INTERNALS].referrer === 'no-referrer') { return ''; } if (this[INTERNALS].referrer === 'client') { return 'about:client'; } if (this[INTERNALS].referrer) { return this[INTERNALS].referrer.toString(); } return undefined; } get referrerPolicy() { return this[INTERNALS].referrerPolicy; } set referrerPolicy(referrerPolicy) { this[INTERNALS].referrerPolicy = (0,referrer/* validateReferrerPolicy */.cc)(referrerPolicy); } /** * Clone this request * * @return Request */ clone() { return new Request(this); } get [Symbol.toStringTag]() { return 'Request'; } } Object.defineProperties(Request.prototype, { method: {enumerable: true}, url: {enumerable: true}, headers: {enumerable: true}, redirect: {enumerable: true}, clone: {enumerable: true}, signal: {enumerable: true}, referrer: {enumerable: true}, referrerPolicy: {enumerable: true} }); /** * Convert a Request to Node.js http request options. * * @param {Request} request - A Request instance * @return The options object to be passed to http.request */ const getNodeRequestOptions = request => { const {parsedURL} = request[INTERNALS]; const headers = new src_headers/* default */.A(request[INTERNALS].headers); // Fetch step 1.3 if (!headers.has('Accept')) { headers.set('Accept', '*/*'); } // HTTP-network-or-cache fetch steps 2.4-2.7 let contentLengthValue = null; if (request.body === null && /^(post|put)$/i.test(request.method)) { contentLengthValue = '0'; } if (request.body !== null) { const totalBytes = (0,body/* getTotalBytes */.Or)(request); // Set Content-Length if totalBytes is a number (that is not NaN) if (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) { contentLengthValue = String(totalBytes); } } if (contentLengthValue) { headers.set('Content-Length', contentLengthValue); } // 4.1. Main fetch, step 2.6 // > If request's referrer policy is the empty string, then set request's referrer policy to the // > default referrer policy. if (request.referrerPolicy === '') { request.referrerPolicy = referrer/* DEFAULT_REFERRER_POLICY */.L8; } // 4.1. Main fetch, step 2.7 // > If request's referrer is not "no-referrer", set request's referrer to the result of invoking // > determine request's referrer. if (request.referrer && request.referrer !== 'no-referrer') { request[INTERNALS].referrer = (0,referrer/* determineRequestsReferrer */.Ft)(request); } else { request[INTERNALS].referrer = 'no-referrer'; } // 4.5. HTTP-network-or-cache fetch, step 6.9 // > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized // > and isomorphic encoded, to httpRequest's header list. if (request[INTERNALS].referrer instanceof URL) { headers.set('Referer', request.referrer); } // HTTP-network-or-cache fetch step 2.11 if (!headers.has('User-Agent')) { headers.set('User-Agent', 'node-fetch'); } // HTTP-network-or-cache fetch step 2.15 if (request.compress && !headers.has('Accept-Encoding')) { headers.set('Accept-Encoding', 'gzip, deflate, br'); } let {agent} = request; if (typeof agent === 'function') { agent = agent(parsedURL); } // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js const search = getSearch(parsedURL); // Pass the full URL directly to request(), but overwrite the following // options: const options = { // Overwrite search to retain trailing ? (issue #776) path: parsedURL.pathname + search, // The following options are not expressed in the URL method: request.method, headers: headers[Symbol.for('nodejs.util.inspect.custom')](), insecureHTTPParser: request.insecureHTTPParser, agent }; return { /** @type {URL} */ parsedURL, options }; }; /***/ }), /***/ 348: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (/* binding */ Response) /* harmony export */ }); /* harmony import */ var _headers_js__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(7557); /* harmony import */ var _body_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(4931); /* harmony import */ var _utils_is_redirect_js__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(5418); /** * Response.js * * Response class provides content decoding */ const INTERNALS = Symbol('Response internals'); /** * Response class * * Ref: https://fetch.spec.whatwg.org/#response-class * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Response extends _body_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Ay { constructor(body = null, options = {}) { super(body, options); // eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition const status = options.status != null ? options.status : 200; const headers = new _headers_js__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A(options.headers); if (body !== null && !headers.has('Content-Type')) { const contentType = (0,_body_js__WEBPACK_IMPORTED_MODULE_0__/* .extractContentType */ .jY)(body, this); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS] = { type: 'default', url: options.url, status, statusText: options.statusText || '', headers, counter: options.counter, highWaterMark: options.highWaterMark }; } get type() { return this[INTERNALS].type; } get url() { return this[INTERNALS].url || ''; } get status() { return this[INTERNALS].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS].status >= 200 && this[INTERNALS].status < 300; } get redirected() { return this[INTERNALS].counter > 0; } get statusText() { return this[INTERNALS].statusText; } get headers() { return this[INTERNALS].headers; } get highWaterMark() { return this[INTERNALS].highWaterMark; } /** * Clone this response * * @return Response */ clone() { return new Response((0,_body_js__WEBPACK_IMPORTED_MODULE_0__/* .clone */ .o8)(this, this.highWaterMark), { type: this.type, url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected, size: this.size, highWaterMark: this.highWaterMark }); } /** * @param {string} url The URL that the new response is to originate from. * @param {number} status An optional status code for the response (e.g., 302.) * @returns {Response} A Response object. */ static redirect(url, status = 302) { if (!(0,_utils_is_redirect_js__WEBPACK_IMPORTED_MODULE_2__/* .isRedirect */ .N)(status)) { throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); } return new Response(null, { headers: { location: new URL(url).toString() }, status }); } static error() { const response = new Response(null, {status: 0, statusText: ''}); response[INTERNALS].type = 'error'; return response; } static json(data = undefined, init = {}) { const body = JSON.stringify(data); if (body === undefined) { throw new TypeError('data is not JSON serializable'); } const headers = new _headers_js__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A(init && init.headers); if (!headers.has('content-type')) { headers.set('content-type', 'application/json'); } return new Response(body, { ...init, headers }); } get [Symbol.toStringTag]() { return 'Response'; } } Object.defineProperties(Response.prototype, { type: {enumerable: true}, url: {enumerable: true}, status: {enumerable: true}, ok: {enumerable: true}, redirected: {enumerable: true}, statusText: {enumerable: true}, headers: {enumerable: true}, clone: {enumerable: true} }); /***/ }), /***/ 5418: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ N: () => (/* binding */ isRedirect) /* harmony export */ }); const redirectStatus = new Set([301, 302, 303, 307, 308]); /** * Redirect code matching * * @param {number} code - Status code * @return {boolean} */ const isRedirect = code => { return redirectStatus.has(code); }; /***/ }), /***/ 1613: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ L3: () => (/* binding */ isAbortSignal), /* harmony export */ MM: () => (/* binding */ isDomainOrSubdomain), /* harmony export */ Od: () => (/* binding */ isURLSearchParameters), /* harmony export */ Zh: () => (/* binding */ isSameProtocol), /* harmony export */ qf: () => (/* binding */ isBlob) /* harmony export */ }); /** * Is.js * * Object type checks. */ const NAME = Symbol.toStringTag; /** * Check if `obj` is a URLSearchParams object * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143 * @param {*} object - Object to check for * @return {boolean} */ const isURLSearchParameters = object => { return ( typeof object === 'object' && typeof object.append === 'function' && typeof object.delete === 'function' && typeof object.get === 'function' && typeof object.getAll === 'function' && typeof object.has === 'function' && typeof object.set === 'function' && typeof object.sort === 'function' && object[NAME] === 'URLSearchParams' ); }; /** * Check if `object` is a W3C `Blob` object (which `File` inherits from) * @param {*} object - Object to check for * @return {boolean} */ const isBlob = object => { return ( object && typeof object === 'object' && typeof object.arrayBuffer === 'function' && typeof object.type === 'string' && typeof object.stream === 'function' && typeof object.constructor === 'function' && /^(Blob|File)$/.test(object[NAME]) ); }; /** * Check if `obj` is an instance of AbortSignal. * @param {*} object - Object to check for * @return {boolean} */ const isAbortSignal = object => { return ( typeof object === 'object' && ( object[NAME] === 'AbortSignal' || object[NAME] === 'EventTarget' ) ); }; /** * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of * the parent domain. * * Both domains must already be in canonical form. * @param {string|URL} original * @param {string|URL} destination */ const isDomainOrSubdomain = (destination, original) => { const orig = new URL(original).hostname; const dest = new URL(destination).hostname; return orig === dest || orig.endsWith(`.${dest}`); }; /** * isSameProtocol reports whether the two provided URLs use the same protocol. * * Both domains must already be in canonical form. * @param {string|URL} original * @param {string|URL} destination */ const isSameProtocol = (destination, original) => { const orig = new URL(original).protocol; const dest = new URL(destination).protocol; return orig === dest; }; /***/ }), /***/ 478: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ Ft: () => (/* binding */ determineRequestsReferrer), /* harmony export */ L8: () => (/* binding */ DEFAULT_REFERRER_POLICY), /* harmony export */ cc: () => (/* binding */ validateReferrerPolicy), /* harmony export */ gn: () => (/* binding */ parseReferrerPolicyFromHeader) /* harmony export */ }); /* unused harmony exports stripURLForUseAsAReferrer, ReferrerPolicy, isOriginPotentiallyTrustworthy, isUrlPotentiallyTrustworthy */ /* harmony import */ var node_net__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(7030); /** * @external URL * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL} */ /** * @module utils/referrer * @private */ /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy §8.4. Strip url for use as a referrer} * @param {string} URL * @param {boolean} [originOnly=false] */ function stripURLForUseAsAReferrer(url, originOnly = false) { // 1. If url is null, return no referrer. if (url == null) { // eslint-disable-line no-eq-null, eqeqeq return 'no-referrer'; } url = new URL(url); // 2. If url's scheme is a local scheme, then return no referrer. if (/^(about|blob|data):$/.test(url.protocol)) { return 'no-referrer'; } // 3. Set url's username to the empty string. url.username = ''; // 4. Set url's password to null. // Note: `null` appears to be a mistake as this actually results in the password being `"null"`. url.password = ''; // 5. Set url's fragment to null. // Note: `null` appears to be a mistake as this actually results in the fragment being `"#null"`. url.hash = ''; // 6. If the origin-only flag is true, then: if (originOnly) { // 6.1. Set url's path to null. // Note: `null` appears to be a mistake as this actually results in the path being `"/null"`. url.pathname = ''; // 6.2. Set url's query to null. // Note: `null` appears to be a mistake as this actually results in the query being `"?null"`. url.search = ''; } // 7. Return url. return url; } /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy} */ const ReferrerPolicy = new Set([ '', 'no-referrer', 'no-referrer-when-downgrade', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin', 'unsafe-url' ]); /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy} */ const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin'; /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy §3. Referrer Policies} * @param {string} referrerPolicy * @returns {string} referrerPolicy */ function validateReferrerPolicy(referrerPolicy) { if (!ReferrerPolicy.has(referrerPolicy)) { throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); } return referrerPolicy; } /** * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy §3.2. Is origin potentially trustworthy?} * @param {external:URL} url * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" */ function isOriginPotentiallyTrustworthy(url) { // 1. If origin is an opaque origin, return "Not Trustworthy". // Not applicable // 2. Assert: origin is a tuple origin. // Not for implementations // 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy". if (/^(http|ws)s:$/.test(url.protocol)) { return true; } // 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy". const hostIp = url.host.replace(/(^\[)|(]$)/g, ''); const hostIPVersion = (0,node_net__WEBPACK_IMPORTED_MODULE_0__.isIP)(hostIp); if (hostIPVersion === 4 && /^127\./.test(hostIp)) { return true; } if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { return true; } // 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy". // We are returning FALSE here because we cannot ensure conformance to // let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost) if (url.host === 'localhost' || url.host.endsWith('.localhost')) { return false; } // 6. If origin's scheme component is file, return "Potentially Trustworthy". if (url.protocol === 'file:') { return true; } // 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy". // Not supported // 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy". // Not supported // 9. Return "Not Trustworthy". return false; } /** * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy §3.3. Is url potentially trustworthy?} * @param {external:URL} url * @returns `true`: "Potentially Trustworthy", `false`: "Not Trustworthy" */ function isUrlPotentiallyTrustworthy(url) { // 1. If url is "about:blank" or "about:srcdoc", return "Potentially Trustworthy". if (/^about:(blank|srcdoc)$/.test(url)) { return true; } // 2. If url's scheme is "data", return "Potentially Trustworthy". if (url.protocol === 'data:') { return true; } // Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were // created. Therefore, blobs created in a trustworthy origin will themselves be potentially // trustworthy. if (/^(blob|filesystem):$/.test(url.protocol)) { return true; } // 3. Return the result of executing §3.2 Is origin potentially trustworthy? on url's origin. return isOriginPotentiallyTrustworthy(url); } /** * Modifies the referrerURL to enforce any extra security policy considerations. * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 * @callback module:utils/referrer~referrerURLCallback * @param {external:URL} referrerURL * @returns {external:URL} modified referrerURL */ /** * Modifies the referrerOrigin to enforce any extra security policy considerations. * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer}, step 7 * @callback module:utils/referrer~referrerOriginCallback * @param {external:URL} referrerOrigin * @returns {external:URL} modified referrerOrigin */ /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy §8.3. Determine request's Referrer} * @param {Request} request * @param {object} o * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback * @returns {external:URL} Request's referrer */ function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) { // There are 2 notes in the specification about invalid pre-conditions. We return null, here, for // these cases: // > Note: If request's referrer is "no-referrer", Fetch will not call into this algorithm. // > Note: If request's referrer policy is the empty string, Fetch will not call into this // > algorithm. if (request.referrer === 'no-referrer' || request.referrerPolicy === '') { return null; } // 1. Let policy be request's associated referrer policy. const policy = request.referrerPolicy; // 2. Let environment be request's client. // not applicable to node.js // 3. Switch on request's referrer: if (request.referrer === 'about:client') { return 'no-referrer'; } // "a URL": Let referrerSource be request's referrer. const referrerSource = request.referrer; // 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer. let referrerURL = stripURLForUseAsAReferrer(referrerSource); // 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the // origin-only flag set to true. let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); // 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set // referrerURL to referrerOrigin. if (referrerURL.toString().length > 4096) { referrerURL = referrerOrigin; } // 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary // policy considerations in the interests of minimizing data leakage. For example, the user // agent could strip the URL down to an origin, modify its host, replace it with an empty // string, etc. if (referrerURLCallback) { referrerURL = referrerURLCallback(referrerURL); } if (referrerOriginCallback) { referrerOrigin = referrerOriginCallback(referrerOrigin); } // 8.Execute the statements corresponding to the value of policy: const currentURL = new URL(request.url); switch (policy) { case 'no-referrer': return 'no-referrer'; case 'origin': return referrerOrigin; case 'unsafe-url': return referrerURL; case 'strict-origin': // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a // potentially trustworthy URL, then return no referrer. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return 'no-referrer'; } // 2. Return referrerOrigin. return referrerOrigin.toString(); case 'strict-origin-when-cross-origin': // 1. If the origin of referrerURL and the origin of request's current URL are the same, then // return referrerURL. if (referrerURL.origin === currentURL.origin) { return referrerURL; } // 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a // potentially trustworthy URL, then return no referrer. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return 'no-referrer'; } // 3. Return referrerOrigin. return referrerOrigin; case 'same-origin': // 1. If the origin of referrerURL and the origin of request's current URL are the same, then // return referrerURL. if (referrerURL.origin === currentURL.origin) { return referrerURL; } // 2. Return no referrer. return 'no-referrer'; case 'origin-when-cross-origin': // 1. If the origin of referrerURL and the origin of request's current URL are the same, then // return referrerURL. if (referrerURL.origin === currentURL.origin) { return referrerURL; } // Return referrerOrigin. return referrerOrigin; case 'no-referrer-when-downgrade': // 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a // potentially trustworthy URL, then return no referrer. if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { return 'no-referrer'; } // 2. Return referrerURL. return referrerURL; default: throw new TypeError(`Invalid referrerPolicy: ${policy}`); } } /** * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy §8.1. Parse a referrer policy from a Referrer-Policy header} * @param {Headers} headers Response headers * @returns {string} policy */ function parseReferrerPolicyFromHeader(headers) { // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` // and response’s header list. const policyTokens = (headers.get('referrer-policy') || '').split(/[,\s]+/); // 2. Let policy be the empty string. let policy = ''; // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty // string, then set policy to token. // Note: This algorithm loops over multiple policy values to allow deployment of new policy // values with fallbacks for older user agents, as described in § 11.1 Unknown Policy Values. for (const token of policyTokens) { if (token && ReferrerPolicy.has(token)) { policy = token; } } // 4. Return policy. return policy; } /***/ }), /***/ 5582: /***/ ((__webpack_module__, __webpack_exports__, __nccwpck_require__) => { __nccwpck_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { /* harmony export */ __nccwpck_require__.d(__webpack_exports__, { /* harmony export */ A: () => (__WEBPACK_DEFAULT_EXPORT__) /* harmony export */ }); /* harmony import */ var is_url_superb__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(9293); /* harmony import */ var ky_universal__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(2027); var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([ky_universal__WEBPACK_IMPORTED_MODULE_0__]); ky_universal__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; const urlExist = async url => { if (typeof url !== "string") { throw new TypeError(`Expected a string, got ${typeof url}`) } if (!(0,is_url_superb__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .A)(url)) { return false } const response = await ky_universal__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .A.head(url, { throwHttpErrors: false }) return response !== undefined && (response.status < 400 || response.status >= 500) } /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (urlExist); __webpack_async_result__(); } catch(e) { __webpack_async_result__(e); } }); /***/ }), /***/ 8281: /***/ ((__webpack_module__, __unused_webpack___webpack_exports__, __nccwpck_require__) => { __nccwpck_require__.a(__webpack_module__, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try { /* harmony import */ var _actions_core__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(9584); /* harmony import */ var xpath__WEBPACK_IMPORTED_MODULE_1__ = __nccwpck_require__(8408); /* harmony import */ var _xmldom_xmldom__WEBPACK_IMPORTED_MODULE_2__ = __nccwpck_require__(8351); /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_3__ = __nccwpck_require__(9896); /* harmony import */ var url_exist__WEBPACK_IMPORTED_MODULE_4__ = __nccwpck_require__(5582); /* harmony import */ var deep_equal__WEBPACK_IMPORTED_MODULE_5__ = __nccwpck_require__(347); /* harmony import */ var _actions_exec__WEBPACK_IMPORTED_MODULE_6__ = __nccwpck_require__(2876); /* harmony import */ var _actions_http_client__WEBPACK_IMPORTED_MODULE_7__ = __nccwpck_require__(4942); var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([url_exist__WEBPACK_IMPORTED_MODULE_4__]); url_exist__WEBPACK_IMPORTED_MODULE_4__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0]; const client = new _actions_http_client__WEBPACK_IMPORTED_MODULE_7__/* .HttpClient */ .Qq('nextcloud-version-matrix') function versionHashBranch(version) { return (0,url_exist__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A)(`https://github.com/nextcloud/server/tree/stable${version}`); } async function getBranch(version) { if (await versionHashBranch(version)) { return `stable${version}`; } else { return "master"; } } function range(from, to) { return [...Array(to - from + 1).keys()].map(i => i + from); } async function getSupportedVersions(branch) { // yes, this is hacky, but it saves having to keep a list updated let res = await client.get(`https://raw.githubusercontent.com/nextcloud/server/${branch}/lib/versioncheck.php`); let versionCheckCode = await res.readBody(); let min, max; if (versionCheckCode.match(/PHP_VERSION_ID < (\d+)/)) { min = parseVersionId(versionCheckCode.match(/PHP_VERSION_ID < (\d+)/)[1]); max = parseVersionId(versionCheckCode.match(/PHP_VERSION_ID >= (\d+)/)[1]); } else { min = parseFloat(versionCheckCode.match(/PHP_VERSION, '([\d.]+)'\) === -1/)[1]); max = parseFloat(versionCheckCode.match(/PHP_VERSION, '([\d.]+)'\) !== -1/)[1]); } max = parseFloat((max - 0.1).toFixed(1)); return {min: min, max: max}; } function parseVersionId(raw) { let matches = raw.match(/^(\d\d)(\d)/) return parseInt(matches[1], 10) / 10 + parseInt(matches[2], 10) / 10 } async function isPhpVersionReleased(version) { return await (0,url_exist__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .A)(`https://github.com/php/php-src/releases/tag/php-${version.toFixed(1)}.0`); } async function distroSupportsPhpVersion(version) { try { const output = await (0,_actions_exec__WEBPACK_IMPORTED_MODULE_6__/* .getExecOutput */ .H)('apt-cache', ['policy', `php${version}`], {silent: true}); return output.stdout.includes("Candidate") } catch (_e) { return false; } } function onlyUnique(value, index, array) { return array.findIndex(item => deep_equal__WEBPACK_IMPORTED_MODULE_5__(value, item)) === index; } function cartesianProduct(input) { const inputArray = []; for (let key of Object.keys(input)) { const item = {}; item[key] = input[key]; inputArray.push(item); } return cartesianProductInner(inputArray); } // https://stackoverflow.com/a/18959668 function cartesianProductInner(input, current) { if (!input || !input.length) { return []; } let head = input[0]; let tail = input.slice(1); let output = []; for (let key in head) { for (let i = 0; i < head[key].length; i++) { let newCurrent = copy(current); newCurrent[key] = head[key][i]; if (tail.length) { let productOfTail = cartesianProductInner(tail, newCurrent); output = output.concat(productOfTail); } else output.push(newCurrent); } } return output; } function copy(obj) { let res = {}; for (let p in obj) res[p] = obj[p]; return res; } // Formatted according to PHP_VERSION_ID function getPHPVersionID(version) { const parts = version.split('.'); let value = parseInt(parts[0]) * 10000; if (parts.length > 1) { value += parseInt(parts[1]) * 100; } if (parts.length > 2) { value += parseInt(parts[2]); } return value.toString(); } (async () => { try { const filename = _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .getInput */ .V4('filename') || 'appinfo/info.xml'; const matrixInput = JSON.parse(_actions_core__WEBPACK_IMPORTED_MODULE_0__/* .getInput */ .V4('matrix') || '{}'); const withPhpInput = _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .getInput */ .V4('with_php') || '[]'; console.log(withPhpInput); let withPhp = []; if (withPhpInput.startsWith('[') && withPhpInput.endsWith(']')) { withPhp = JSON.parse(withPhpInput); } else { withPhp = [withPhpInput]; } const content = fs__WEBPACK_IMPORTED_MODULE_3__.readFileSync(filename, 'utf8'); const document = new _xmldom_xmldom__WEBPACK_IMPORTED_MODULE_2__/* .DOMParser */ .S4().parseFromString(content, 'text/xml'); const nextcloudMinVersion = parseInt(xpath__WEBPACK_IMPORTED_MODULE_1__.select1("//info//dependencies//nextcloud/@min-version", document).value, 10); const nextcloudMaxVersion = parseInt(xpath__WEBPACK_IMPORTED_MODULE_1__.select1("//info//dependencies//nextcloud/@max-version", document).value, 10); const phpMinVersion = parseFloat(xpath__WEBPACK_IMPORTED_MODULE_1__.select1("//info//dependencies//php/@min-version", document)?.value); const phpMaxVersion = parseFloat(xpath__WEBPACK_IMPORTED_MODULE_1__.select1("//info//dependencies//php/@max-version", document)?.value); console.log(`App supports Nextcloud ${nextcloudMinVersion} till ${nextcloudMaxVersion}`); console.log(`App supports PHP ${phpMinVersion} till ${phpMaxVersion} (NaN = no range limit specified)`); const versions = range(nextcloudMinVersion, nextcloudMaxVersion); // we reverse the order to put highest version first for the "branched off check" let versionData = (await Promise.all(versions.reverse().map(async (version) => { const branch = await getBranch(version); const phpVersionRange = await getSupportedVersions(branch); return { "phpMin": isNaN(phpMinVersion) ? phpVersionRange.min : Math.max(phpVersionRange.min, phpMinVersion), "phpMax": isNaN(phpMaxVersion) ? phpVersionRange.max : Math.min(phpVersionRange.max, phpMaxVersion), "branch": branch, } }))).reverse(); versionData = versionData.filter(data => data.phpMin <= data.phpMax); // matrix with a single php version per server version const serverMatrix = cartesianProduct({ "server-versions": versionData.map(data => data.branch), ...matrixInput }); serverMatrix.forEach(row => { const phpMax = versionData.find(data => data.branch === row["server-versions"]).phpMax; row["php-versions"] = phpMax.toFixed(1); }); for (let extraPhpVersion of withPhp) { serverMatrix.push({ "php-versions": extraPhpVersion, "server-versions": "master", }); } _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("versions", JSON.stringify(versions)); const branches = versionData.map(data => data.branch).filter(onlyUnique); const phpMin = Math.min(...versionData.map(data => data.phpMin)); const phpMax = Math.max(...versionData.map(data => data.phpMax)); const php = withPhp.concat([]); // clone, not alias for(let version = phpMin; version <= phpMax; version += 0.1) { // floats are a pain version = parseFloat(version.toFixed(1)); if (await isPhpVersionReleased(version)) { php.push(version.toFixed(1)); console.log(`Release for PHP Version ${version.toFixed(1)} exists`); } else { // no more minors for this major version = Math.ceil(version) - 0.1; console.log(`No release for PHP Version ${version.toFixed(1)} exists -> skipping`); } } php.sort(); const distroPhp = []; let availablePhp = phpMax; for(let version of php) { if (await distroSupportsPhpVersion(version)) { distroPhp.push(version) availablePhp = version; console.log(`Install candidates for PHP Version ${version} found`); } else { console.log(`No install candidates for PHP version ${version} found -> skipping`); } } // matrix with a single server version per php version const phpMatrix = cartesianProduct({ "php-versions": php, ...matrixInput }); phpMatrix.forEach(row => { const php = row['php-versions']; const candidateVersion = versionData.findLast(data => data.phpMin <= php && data.phpMax >= php); row["server-versions"] = candidateVersion?.branch ?? "master"; }); // matrix with every php and server combination const fullMatrix = cartesianProduct({ "server-versions": versionData.map(data => data.branch), "php-versions": php, ...matrixInput }).filter(row => { const php = row['php-versions']; const version = versionData.find(version => version.branch === row['server-versions']); return version.phpMin <= php && version.phpMax >= php; }); for (let extraPhpVersion of withPhp) { fullMatrix.push({ "php-versions": extraPhpVersion, "server-versions": "master", }); } // matrix with at least one item for every server and php version let testMatrix = phpMatrix.concat(serverMatrix).filter(onlyUnique); console.log(`App supports from php ${phpMin.toFixed(1)} till php ${phpMax.toFixed(1)}`); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("branches", JSON.stringify(branches)); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("ocp-branches", JSON.stringify(branches.map(branch => `dev-${branch}`))); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-versions", JSON.stringify(php)); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-min-list", JSON.stringify([php[0]])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-max-list", JSON.stringify([php[php.length - 1]])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-available-list", JSON.stringify([availablePhp])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("branches-min-list", JSON.stringify([branches[0]])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("branches-max-list", JSON.stringify([branches[branches.length - 1]])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-min", php[0]); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-min-id", getPHPVersionID(php[0])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-max", php[php.length - 1]); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-max-id", getPHPVersionID(php[php.length - 1])); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("php-available", availablePhp); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("branches-min", branches[0]); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("branches-max", branches[branches.length - 1]); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("matrix", JSON.stringify({ include: serverMatrix })); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("sparse-matrix", JSON.stringify({ include: testMatrix })); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("full-matrix", JSON.stringify({ include: fullMatrix })); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setOutput */ .uH("ocp-matrix", JSON.stringify({ include: serverMatrix.map(row => { const ocpVersion = `dev-${row["server-versions"]}`; delete row["server-versions"]; row["ocp-version"] = ocpVersion; return row; }) })); } catch (error) { console.error(error); _actions_core__WEBPACK_IMPORTED_MODULE_0__/* .setFailed */ .C1(error.message); } })() __webpack_async_result__(); } catch(e) { __webpack_async_result__(e); } }); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; /******/ } /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __nccwpck_require__.m = __webpack_modules__; /******/ /************************************************************************/ /******/ /* webpack/runtime/async module */ /******/ (() => { /******/ var webpackQueues = typeof Symbol === "function" ? Symbol("webpack queues") : "__webpack_queues__"; /******/ var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__"; /******/ var webpackError = typeof Symbol === "function" ? Symbol("webpack error") : "__webpack_error__"; /******/ var resolveQueue = (queue) => { /******/ if(queue && queue.d < 1) { /******/ queue.d = 1; /******/ queue.forEach((fn) => (fn.r--)); /******/ queue.forEach((fn) => (fn.r-- ? fn.r++ : fn())); /******/ } /******/ } /******/ var wrapDeps = (deps) => (deps.map((dep) => { /******/ if(dep !== null && typeof dep === "object") { /******/ if(dep[webpackQueues]) return dep; /******/ if(dep.then) { /******/ var queue = []; /******/ queue.d = 0; /******/ dep.then((r) => { /******/ obj[webpackExports] = r; /******/ resolveQueue(queue); /******/ }, (e) => { /******/ obj[webpackError] = e; /******/ resolveQueue(queue); /******/ }); /******/ var obj = {}; /******/ obj[webpackQueues] = (fn) => (fn(queue)); /******/ return obj; /******/ } /******/ } /******/ var ret = {}; /******/ ret[webpackQueues] = x => {}; /******/ ret[webpackExports] = dep; /******/ return ret; /******/ })); /******/ __nccwpck_require__.a = (module, body, hasAwait) => { /******/ var queue; /******/ hasAwait && ((queue = []).d = -1); /******/ var depQueues = new Set(); /******/ var exports = module.exports; /******/ var currentDeps; /******/ var outerResolve; /******/ var reject; /******/ var promise = new Promise((resolve, rej) => { /******/ reject = rej; /******/ outerResolve = resolve; /******/ }); /******/ promise[webpackExports] = exports; /******/ promise[webpackQueues] = (fn) => (queue && fn(queue), depQueues.forEach(fn), promise["catch"](x => {})); /******/ module.exports = promise; /******/ body((deps) => { /******/ currentDeps = wrapDeps(deps); /******/ var fn; /******/ var getResult = () => (currentDeps.map((d) => { /******/ if(d[webpackError]) throw d[webpackError]; /******/ return d[webpackExports]; /******/ })) /******/ var promise = new Promise((resolve) => { /******/ fn = () => (resolve(getResult)); /******/ fn.r = 0; /******/ var fnQueue = (q) => (q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn)))); /******/ currentDeps.map((dep) => (dep[webpackQueues](fnQueue))); /******/ }); /******/ return fn.r ? promise : getResult(); /******/ }, (err) => ((err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue))); /******/ queue && queue.d < 0 && (queue.d = 0); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/create fake namespace object */ /******/ (() => { /******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__); /******/ var leafPrototypes; /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 16: return value when it's Promise-like /******/ // mode & 8|1: behave like require /******/ __nccwpck_require__.t = function(value, mode) { /******/ if(mode & 1) value = this(value); /******/ if(mode & 8) return value; /******/ if(typeof value === 'object' && value) { /******/ if((mode & 4) && value.__esModule) return value; /******/ if((mode & 16) && typeof value.then === 'function') return value; /******/ } /******/ var ns = Object.create(null); /******/ __nccwpck_require__.r(ns); /******/ var def = {}; /******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; /******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) { /******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key]))); /******/ } /******/ def['default'] = () => (value); /******/ __nccwpck_require__.d(ns, def); /******/ return ns; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __nccwpck_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/ensure chunk */ /******/ (() => { /******/ __nccwpck_require__.f = {}; /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __nccwpck_require__.e = (chunkId) => { /******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => { /******/ __nccwpck_require__.f[key](chunkId, promises); /******/ return promises; /******/ }, [])); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/get javascript chunk filename */ /******/ (() => { /******/ // This function allow to reference async chunks /******/ __nccwpck_require__.u = (chunkId) => { /******/ // return url for filenames based on template /******/ return "" + chunkId + ".index.mjs"; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __nccwpck_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/compat */ /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; /******/ /******/ /* webpack/runtime/import chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ 792: 0 /******/ }; /******/ /******/ var installChunk = (data) => { /******/ var {ids, modules, runtime} = data; /******/ // add "modules" to the modules object, /******/ // then flag all "ids" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ for(moduleId in modules) { /******/ if(__nccwpck_require__.o(modules, moduleId)) { /******/ __nccwpck_require__.m[moduleId] = modules[moduleId]; /******/ } /******/ } /******/ if(runtime) runtime(__nccwpck_require__); /******/ for(;i < ids.length; i++) { /******/ chunkId = ids[i]; /******/ if(__nccwpck_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[ids[i]] = 0; /******/ } /******/ /******/ } /******/ /******/ __nccwpck_require__.f.j = (chunkId, promises) => { /******/ // import() chunk loading for javascript /******/ var installedChunkData = __nccwpck_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined; /******/ if(installedChunkData !== 0) { // 0 means "already installed". /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ promises.push(installedChunkData[1]); /******/ } else { /******/ if(true) { // all chunks have JS /******/ // setup Promise in chunk cache /******/ var promise = import("./" + __nccwpck_require__.u(chunkId)).then(installChunk, (e) => { /******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined; /******/ throw e; /******/ }); /******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))]) /******/ promises.push(installedChunkData[1] = promise); /******/ } /******/ } /******/ } /******/ }; /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no external install chunk /******/ /******/ // no on chunks loaded /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module used 'module' so it can't be inlined /******/ var __webpack_exports__ = __nccwpck_require__(8281); /******/ __webpack_exports__ = await __webpack_exports__; /******/