(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.EventSource = {}));
})(this, (function (exports) { 'use strict';

    /**
     * An extended version of the `Event` emitted by the `EventSource` object when an error occurs.
     * While the spec does not include any additional properties, we intentionally go beyond the spec
     * and provide some (minimal) additional information to aid in debugging.
     *
     * @public
     */
    class ErrorEvent extends Event {
        /**
         * Constructs a new `ErrorEvent` instance. This is typically not called directly,
         * but rather emitted by the `EventSource` object when an error occurs.
         *
         * @param type - The type of the event (should be "error")
         * @param errorEventInitDict - Optional properties to include in the error event
         */
        constructor(type, errorEventInitDict) {
            var _a, _b;
            super(type);
            this.code = (_a = errorEventInitDict === null || errorEventInitDict === void 0 ? void 0 : errorEventInitDict.code) !== null && _a !== void 0 ? _a : undefined;
            this.message = (_b = errorEventInitDict === null || errorEventInitDict === void 0 ? void 0 : errorEventInitDict.message) !== null && _b !== void 0 ? _b : undefined;
        }
        /**
         * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
         * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
         * we explicitly include the properties in the `inspect` method.
         *
         * This is automatically called by Node.js when you `console.log` an instance of this class.
         *
         * @param _depth - The current depth
         * @param options - The options passed to `util.inspect`
         * @param inspect - The inspect function to use (prevents having to import it from `util`)
         * @returns A string representation of the error
         */
        [Symbol.for('nodejs.util.inspect.custom')](_depth, options, inspect) {
            return inspect(inspectableError(this), options);
        }
        /**
         * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
         * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
         * we explicitly include the properties in the `inspect` method.
         *
         * This is automatically called by Deno when you `console.log` an instance of this class.
         *
         * @param inspect - The inspect function to use (prevents having to import it from `util`)
         * @param options - The options passed to `Deno.inspect`
         * @returns A string representation of the error
         */
        [Symbol.for('Deno.customInspect')](inspect, options) {
            return inspect(inspectableError(this), options);
        }
    }
    /**
     * For environments where DOMException may not exist, we will use a SyntaxError instead.
     * While this isn't strictly according to spec, it is very close.
     *
     * @param message - The message to include in the error
     * @returns A `DOMException` or `SyntaxError` instance
     * @internal
     */
    function syntaxError(message) {
        // If someone can figure out a way to make this work without depending on DOM/Node.js typings,
        // and without casting to `any`, please send a PR 🙏
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const DomException = globalThis.DOMException;
        if (typeof DomException === 'function') {
            return new DomException(message, 'SyntaxError');
        }
        return new SyntaxError(message);
    }
    /**
     * Flatten an error into a single error message string.
     * Unwraps nested errors and joins them with a comma.
     *
     * @param err - The error to flatten
     * @returns A string representation of the error
     * @internal
     */
    function flattenError(err) {
        if (!(err instanceof Error)) {
            return `${err}`;
        }
        if ('errors' in err && Array.isArray(err.errors)) {
            return err.errors.map(flattenError).join(', ');
        }
        if ('cause' in err && err.cause instanceof Error) {
            return `${err}: ${flattenError(err.cause)}`;
        }
        return err.message;
    }
    /**
     * Convert an `ErrorEvent` instance into a plain object for inspection.
     *
     * @param err - The `ErrorEvent` instance to inspect
     * @returns A plain object representation of the error
     * @internal
     */
    function inspectableError(err) {
        return {
            type: err.type,
            message: err.message,
            code: err.code,
            defaultPrevented: err.defaultPrevented,
            cancelable: err.cancelable,
            timeStamp: err.timeStamp,
        };
    }

    /******************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise, SuppressedError, Symbol, Iterator */


    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }

    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m") throw new TypeError("Private method is not writable");
        if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }

    typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };

    var __defProp = Object.defineProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
    class ParseError extends Error {
      constructor(message, options) {
        super(message), __publicField(this, "type"), __publicField(this, "field"), __publicField(this, "value"), __publicField(this, "line"), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
      }
    }
    function noop(_arg) {
    }
    function createParser(callbacks) {
      const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
      let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
      function feed(newChunk) {
        const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
        for (const line of complete)
          parseLine(line);
        incompleteLine = incomplete, isFirstChunk = false;
      }
      function parseLine(line) {
        if (line === "") {
          dispatchEvent();
          return;
        }
        if (line.startsWith(":")) {
          onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
          return;
        }
        const fieldSeparatorIndex = line.indexOf(":");
        if (fieldSeparatorIndex !== -1) {
          const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
          processField(field, value, line);
          return;
        }
        processField(line, "", line);
      }
      function processField(field, value, line) {
        switch (field) {
          case "event":
            eventType = value;
            break;
          case "data":
            data = `${data}${value}
`;
            break;
          case "id":
            id = value.includes("\0") ? void 0 : value;
            break;
          case "retry":
            /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
              new ParseError(`Invalid \`retry\` value: "${value}"`, {
                type: "invalid-retry",
                value,
                line
              })
            );
            break;
          default:
            onError(
              new ParseError(
                `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
                { type: "unknown-field", field, value, line }
              )
            );
            break;
        }
      }
      function dispatchEvent() {
        data.length > 0 && onEvent({
          id,
          event: eventType || void 0,
          // If the data buffer's last character is a U+000A LINE FEED (LF) character,
          // then remove the last character from the data buffer.
          data: data.endsWith(`
`) ? data.slice(0, -1) : data
        }), id = void 0, data = "", eventType = "";
      }
      function reset(options = {}) {
        incompleteLine && options.consume && parseLine(incompleteLine), id = void 0, data = "", eventType = "", incompleteLine = "";
      }
      return { feed, reset };
    }
    function splitLines(chunk) {
      const lines = [];
      let incompleteLine = "";
      const totalLength = chunk.length;
      for (let i = 0; i < totalLength; i++) {
        const char = chunk[i];
        char === "\r" && chunk[i + 1] === `
` ? (lines.push(incompleteLine), incompleteLine = "", i++) : char === "\r" || char === `
` ? (lines.push(incompleteLine), incompleteLine = "") : incompleteLine += char;
      }
      return [lines, incompleteLine];
    }

    var _EventSource_instances, _EventSource_readyState, _EventSource_url, _EventSource_redirectUrl, _EventSource_withCredentials, _EventSource_fetch, _EventSource_reconnectInterval, _EventSource_reconnectTimer, _EventSource_lastEventId, _EventSource_controller, _EventSource_parser, _EventSource_onError, _EventSource_onMessage, _EventSource_onOpen, _EventSource_connect, _EventSource_onFetchResponse, _EventSource_onFetchError, _EventSource_getRequestOptions, _EventSource_onEvent, _EventSource_onRetryChange, _EventSource_failConnection, _EventSource_scheduleReconnect, _EventSource_reconnect;
    /**
     * An `EventSource` instance opens a persistent connection to an HTTP server, which sends events
     * in `text/event-stream` format. The connection remains open until closed by calling `.close()`.
     *
     * @public
     * @example
     * ```js
     * const eventSource = new EventSource('https://example.com/stream')
     * eventSource.addEventListener('error', (error) => {
     *   console.error(error)
     * })
     * eventSource.addEventListener('message', (event) => {
     *  console.log('Received message:', event.data)
     * })
     * ```
     */
    class EventSource extends EventTarget {
        /**
         * Returns the state of this EventSource object's connection. It can have the values described below.
         *
         * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
         *
         * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
         * defined in the TypeScript `dom` library.
         *
         * @public
         */
        get readyState() {
            return __classPrivateFieldGet(this, _EventSource_readyState, "f");
        }
        /**
         * Returns the URL providing the event stream.
         *
         * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
         *
         * @public
         */
        get url() {
            return __classPrivateFieldGet(this, _EventSource_url, "f").href;
        }
        /**
         * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
         *
         * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
         */
        get withCredentials() {
            return __classPrivateFieldGet(this, _EventSource_withCredentials, "f");
        }
        /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
        get onerror() {
            return __classPrivateFieldGet(this, _EventSource_onError, "f");
        }
        set onerror(value) {
            __classPrivateFieldSet(this, _EventSource_onError, value, "f");
        }
        /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
        get onmessage() {
            return __classPrivateFieldGet(this, _EventSource_onMessage, "f");
        }
        set onmessage(value) {
            __classPrivateFieldSet(this, _EventSource_onMessage, value, "f");
        }
        /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
        get onopen() {
            return __classPrivateFieldGet(this, _EventSource_onOpen, "f");
        }
        set onopen(value) {
            __classPrivateFieldSet(this, _EventSource_onOpen, value, "f");
        }
        addEventListener(type, listener, options) {
            const listen = listener;
            super.addEventListener(type, listen, options);
        }
        removeEventListener(type, listener, options) {
            const listen = listener;
            super.removeEventListener(type, listen, options);
        }
        constructor(url, eventSourceInitDict) {
            var _a, _b;
            super();
            _EventSource_instances.add(this);
            /**
             * ReadyState representing an EventSource currently trying to connect
             *
             * @public
             */
            this.CONNECTING = 0;
            /**
             * ReadyState representing an EventSource connection that is open (eg connected)
             *
             * @public
             */
            this.OPEN = 1;
            /**
             * ReadyState representing an EventSource connection that is closed (eg disconnected)
             *
             * @public
             */
            this.CLOSED = 2;
            // PRIVATES FOLLOW
            /**
             * Current connection state
             *
             * @internal
             */
            _EventSource_readyState.set(this, void 0);
            /**
             * Original URL used to connect.
             *
             * Note that this will stay the same even after a redirect.
             *
             * @internal
             */
            _EventSource_url.set(this, void 0);
            /**
             * The destination URL after a redirect. Is reset on reconnection.
             *
             * @internal
             */
            _EventSource_redirectUrl.set(this, void 0);
            /**
             * Whether to include credentials in the request
             *
             * @internal
             */
            _EventSource_withCredentials.set(this, void 0);
            /**
             * The fetch implementation to use
             *
             * @internal
             */
            _EventSource_fetch.set(this, void 0);
            /**
             * The reconnection time in milliseconds
             *
             * @internal
             */
            _EventSource_reconnectInterval.set(this, void 0);
            /**
             * Reference to an ongoing reconnect attempt, if any
             *
             * @internal
             */
            _EventSource_reconnectTimer.set(this, void 0);
            /**
             * The last event ID seen by the EventSource, which will be sent as `Last-Event-ID` in the
             * request headers on a reconnection attempt.
             *
             * @internal
             */
            _EventSource_lastEventId.set(this, null
            /**
             * The AbortController instance used to abort the fetch request
             *
             * @internal
             */
            );
            /**
             * The AbortController instance used to abort the fetch request
             *
             * @internal
             */
            _EventSource_controller.set(this, void 0);
            /**
             * Instance of an EventSource parser (`eventsource-parser` npm module)
             *
             * @internal
             */
            _EventSource_parser.set(this, void 0);
            /**
             * Holds the current error handler, attached through `onerror` property directly.
             * Note that `addEventListener('error', …)` will not be stored here.
             *
             * @internal
             */
            _EventSource_onError.set(this, null
            /**
             * Holds the current message handler, attached through `onmessage` property directly.
             * Note that `addEventListener('message', …)` will not be stored here.
             *
             * @internal
             */
            );
            /**
             * Holds the current message handler, attached through `onmessage` property directly.
             * Note that `addEventListener('message', …)` will not be stored here.
             *
             * @internal
             */
            _EventSource_onMessage.set(this, null
            /**
             * Holds the current open handler, attached through `onopen` property directly.
             * Note that `addEventListener('open', …)` will not be stored here.
             *
             * @internal
             */
            );
            /**
             * Holds the current open handler, attached through `onopen` property directly.
             * Note that `addEventListener('open', …)` will not be stored here.
             *
             * @internal
             */
            _EventSource_onOpen.set(this, null
            /**
             * Connect to the given URL and start receiving events
             *
             * @internal
             */
            );
            /**
             * Handles the fetch response
             *
             * @param response - The Fetch(ish) response
             * @internal
             */
            _EventSource_onFetchResponse.set(this, async (response) => {
                var _a;
                __classPrivateFieldGet(this, _EventSource_parser, "f").reset();
                const { body, redirected, status, headers } = response;
                // [spec] a client can be told to stop reconnecting using the HTTP 204 No Content response code.
                if (status === 204) {
                    // We still need to emit an error event - this mirrors the browser behavior,
                    // and without it there is no way to tell the user that the connection was closed.
                    __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_failConnection).call(this, 'Server sent HTTP 204, not reconnecting', 204);
                    this.close();
                    return;
                }
                // [spec] …Event stream requests can be redirected using HTTP 301 and 307 redirects as with
                // [spec] normal HTTP requests.
                // Spec does not say anything about other redirect codes (302, 308), but this seems an
                // unintended omission, rather than a feature. Browsers will happily redirect on other 3xxs's.
                if (redirected) {
                    __classPrivateFieldSet(this, _EventSource_redirectUrl, new URL(response.url), "f");
                }
                else {
                    __classPrivateFieldSet(this, _EventSource_redirectUrl, undefined, "f");
                }
                // [spec] if res's status is not 200, …, then fail the connection.
                if (status !== 200) {
                    __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_failConnection).call(this, `Non-200 status code (${status})`, status);
                    return;
                }
                // [spec] …or if res's `Content-Type` is not `text/event-stream`, then fail the connection.
                const contentType = headers.get('content-type') || '';
                if (!contentType.startsWith('text/event-stream')) {
                    __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_failConnection).call(this, 'Invalid content type, expected "text/event-stream"', status);
                    return;
                }
                // [spec] …if the readyState attribute is set to a value other than CLOSED…
                if (__classPrivateFieldGet(this, _EventSource_readyState, "f") === this.CLOSED) {
                    return;
                }
                // [spec] …sets the readyState attribute to OPEN and fires an event
                // [spec] …named open at the EventSource object.
                __classPrivateFieldSet(this, _EventSource_readyState, this.OPEN, "f");
                const openEvent = new Event('open');
                (_a = __classPrivateFieldGet(this, _EventSource_onOpen, "f")) === null || _a === void 0 ? void 0 : _a.call(this, openEvent);
                this.dispatchEvent(openEvent);
                // Ensure that the response stream is a web stream
                if (typeof body !== 'object' || !body || !('getReader' in body)) {
                    __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_failConnection).call(this, 'Invalid response body, expected a web ReadableStream', status);
                    this.close(); // This should only happen if `fetch` provided is "faulty" - don't reconnect
                    return;
                }
                const decoder = new TextDecoder();
                const reader = body.getReader();
                let open = true;
                do {
                    const { done, value } = await reader.read();
                    if (value) {
                        __classPrivateFieldGet(this, _EventSource_parser, "f").feed(decoder.decode(value, { stream: !done }));
                    }
                    if (!done) {
                        continue;
                    }
                    open = false;
                    __classPrivateFieldGet(this, _EventSource_parser, "f").reset();
                    __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_scheduleReconnect).call(this);
                } while (open);
            }
            /**
             * Handles rejected requests for the EventSource endpoint
             *
             * @param err - The error from `fetch()`
             * @internal
             */
            );
            /**
             * Handles rejected requests for the EventSource endpoint
             *
             * @param err - The error from `fetch()`
             * @internal
             */
            _EventSource_onFetchError.set(this, (err) => {
                __classPrivateFieldSet(this, _EventSource_controller, undefined, "f");
                // We expect abort errors when the user manually calls `close()` - ignore those
                if (err.name === 'AbortError' || err.type === 'aborted') {
                    return;
                }
                __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_scheduleReconnect).call(this, flattenError(err));
            }
            /**
             * Get request options for the `fetch()` request
             *
             * @returns The request options
             * @internal
             */
            );
            /**
             * Called by EventSourceParser instance when an event has successfully been parsed
             * and is ready to be processed.
             *
             * @param event - The parsed event
             * @internal
             */
            _EventSource_onEvent.set(this, (event) => {
                if (typeof event.id === 'string') {
                    __classPrivateFieldSet(this, _EventSource_lastEventId, event.id, "f");
                }
                const messageEvent = new MessageEvent(event.event || 'message', {
                    data: event.data,
                    origin: __classPrivateFieldGet(this, _EventSource_redirectUrl, "f") ? __classPrivateFieldGet(this, _EventSource_redirectUrl, "f").origin : __classPrivateFieldGet(this, _EventSource_url, "f").origin,
                    lastEventId: event.id || '',
                });
                // The `onmessage` property of the EventSource instance only triggers on messages without an
                // `event` field, or ones that explicitly set `message`.
                if (__classPrivateFieldGet(this, _EventSource_onMessage, "f") && (!event.event || event.event === 'message')) {
                    __classPrivateFieldGet(this, _EventSource_onMessage, "f").call(this, messageEvent);
                }
                this.dispatchEvent(messageEvent);
            }
            /**
             * Called by EventSourceParser instance when a new reconnection interval is received
             * from the EventSource endpoint.
             *
             * @param value - The new reconnection interval in milliseconds
             * @internal
             */
            );
            /**
             * Called by EventSourceParser instance when a new reconnection interval is received
             * from the EventSource endpoint.
             *
             * @param value - The new reconnection interval in milliseconds
             * @internal
             */
            _EventSource_onRetryChange.set(this, (value) => {
                __classPrivateFieldSet(this, _EventSource_reconnectInterval, value, "f");
            }
            /**
             * Handles the process referred to in the EventSource specification as "failing a connection".
             *
             * @param error - The error causing the connection to fail
             * @param code - The HTTP status code, if available
             * @internal
             */
            );
            /**
             * Reconnects to the EventSource endpoint after a disconnect/failure
             *
             * @internal
             */
            _EventSource_reconnect.set(this, () => {
                __classPrivateFieldSet(this, _EventSource_reconnectTimer, undefined, "f");
                // [spec] If the EventSource's readyState attribute is not set to CONNECTING, then return.
                if (__classPrivateFieldGet(this, _EventSource_readyState, "f") !== this.CONNECTING) {
                    return;
                }
                __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_connect).call(this);
            });
            try {
                if (url instanceof URL) {
                    __classPrivateFieldSet(this, _EventSource_url, url, "f");
                }
                else if (typeof url === 'string') {
                    __classPrivateFieldSet(this, _EventSource_url, new URL(url, getBaseURL()), "f");
                }
                else {
                    throw new Error('Invalid URL');
                }
            }
            catch (err) {
                throw syntaxError('An invalid or illegal string was specified');
            }
            __classPrivateFieldSet(this, _EventSource_parser, createParser({
                onEvent: __classPrivateFieldGet(this, _EventSource_onEvent, "f"),
                onRetry: __classPrivateFieldGet(this, _EventSource_onRetryChange, "f"),
            }), "f");
            __classPrivateFieldSet(this, _EventSource_readyState, this.CONNECTING, "f");
            __classPrivateFieldSet(this, _EventSource_reconnectInterval, 3000, "f");
            __classPrivateFieldSet(this, _EventSource_fetch, (_a = eventSourceInitDict === null || eventSourceInitDict === void 0 ? void 0 : eventSourceInitDict.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch, "f");
            __classPrivateFieldSet(this, _EventSource_withCredentials, (_b = eventSourceInitDict === null || eventSourceInitDict === void 0 ? void 0 : eventSourceInitDict.withCredentials) !== null && _b !== void 0 ? _b : false, "f");
            __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_connect).call(this);
        }
        /**
         * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
         *
         * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
         *
         * @public
         */
        close() {
            if (__classPrivateFieldGet(this, _EventSource_reconnectTimer, "f"))
                clearTimeout(__classPrivateFieldGet(this, _EventSource_reconnectTimer, "f"));
            if (__classPrivateFieldGet(this, _EventSource_readyState, "f") === this.CLOSED)
                return;
            if (__classPrivateFieldGet(this, _EventSource_controller, "f"))
                __classPrivateFieldGet(this, _EventSource_controller, "f").abort();
            __classPrivateFieldSet(this, _EventSource_readyState, this.CLOSED, "f");
            __classPrivateFieldSet(this, _EventSource_controller, undefined, "f");
        }
    }
    _EventSource_readyState = new WeakMap(), _EventSource_url = new WeakMap(), _EventSource_redirectUrl = new WeakMap(), _EventSource_withCredentials = new WeakMap(), _EventSource_fetch = new WeakMap(), _EventSource_reconnectInterval = new WeakMap(), _EventSource_reconnectTimer = new WeakMap(), _EventSource_lastEventId = new WeakMap(), _EventSource_controller = new WeakMap(), _EventSource_parser = new WeakMap(), _EventSource_onError = new WeakMap(), _EventSource_onMessage = new WeakMap(), _EventSource_onOpen = new WeakMap(), _EventSource_onFetchResponse = new WeakMap(), _EventSource_onFetchError = new WeakMap(), _EventSource_onEvent = new WeakMap(), _EventSource_onRetryChange = new WeakMap(), _EventSource_reconnect = new WeakMap(), _EventSource_instances = new WeakSet(), _EventSource_connect = function _EventSource_connect() {
        __classPrivateFieldSet(this, _EventSource_readyState, this.CONNECTING, "f");
        __classPrivateFieldSet(this, _EventSource_controller, new AbortController(), "f");
        // Browser tests are failing if we directly call `this.#fetch()`, thus the indirection.
        const fetch = __classPrivateFieldGet(this, _EventSource_fetch, "f");
        fetch(__classPrivateFieldGet(this, _EventSource_url, "f"), __classPrivateFieldGet(this, _EventSource_instances, "m", _EventSource_getRequestOptions).call(this))
            .then(__classPrivateFieldGet(this, _EventSource_onFetchResponse, "f"))
            .catch(__classPrivateFieldGet(this, _EventSource_onFetchError, "f"));
    }, _EventSource_getRequestOptions = function _EventSource_getRequestOptions() {
        var _a;
        const lastEvent = __classPrivateFieldGet(this, _EventSource_lastEventId, "f") ? { 'Last-Event-ID': __classPrivateFieldGet(this, _EventSource_lastEventId, "f") } : undefined;
        const headers = { Accept: 'text/event-stream', ...lastEvent };
        const init = {
            // [spec] Let `corsAttributeState` be `Anonymous`…
            // [spec] …will have their mode set to "cors"…
            mode: 'cors',
            redirect: 'follow',
            headers,
            cache: 'no-store',
            signal: (_a = __classPrivateFieldGet(this, _EventSource_controller, "f")) === null || _a === void 0 ? void 0 : _a.signal,
        };
        // Some environments crash if attempting to set `credentials` where it is not supported,
        // eg on Cloudflare Workers. To avoid this, we only set it in browser-like environments.
        if ('window' in globalThis) {
            // [spec] …and their credentials mode set to "same-origin"
            // [spec] …if the `withCredentials` attribute is `true`, set the credentials mode to "include"…
            init.credentials = this.withCredentials ? 'include' : 'same-origin';
        }
        return init;
    }, _EventSource_failConnection = function _EventSource_failConnection(message, code) {
        var _a;
        // [spec] …if the readyState attribute is set to a value other than CLOSED,
        // [spec] sets the readyState attribute to CLOSED…
        if (__classPrivateFieldGet(this, _EventSource_readyState, "f") !== this.CLOSED) {
            __classPrivateFieldSet(this, _EventSource_readyState, this.CLOSED, "f");
        }
        // [spec] …and fires an event named `error` at the `EventSource` object.
        // [spec] Once the user agent has failed the connection, it does not attempt to reconnect.
        // [spec] > Implementations are especially encouraged to report detailed information
        // [spec] > to their development consoles whenever an error event is fired, since little
        // [spec] > to no information can be made available in the events themselves.
        // Printing to console is not very programatically helpful, though, so we emit a custom event.
        const errorEvent = new ErrorEvent('error', { code, message });
        (_a = __classPrivateFieldGet(this, _EventSource_onError, "f")) === null || _a === void 0 ? void 0 : _a.call(this, errorEvent);
        this.dispatchEvent(errorEvent);
    }, _EventSource_scheduleReconnect = function _EventSource_scheduleReconnect(message, code) {
        var _a;
        // [spec] If the readyState attribute is set to CLOSED, abort the task.
        if (__classPrivateFieldGet(this, _EventSource_readyState, "f") === this.CLOSED) {
            return;
        }
        // [spec] Set the readyState attribute to CONNECTING.
        __classPrivateFieldSet(this, _EventSource_readyState, this.CONNECTING, "f");
        // [spec] Fire an event named `error` at the EventSource object.
        const errorEvent = new ErrorEvent('error', { code, message });
        (_a = __classPrivateFieldGet(this, _EventSource_onError, "f")) === null || _a === void 0 ? void 0 : _a.call(this, errorEvent);
        this.dispatchEvent(errorEvent);
        // [spec] Wait a delay equal to the reconnection time of the event source.
        __classPrivateFieldSet(this, _EventSource_reconnectTimer, setTimeout(__classPrivateFieldGet(this, _EventSource_reconnect, "f"), __classPrivateFieldGet(this, _EventSource_reconnectInterval, "f")), "f");
    };
    /**
     * ReadyState representing an EventSource currently trying to connect
     *
     * @public
     */
    EventSource.CONNECTING = 0;
    /**
     * ReadyState representing an EventSource connection that is open (eg connected)
     *
     * @public
     */
    EventSource.OPEN = 1;
    /**
     * ReadyState representing an EventSource connection that is closed (eg disconnected)
     *
     * @public
     */
    EventSource.CLOSED = 2;
    /**
     * According to spec, when constructing a URL:
     * > 1. Let baseURL be environment's base URL, if environment is a Document object
     * > 2. Return the result of applying the URL parser to url, with baseURL.
     *
     * Thus we should use `document.baseURI` if available, since it can be set through a base tag.
     *
     * @returns The base URL, if available - otherwise `undefined`
     * @internal
     */
    function getBaseURL() {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const doc = 'document' in globalThis ? globalThis.document : undefined;
        return doc && typeof doc === 'object' && 'baseURI' in doc && typeof doc.baseURI === 'string'
            ? doc.baseURI
            : undefined;
    }

    exports.ErrorEvent = ErrorEvent;
    exports.EventSource = EventSource;

}));
