def style(
    text: t.Any,
    fg: int | tuple[int, int, int] | str | None = None,
    bg: int | tuple[int, int, int] | str | None = None,
    bold: bool | None = None,
    dim: bool | None = None,
    underline: bool | None = None,
    overline: bool | None = None,
    italic: bool | None = None,
    blink: bool | None = None,
    reverse: bool | None = None,
    strikethrough: bool | None = None,
    reset: bool = True,
) -> str:
    """Styles a text with ANSI styles and returns the new string.  By
    default the styling is self contained which means that at the end
    of the string a reset code is issued.  This can be prevented by
    passing ``reset=False``.

    Examples::

        click.echo(click.style('Hello World!', fg='green'))
        click.echo(click.style('ATTENTION!', blink=True))
        click.echo(click.style('Some things', reverse=True, fg='cyan'))
        click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))

    Supported color names:

    * ``black`` (might be a gray)
    * ``red``
    * ``green``
    * ``yellow`` (might be an orange)
    * ``blue``
    * ``magenta``
    * ``cyan``
    * ``white`` (might be light gray)
    * ``bright_black``
    * ``bright_red``
    * ``bright_green``
    * ``bright_yellow``
    * ``bright_blue``
    * ``bright_magenta``
    * ``bright_cyan``
    * ``bright_white``
    * ``reset`` (reset the color code only)

    If the terminal supports it, color may also be specified as:

    -   An integer in the interval [0, 255]. The terminal must support
        8-bit/256-color mode.
    -   An RGB tuple of three integers in [0, 255]. The terminal must
        support 24-bit/true-color mode.

    See https://en.wikipedia.org/wiki/ANSI_color and
    https://gist.github.com/XVilka/8346728 for more information.

    :param text: the string to style with ansi codes.
    :param fg: if provided this will become the foreground color.
    :param bg: if provided this will become the background color.
    :param bold: if provided this will enable or disable bold mode.
    :param dim: if provided this will enable or disable dim mode.  This is
                badly supported.
    :param underline: if provided this will enable or disable underline.
    :param overline: if provided this will enable or disable overline.
    :param italic: if provided this will enable or disable italic.
    :param blink: if provided this will enable or disable blinking.
    :param reverse: if provided this will enable or disable inverse
                    rendering (foreground becomes background and the
                    other way round).
    :param strikethrough: if provided this will enable or disable
        striking through text.
    :param reset: by default a reset-all code is added at the end of the
                  string which means that styles do not carry over.  This
                  can be disabled to compose styles.

    .. versionchanged:: 8.0
        A non-string ``message`` is converted to a string.

    .. versionchanged:: 8.0
       Added support for 256 and RGB color codes.

    .. versionchanged:: 8.0
        Added the ``strikethrough``, ``italic``, and ``overline``
        parameters.

    .. versionchanged:: 7.0
        Added support for bright colors.

    .. versionadded:: 2.0
    """
    if not isinstance(text, str):
        text = str(text)

    bits = []

    if fg:
        try:
            bits.append(f"\033[{_interpret_color(fg)}m")
        except KeyError:
            raise TypeError(f"Unknown color {fg!r}") from None

    if bg:
        try:
            bits.append(f"\033[{_interpret_color(bg, 10)}m")
        except KeyError:
            raise TypeError(f"Unknown color {bg!r}") from None

    if bold is not None:
        bits.append(f"\033[{1 if bold else 22}m")
    if dim is not None:
        bits.append(f"\033[{2 if dim else 22}m")
    if underline is not None:
        bits.append(f"\033[{4 if underline else 24}m")
    if overline is not None:
        bits.append(f"\033[{53 if overline else 55}m")
    if italic is not None:
        bits.append(f"\033[{3 if italic else 23}m")
    if blink is not None:
        bits.append(f"\033[{5 if blink else 25}m")
    if reverse is not None:
        bits.append(f"\033[{7 if reverse else 27}m")
    if strikethrough is not None:
        bits.append(f"\033[{9 if strikethrough else 29}m")
    bits.append(text)
    if reset:
        bits.append(_ansi_reset_all)
    return "".join(bits)


def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None:
        self.write("Markup(")
        self.visit(node.expr, frame)
        self.write(")")


function handleResults(results: { ctx: ParseContext; result: SyncParseReturnType<any> }[]) {
      // return first issue-free validation if it exists
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }

      for (const result of results) {
        if (result.result.status === "dirty") {
          // add issues from dirty option

          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }

      // return invalid
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));

      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors,
      });
      return INVALID;
    }


"""
requests.cookies
~~~~~~~~~~~~~~~~

Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.

requests.utils imports from here, so be careful with imports.
"""

import calendar
import copy
import time

from ._internal_utils import to_native_string
from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse

try:
    import threading
except ImportError:
    import dummy_threading as threading

class MockRequest:
    """Wraps a `requests.Request` to mimic a `urllib2.Request`.

    The code in `http.cookiejar.CookieJar` expects this interface in order to correctly
    manage cookie policies, i.e., determine whether a cookie can be set, given the
    domains of the request and the cookie.

    The original request object is read-only. The client is responsible for collecting
    the new headers via `get_new_headers()` and interpreting them appropriately. You
    probably want `get_cookie_header`, defined below.
    """

    def __init__(self, request):
        self._r = request
        self._new_headers = {}
        self.type = urlparse(self._r.url).scheme

    def get_type(self):
        return self.type

    def get_host(self):
        return urlparse(self._r.url).netloc

    def get_origin_req_host(self):
        return self.get_host()

    def get_full_url(self):
        # Only return the response's URL if the user hadn't set the Host
        # header
        if not self._r.headers.get("Host"):
            return self._r.url
        # If they did set it, retrieve it and reconstruct the expected domain
        host = to_native_string(self._r.headers["Host"], encoding="utf-8")
        parsed = urlparse(self._r.url)
        # Reconstruct the URL as we expect it
        return urlunparse(
            [
                parsed.scheme,
                host,
                parsed.path,
                parsed.params,
                parsed.query,
                parsed.fragment,
            ]
        )

    def is_unverifiable(self):
        return True

    def has_header(self, name):
        return name in self._r.headers or name in self._new_headers

    def get_header(self, name, default=None):
        return self._r.headers.get(name, self._new_headers.get(name, default))

    def add_header(self, key, val):
        """cookiejar has no legitimate use for this method; add it back if you find one."""
        raise NotImplementedError(
            "Cookie headers should be added with add_unredirected_header()"
        )

    def add_unredirected_header(self, name, value):
        self._new_headers[name] = value

    def get_new_headers(self):
        return self._new_headers

    @property
    def unverifiable(self):
        return self.is_unverifiable()

    @property
    def origin_req_host(self):
        return self.get_origin_req_host()

    @property
    def host(self):
        return self.get_host()

class MockResponse:
    """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.

    ...what? Basically, expose the parsed HTTP headers from the server response
    the way `http.cookiejar` expects to see them.
    """

    def __init__(self, headers):
        """Make a MockResponse for `cookiejar` to read.

        :param headers: a httplib.HTTPMessage or analogous carrying the headers
        """
        self._headers = headers

    def info(self):
        return self._headers

    def getheaders(self, name):
        self._headers.getheaders(name)

def extract_cookies_to_jar(jar, request, response):
    """Extract the cookies from the response into a CookieJar.

    :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)
    :param request: our own requests.Request object
    :param response: urllib3.HTTPResponse object
    """
    if not (hasattr(response, "_original_response") and response._original_response):
        return
    # the _original_response field is the wrapped httplib.HTTPResponse object,
    req = MockRequest(request)
    # pull out the HTTPMessage with the headers and put it in the mock:
    res = MockResponse(response._original_response.msg)
    jar.extract_cookies(res, req)

def get_cookie_header(jar, request):
    """
    Produce an appropriate Cookie header string to be sent with `request`, or None.

    :rtype: str
    """
    r = MockRequest(request)
    jar.add_cookie_header(r)
    return r.get_new_headers().get("Cookie")

def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
    """Unsets a cookie by name, by default over all domains and paths.

    Wraps CookieJar.clear(), is O(n).
    """
    clearables = []
    for cookie in cookiejar:
        if cookie.name != name:
            continue
        if domain is not None and domain != cookie.domain:
            continue
        if path is not None and path != cookie.path:
            continue
        clearables.append((cookie.domain, cookie.path, cookie.name))

    for domain, path, name in clearables:
        cookiejar.clear(domain, path, name)

class CookieConflictError(RuntimeError):
    """There are two cookies that meet the criteria specified in the cookie jar.
    Use .get and .set and include domain and path args in order to be more specific.
    """

class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
    """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict
    interface.

    This is the CookieJar we create by default for requests and sessions that
    don't specify one, since some clients may expect response.cookies and
    session.cookies to support dict operations.

    Requests does not use the dict interface internally; it's just for
    compatibility with external client code. All requests code should work
    out of the box with externally provided instances of ``CookieJar``, e.g.
    ``LWPCookieJar`` and ``FileCookieJar``.

    Unlike a regular CookieJar, this class is pickleable.

    .. warning:: dictionary operations that are normally O(1) may be O(n).
    """

    def get(self, name, default=None, domain=None, path=None):
        """Dict-like get() that also supports optional domain and path args in
        order to resolve naming collisions from using one cookie jar over
        multiple domains.

        .. warning:: operation is O(n), not O(1).
        """
        try:
            return self._find_no_duplicates(name, domain, path)
        except KeyError:
            return default

    def set(self, name, value, **kwargs):
        """Dict-like set() that also supports optional domain and path args in
        order to resolve naming collisions from using one cookie jar over
        multiple domains.
        """
        # support client code that unsets cookies by assignment of a None value:
        if value is None:
            remove_cookie_by_name(
                self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
            )
            return

        if isinstance(value, Morsel):
            c = morsel_to_cookie(value)
        else:
            c = create_cookie(name, value, **kwargs)
        self.set_cookie(c)
        return c

    def iterkeys(self):
        """Dict-like iterkeys() that returns an iterator of names of cookies
        from the jar.

        .. seealso:: itervalues() and iteritems().
        """
        for cookie in iter(self):
            yield cookie.name

    def keys(self):
        """Dict-like keys() that returns a list of names of cookies from the
        jar.

        .. seealso:: values() and items().
        """
        return list(self.iterkeys())

    def itervalues(self):
        """Dict-like itervalues() that returns an iterator of values of cookies
        from the jar.

        .. seealso:: iterkeys() and iteritems().
        """
        for cookie in iter(self):
            yield cookie.value

    def values(self):
        """Dict-like values() that returns a list of values of cookies from the
        jar.

        .. seealso:: keys() and items().
        """
        return list(
# … (truncated at 8000 chars)


function createInitialState(arraySize = BENCHMARK_CONFIG.arraySize) {
	const initialState = {
		largeArray: Array.from({length: arraySize}, (_, i) => ({
			id: i,
			value: Math.random(),
			nested: {key: `key-${i}`, data: Math.random()},
			moreNested: {
				items: Array.from(
					{length: BENCHMARK_CONFIG.nestedArraySize},
					(_, i) => ({id: i, name: String(i)})
				)
			}
		})),
		otherData: Array.from({length: arraySize}, (_, i) => ({
			id: i,
			name: `name-${i}`,
			isActive: i % 2 === 0
		})),
		largeObject1: createLargeObject(BENCHMARK_CONFIG.largeObjectSize1),
		largeObject2: createLargeObject(BENCHMARK_CONFIG.largeObjectSize2),
		api: {
			queries: {},
			provided: {
				keys: {}
			},
			subscriptions: {}
		}
	}
	return initialState
}


writeResponseBody onErrorCallback sseStreamProducer unstable_localLink generatorWithErrorHandling

export function isAbortError(
  error: unknown,
): error is DOMException | Error | { name: 'AbortError' } {
  return isObject(error) && error['name'] === 'AbortError';
}


export function createTRPCHeyApiClientConfig(opts?: TRPCHeyApiClientOptions) {
  const transformer = opts?.transformer
    ? resolveTransformer(opts.transformer)
    : undefined;

  return {
    querySerializer: (query: Record<string, unknown>) => {
      const params = new URLSearchParams();

      for (const [key, value] of Object.entries(query)) {
        if (value === undefined) {
          continue;
        }

        if (key === 'input' && transformer) {
          params.append(
            key,
            JSON.stringify(transformer.input.serialize(value)),
          );
        } else {
          params.append(key, JSON.stringify(value));
        }
      }

      return params.toString();
    },

    ...(transformer && {
      bodySerializer: (body: unknown) => {
        return JSON.stringify(transformer.input.serialize(body));
      },

      responseTransformer: async (data: unknown) => {
        if (!!data && typeof data === 'object' && 'result' in data) {
          const result = (data as any).result;
          if (!result.type || result.type === 'data') {
            result.data = transformer.output.deserialize(result.data);
          }
        }

        return data;
      },
    }),
  } as const satisfies TRPCHeyApiClientConfig;
}


get maxHeaderSize() {
		return this.#internals.maxHeaderSize;
	}


export function string<T = unknown>(params?: string | core.$ZodStringParams): ZodCoercedString<T> {
  return core._coercedString(schemas.ZodString, params) as any;
}


def reset_all(self) -> None:
        """
        Go through all stats entries and reset them to zero
        """
        self.total.reset()
        self.errors = {}
        for r in self.entries.values():
            r.reset()
        self.history = []


export function readQueryKey(queryKey: AnyTRPCQueryKey) {
  if (isPrefixedQueryKey(queryKey)) {
    return {
      type: 'prefixed' as const,
      prefix: queryKey[0],
      path: queryKey[1],
      args: queryKey[2],
    };
  } else {
    return {
      type: 'unprefixed' as const,
      prefix: undefined,
      path: queryKey[0],
      args: queryKey[1],
    };
  }
}


query setMutationDefaults getClientArgs createTRPCOptionsResult mutation isAsyncIterable getUntypedClient

export function createTRPCQueryUtils<TRouter extends AnyRouter>(
  opts: CreateQueryUtilsOptions<TRouter>,
) {
  const utils = createUtilityFunctions(opts);
  return createQueryUtilsProxy<TRouter>(utils);
}


def callable_from_ref(ref: str) -> Callable:
    """
    Return the callable pointed to by ``ref``.

    :raises DeserializationError: if the reference could not be resolved or the looked
        up object is not callable

    """
    if ":" not in ref:
        raise ValueError(f"Invalid reference: {ref}")

    modulename, rest = ref.split(":", 1)
    try:
        obj = __import__(modulename, fromlist=[rest])
    except ImportError as exc:
        raise LookupError(
            f"Error resolving reference {ref!r}: could not import module"
        ) from exc

    try:
        for name in rest.split("."):
            obj = getattr(obj, name)
    except Exception as exc:
        raise DeserializationError(
            f"Error resolving reference {ref!r}: error looking up object"
        ) from exc

    if not callable(obj):
        raise DeserializationError(
            f"{ref!r} points to an object of type "
            f"{obj.__class__.__qualname__} which is not callable"
        )

    return obj


@classmethod
    def dependents_key_for(cls, job_id: str) -> str:
        """The Redis key that is used to store job dependents hash under.

        Args:
            job_id (str): The "parent" job id

        Returns:
            dependents_key (str): The dependents key
        """
        return f'{cls.redis_job_namespace_prefix}{job_id}:dependents'


def on_state_change(self, meta, message):
        if self.on_message:
            self.on_message(meta)
        if meta['status'] in states.READY_STATES:
            task_id = meta['task_id']
            try:
                result = self._get_pending_result(task_id)
            except KeyError:
                # send to buffer in case we received this result
                # before it was added to _pending_results.
                self._pending_messages.put(task_id, meta)
            else:
                result._maybe_set_cache(meta)
                buckets = self.buckets
                try:
                    # remove bucket for this result, since it's fulfilled
                    bucket = buckets.pop(result)
                except KeyError:
                    pass
                else:
                    # send to waiter via bucket
                    bucket.append(result)
        sleep(0)

"""Async I/O backend support utilities."""

import logging
import socket
import threading
import time
from collections import deque
from contextlib import contextmanager
from queue import Empty
from time import sleep
from weakref import WeakKeyDictionary

from kombu.utils.compat import detect_environment

from celery import states
from celery.exceptions import TimeoutError
from celery.utils.log import get_logger
from celery.utils.threads import THREAD_TIMEOUT_MAX

E_CELERY_RESTART_REQUIRED = "Celery must be restarted because a shutdown signal was detected."

E_RETRY_LIMIT_EXCEEDED = """
Retry limit exceeded while trying to reconnect to the Celery result store
backend. The Celery application must be restarted.
"""

logger = get_logger(__name__)

__all__ = (
    'AsyncBackendMixin', 'BaseResultConsumer', 'Drainer',
    'register_drainer',
)

class EventletAdaptedEvent:
    """
    An adapted eventlet event, designed to match the API of `threading.Event` and
    `gevent.event.Event`.
    """

    def __init__(self):
        import eventlet
        self.evt = eventlet.Event()

    def is_set(self):
        return self.evt.ready()

    def set(self):
        return self.evt.send()

    def wait(self, timeout=None):
        return self.evt.wait(timeout)

drainers = {}

def register_drainer(name):
    """Decorator used to register a new result drainer type."""
    def _inner(cls):
        drainers[name] = cls
        return cls
    return _inner

@register_drainer('default')
class Drainer:
    """Result draining service."""

    def __init__(self, result_consumer):
        self.result_consumer = result_consumer

    def start(self):
        pass

    def stop(self):
        pass

    def drain_events_until(self, p, timeout=None, interval=1, on_interval=None, wait=None):
        wait = wait or self.result_consumer.drain_events
        time_start = time.monotonic()

        while 1:
            # Total time spent may exceed a single call to wait()
            if timeout and time.monotonic() - time_start >= timeout:
                raise socket.timeout()
            try:
                yield self.wait_for(p, wait, timeout=interval)
            except socket.timeout:
                pass
            except OSError:
                # Recoverable connection error (e.g. broker restart).
                # drain_events handles reconnection internally; if an
                # OSError still leaks through, we log, sleep for one
                # interval, and continue rather than spinning hot.
                logging.warning(
                    'Drainer: connection error during drain_events, '
                    'will retry on next loop iteration.',
                    exc_info=True,
                )
                time.sleep(interval)

            if on_interval:
                on_interval()
            if p.ready:  # got event on the wanted channel.
                break

    def wait_for(self, p, wait, timeout=None):
        wait(timeout=timeout)

    def _event(self):
        return threading.Event()

class greenletDrainer(Drainer):
    spawn = None
    _exc = None
    _g = None
    _drain_complete_event = None    # event, sended (and recreated) after every drain_events iteration

    def _send_drain_complete_event(self):
        self._drain_complete_event.set()
        self._drain_complete_event = self._event()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._started = self._event()
        self._stopped = self._event()
        self._shutdown = self._event()
        self._drain_complete_event = self._event()

    def run(self):
        self._started.set()

        try:
            while not self._stopped.is_set():
                try:
                    self.result_consumer.drain_events(timeout=1)
                    self._send_drain_complete_event()
                except socket.timeout:
                    pass
                except OSError:
                    # Recoverable connection errors (e.g. broker restart)
                    # are handled inside drain_events via reconnection.
                    # If something still leaks through, we log, back off
                    # briefly, and retry instead of spinning hot.
                    logging.warning(
                        'Drainer: connection error during drain_events, '
                        'will retry on next loop iteration.',
                        exc_info=True,
                    )
                    time.sleep(1)
        except Exception as e:
            self._exc = e
            raise
        finally:
            self._send_drain_complete_event()
            try:
                self._shutdown.set()
            except RuntimeError as e:
                logging.error(f"Failed to set shutdown event: {e}")

    def start(self):
        self._ensure_not_shut_down()

        if not self._started.is_set():
            self._g = self.spawn(self.run)
            self._started.wait()

    def stop(self):
        self._stopped.set()
        self._shutdown.wait(THREAD_TIMEOUT_MAX)

    def wait_for(self, p, wait, timeout=None):
        self.start()
        if not p.ready:
            self._drain_complete_event.wait(timeout=timeout)

            self._ensure_not_shut_down()

    def _ensure_not_shut_down(self):
        """Currently used to ensure the drainer has not run to completion.

        Raises if the shutdown event has been signaled (either due to an exception
        or stop() being called).

        The _shutdown event acts as synchronization to ensure _exc is properly
        set before it is read from, avoiding need for locks.
        """
        if self._shutdown.is_set():
            if self._exc is not None:
                raise self._exc
            else:
                raise Exception(E_CELERY_RESTART_REQUIRED)

@register_drainer('eventlet')
class eventletDrainer(greenletDrainer):

    def spawn(self, func):
        from eventlet import sleep, spawn
        g = spawn(func)
        sleep(0)
        return g

    def _event(self):
        return EventletAdaptedEvent()

@register_drainer('gevent')
class geventDrainer(greenletDrainer):

    def spawn(self, func):
        import gevent
        g = gevent.spawn(func)
        gevent.sleep(0)
        return g

    def _event(self):
        from gevent.event import Event
        return Event()

class AsyncBackendMixin:
    """Mixin for backends that enables the async API."""

    def _collect_into(self, result, bucket):
        self.result_consumer.buckets[result] = bucket

    def iter_native(self, result, no_ack=True, **kwargs):
        self._ensure_not_eager()

        results = result.results
        if not results:
            raise StopIteration()

        # we tell the result consumer to put consumed results
        # into these buckets.
        bucket = deque()
        for node in results:
            if not hasattr(node, '_cache'):
                bucket.append(node)
            elif node._cache:
                bucket.append(node)
            else:
                self._collect_into(node, bucket)

        for _ in self._wait_for_pending(result, no_ack=no_ack, **kwargs):
            while bucket:
                node = bucket.popleft()
                if not hasattr(node, '_cache'):
                    yield node.id, node.children
                else:
                    yield node.id, node._cache
        while bucket:
            node = bucket.popleft()
            yield node.id, node._cache

    def add_pending_result(self, result, weak=False, start_drainer=True):
        if start_drainer:
            self.result_consumer.drainer.start()
        try:
            self._maybe_resolve_from_buffer(result)
        except Empty:
            self._add_pending_result(result.id, result, weak=weak)
        return result

    def _maybe_resolve_from_buffer(self, result):
        result._maybe_set_cache(self._pending_messages.take(result.id))

    def _add_pending_result(self
# … (truncated at 8000 chars)


def _format_user_classes_count_for_log(user_classes_count: dict[str, int]) -> str:
    return "{} ({} total users)".format(  # noqa: UP032
        json.dumps(dict(sorted(user_classes_count.items(), key=itemgetter(0)))),
        sum(user_classes_count.values()),
    )


def add(  # type: ignore[override]
        self,
        job: 'Job',
        ttl=None,
        exc_string: str = '',
        pipeline: Optional['Pipeline'] = None,
    ):
        """
        Adds a job to a registry with expiry time of now + ttl.
        `ttl` defaults to DEFAULT_FAILURE_TTL if not specified.
        """
        if ttl is None:
            ttl = DEFAULT_FAILURE_TTL
        score = ttl if ttl < 0 else current_timestamp() + ttl

        if pipeline:
            p = pipeline
        else:
            p = self.connection.pipeline()

        job._exc_info = exc_string
        job.save(pipeline=p, include_meta=False, include_result=False)
        job.cleanup(ttl=ttl, pipeline=p)
        p.zadd(self.key, {job.id: score})

        if not pipeline:
            p.execute()


def get_current_context(silent: bool = False) -> Context | None:
    """Returns the current click context.  This can be used as a way to
    access the current context object from anywhere.  This is a more implicit
    alternative to the :func:`pass_context` decorator.  This function is
    primarily useful for helpers such as :func:`echo` which might be
    interested in changing its behavior based on the current context.

    To push the current context, :meth:`Context.scope` can be used.

    .. versionadded:: 5.0

    :param silent: if set to `True` the return value is `None` if no context
                   is available.  The default behavior is to raise a
                   :exc:`RuntimeError`.
    """
    try:
        return t.cast("Context", _local.stack[-1])
    except (AttributeError, IndexError) as e:
        if not silent:
            raise RuntimeError("There is no active click context.") from e

    return None


export function _isoDate<T extends schemas.$ZodISODate>(
  Class: util.SchemaClass<T>,
  params?: string | $ZodISODateParams | $ZodCheckISODateParams
): T {
  return new Class({
    type: "string",
    format: "date",
    check: "string_format",
    ...util.normalizeParams(params),
  });
}


function prepareSetCopy(state: SetState) {
		if (!state.copy_) {
			// create drafts for all entries to preserve insertion order
			state.copy_ = new Set()
			state.base_.forEach(value => {
				if (isDraftable(value)) {
					const draft = createProxy(state.scope_, value, state, value)
					state.drafts_.set(value, draft)
					state.copy_!.add(draft)
				} else {
					state.copy_!.add(value)
				}
			})
		}
	}


safeExtend extend parse shallowClone mergeValues

export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
  if (isObject(o) === false) return false;

  // modified constructor
  const ctor = o.constructor;
  if (ctor === undefined) return true;

  if (typeof ctor !== "function") return true;

  // modified prototype
  const prot = ctor.prototype;
  if (isObject(prot) === false) return false;

  // ctor doesn't have static `isPrototypeOf`
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }

  return true;
}


#getFallbackRequestFunction() {
		const url = this.#internals.url as (URL | undefined);

		if (!url) {
			return;
		}

		if (url.protocol === 'https:') {
			if (this.#internals.http2) {
				if (major < 15 || (major === 15 && minor < 10)) {
					const error = new Error('To use the `http2` option, install Node.js 15.10.0 or above');
					(error as NodeJS.ErrnoException).code = 'EUNSUPPORTED';

					throw error;
				}

				return http2wrapper.auto as RequestFunction;
			}

			return https.request;
		}

		return http.request;
	}

import process from 'node:process';
import {promisify, inspect, type InspectOptions} from 'node:util';
import {checkServerIdentity, type SecureContextOptions, type DetailedPeerCertificate} from 'node:tls';
// DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`.
import https, {
	type RequestOptions as HttpsRequestOptions,
	type Agent as HttpsAgent,
} from 'node:https';
import http, {
	type Agent as HttpAgent,
	type ClientRequest,
} from 'node:http';
import type {Readable} from 'node:stream';
import type {Socket, LookupFunction} from 'node:net';
import is, {assert} from '@sindresorhus/is';
import lowercaseKeys from 'lowercase-keys';
import CacheableLookup from 'cacheable-lookup';
import http2wrapper, {type ClientHttp2Session} from 'http2-wrapper';
import type {KeyvStoreAdapter} from 'keyv';
import type KeyvType from 'keyv';
import type ResponseLike from 'responselike';
import type {RequestPromise} from '../as-promise/types.js';
import type {IncomingMessageWithTimings} from './utils/timer.js';
import parseLinkHeader from './parse-link-header.js';
import type {PlainResponse, Response} from './response.js';
import type {RequestError} from './errors.js';
import type {Delays} from './timed-out.js';

type StorageAdapter = KeyvStoreAdapter | KeyvType | Map<unknown, unknown>;

type Promisable<T> = T | Promise<T>;

const [major, minor] = process.versions.node.split('.').map(Number) as [number, number, number];

export type DnsLookupIpVersion = undefined | 4 | 6;

type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;

export type NativeRequestOptions = HttpsRequestOptions & CacheOptions & {checkServerIdentity?: CheckServerIdentityFunction};

type AcceptableResponse = IncomingMessageWithTimings | ResponseLike;
type AcceptableRequestResult = Promisable<AcceptableResponse | ClientRequest | undefined>;
export type RequestFunction = (url: URL, options: NativeRequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult;

export type Agents = {
	http?: HttpAgent | false;
	https?: HttpsAgent | false;
	http2?: unknown | false;
};

export type Headers = Record<string, string | string[] | undefined>;

export type ToughCookieJar = {
	getCookieString: ((currentUrl: string, options: Record<string, unknown>, callback: (error: Error | undefined, cookies: string) => void) => void)
		& ((url: string, callback: (error: Error | undefined, cookieHeader: string) => void) => void);
	setCookie: ((cookieOrString: unknown, currentUrl: string, options: Record<string, unknown>, callback: (error: Error | undefined, cookie: unknown) => void) => void)
		& ((rawCookie: string, url: string, callback: (error: Error | undefined, result: unknown) => void) => void);
};

export type PromiseCookieJar = {
	getCookieString: (url: string) => Promise<string>;
	setCookie: (rawCookie: string, url: string) => Promise<unknown>;
};

/**
Utility type to override specific properties in a type.

Uses `Omit` to remove properties before adding them back to ensure proper type replacement rather than intersection, which handles edge cases with optional/required properties correctly.
*/
type OverrideProperties<T, U> = Omit<T, keyof U> & U;

/**
Represents the runtime state of Options as seen by hooks after normalization.

Some Options properties accept multiple input types but are normalized to a single type internally by the Options class setters. This type reflects the actual runtime types that hooks receive, ensuring type safety when accessing options within hook functions.
*/
export type NormalizedOptions = OverrideProperties<Options, {
	// The URL is always normalized to a URL instance (or undefined) by the time hooks execute.
	url: URL | undefined;

	// When set to `true`, dnsCache is normalized to a CacheableLookup instance. When set to `false`, it becomes `undefined`.
	dnsCache: CacheableLookup | undefined;

	// When set to `true`, cache is normalized to the global cache Map. When set to `false`, it becomes `undefined`. Strings and other values are wrapped/processed into a StorageAdapter.
	cache: StorageAdapter | undefined;

	// The prefix URL is always normalized to a string.
	prefixUrl: string;
}>;

export type InitHook = (init: OptionsInit, self: Options) => void;

export type BeforeRequestHookContext = {
	/**
	The current retry count.

	It will be `0` for the initial request and increment for each retry.
	*/
	retryCount: number;
};

export type BeforeRequestHook = (options: NormalizedOptions, context: BeforeRequestHookContext) => Promisable<void | Response | ResponseLike>;
export type BeforeRedirectHook = (updatedOptions: NormalizedOptions, plainResponse: PlainResponse) => Promisable<void>;
export type BeforeErrorHook = (error: RequestError) => Promisable<Error>;
export type BeforeRetryHook = (error: RequestError, retryCount: number) => Promisable<void>;
export type BeforeCacheHook = (response: PlainResponse) => false | void;
export type AfterResponseHook<ResponseType = unknown> = (response: Response<ResponseType>, retryWithMergedOptions: (options: OptionsInit) => never) => Promisable<Response | RequestPromise<Response>>;

/**
All available hooks of Got.
*/
export type Hooks = {
	/**
	Called with the plain request options, right before their normalization.

	The second argument represents the current `Options` instance.

	@default []

	**Note:**
	> - This hook must be synchronous.

	**Note:**
	> - This is called every time options are merged.

	**Note:**
	> - The `options` object may not have the `url` property. To modify it, use a `beforeRequest` hook instead.

	**Note:**
	> - This hook is called when a new instance of `Options` is created.
	> - Do not confuse this with the creation of `Request` or `got(…)`.

	**Note:**
	> - When using `got(url)` or `got(url, undefined, defaults)` this hook will **not** be called.

	This is especially useful in conjunction with `got.extend()` when the input needs custom handling.

	For example, this can be used to fix typos to migrate from older versions faster.

	@example
	```
	import got from 'got';

	const instance = got.extend({
		hooks: {
			init: [
				plain => {
					if ('followRedirects' in plain) {
						plain.followRedirect = plain.followRedirects;
						delete plain.followRedirects;
					}
				}
			]
		}
	});

	// Normally, the following would throw:
	const response = await instance(
		'https://example.com',
		{
			followRedirects: true
		}
	);

	// There is no option named `followRedirects`, but we correct it in an `init` hook.
	```

	Or you can create your own option and store it in a context:

	```
	import got from 'got';

	const instance = got.extend({
		hooks: {
			init: [
				(plain, options) => {
					if ('secret' in plain) {
						options.context.secret = plain.secret;
						delete plain.secret;
					}
				}
			],
			beforeRequest: [
				options => {
					options.headers.secret = options.context.secret;
				}
			]
		}
	});

	const {headers} = await instance(
		'https://httpbin.org/anything',
		{
			secret: 'passphrase'
		}
	).json();

	console.log(headers.Secret);
	//=> 'passphrase'
	```
	*/
	init: InitHook[];

	/**
	Called right before making the request with `options.createNativeRequestOptions()`.

	The second argument is a context object containing request state information.

	This hook is especially useful in conjunction with `got.extend()` when you want to sign your request.

	@default []

	**Note:**
	> - Got will make no further changes to the request before it is sent.

	**Note:**
	> - Changing `options.json` or `options.form` has no effect on the request. You should change `options.body` instead. If needed, update the `options.headers` accordingly.

	@example
	```
	import got from 'got';

	const response = await got.post(
		'https://httpbin.org/anything',
		{
			json: {payload: 'old'},
			hooks: {
				beforeRequest: [
					(options, context) => {
						options.body = JSON.stringify({payload: 'new'});

# … (truncated at 8000 chars)


def put(self, localpath, remotepath, callback=None, confirm=True):
        """
        Copy a local file (``localpath``) to the SFTP server as ``remotepath``.
        Any exception raised by operations will be passed through.  This
        method is primarily provided as a convenience.

        The SFTP operations use pipelining for speed.

        :param str localpath: the local file to copy
        :param str remotepath: the destination path on the SFTP server. Note
            that the filename should be included. Only specifying a directory
            may result in an error.
        :param callable callback:
            optional callback function (form: ``func(int, int)``) that accepts
            the bytes transferred so far and the total bytes to be transferred
        :param bool confirm:
            whether to do a stat() on the file afterwards to confirm the file
            size

        :return: an `.SFTPAttributes` object containing attributes about the
            given file

        .. versionadded:: 1.4
        .. versionchanged:: 1.7.4
            ``callback`` and rich attribute return value added.
        .. versionchanged:: 1.7.7
            ``confirm`` param added.
        """
        file_size = os.stat(localpath).st_size
        with open(localpath, "rb") as fl:
            return self.putfo(fl, remotepath, file_size, callback, confirm)


def _filter_tasks_by_tags(self) -> None:
        """
        Filter the tasks on all the user_classes recursively, according to the tags and
        exclude_tags attributes
        """
        if getattr(self, "_tasks_filtered", False):
            return  # only filter once
        self._tasks_filtered = True

        if self.tags is not None:
            tags = set(self.tags)
        elif self.parsed_options and getattr(self.parsed_options, "tags", False):
            tags = set(self.parsed_options.tags)
        else:
            tags = None

        if self.exclude_tags is not None:
            exclude_tags = set(self.exclude_tags)
        elif self.parsed_options and getattr(self.parsed_options, "exclude_tags", False):
            exclude_tags = set(self.parsed_options.exclude_tags)
        else:
            exclude_tags = None

        for user_class in self.user_classes:
            filter_tasks_by_tags(user_class, tags, exclude_tags)


@property
    def failure_callback(self) -> Optional[FailureCallbackType]:
        if self._failure_callback is UNEVALUATED:
            if self._failure_callback_name:
                self._failure_callback = import_attribute(self._failure_callback_name)
            else:
                return None

        return self._failure_callback  # type: ignore[return-value]


sleep close open hasPendingRequests getPendingRequests WsClient send from

private handleIncomingRequest(message: TRPCClientIncomingRequest) {
    if (message.method === 'reconnect') {
      this.reconnect(
        new TRPCWebSocketClosedError({
          message: 'Server requested reconnect',
        }),
      );
    }
  }


def create_cookie(name, value, **kwargs):
    """Make a cookie from underspecified parameters.

    By default, the pair of `name` and `value` will be set for the domain ''
    and sent on every request (this is sometimes called a "supercookie").
    """
    result = {
        "version": 0,
        "name": name,
        "value": value,
        "port": None,
        "domain": "",
        "path": "/",
        "secure": False,
        "expires": None,
        "discard": True,
        "comment": None,
        "comment_url": None,
        "rest": {"HttpOnly": None},
        "rfc2109": False,
    }

    badargs = set(kwargs) - set(result)
    if badargs:
        raise TypeError(
            f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
        )

    result.update(kwargs)
    result["port_specified"] = bool(result["port"])
    result["domain_specified"] = bool(result["domain"])
    result["domain_initial_dot"] = result["domain"].startswith(".")
    result["path_specified"] = bool(result["path"])

    return cookielib.Cookie(**result)


isValidCidr isValidJWT addIssueToContext timeRegex ParseStatus _getOrReturnCtx _getType isValidIP assertNever datetimeRegex dirty

_parse(input: ParseInput): ParseReturnType<string> {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);

    if (parsedType !== ZodParsedType.string) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx.parsedType,
      });
      return INVALID;
    }

    const status = new ParseStatus();
    let ctx: undefined | ParseContext = undefined;

    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message,
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message,
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          // @ts-ignore
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!(input.data as string).includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!(input.data as string).startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check.value },
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!(input.data as string).endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check.value },
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex(check);

        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex;

        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex(check);

        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check.message,
          });
          status.dirty();
        }
      } else {
        util.assertNever(check);
      }
    }

    return { status: status.value, value: input.data };
  }


transformTRPCResponseItem getHTTPStatusCodeFromError TRPCError constructor

export function internal_exceptionHandler<
  TRouter extends AnyRouter,
  TRequest extends NodeHTTPRequest,
  TResponse extends NodeHTTPResponse,
>(opts: NodeHTTPRequestHandlerOptions<TRouter, TRequest, TResponse>) {
  return (cause: unknown) => {
    const { res, req } = opts;
    const error = getTRPCErrorFromUnknown(cause);

    const shape = getErrorShape({
      config: opts.router._def._config,
      error,
      type: 'unknown',
      path: undefined,
      input: undefined,
      ctx: undefined,
    });

    opts.onError?.({
      req,
      error,
      type: 'unknown',
      path: undefined,
      input: undefined,
      ctx: undefined,
    });

    const transformed = transformTRPCResponse(opts.router._def._config, {
      error: shape,
    });

    res.statusCode = shape.data.httpStatus;
    res.end(JSON.stringify(transformed));
  };
}


def remove(self, job_or_id: Union['Job', str], pipeline: Optional['Pipeline'] = None):
        """Removes Job from queue, accepts either a Job instance or ID.

        Args:
            job_or_id (Union[Job, str]): The Job instance or Job ID string.
            pipeline (Optional[Pipeline], optional): The Redis Pipeline. Defaults to None.

        Returns:
            _type_: _description_
        """
        job_id = cast(str, job_or_id.id if isinstance(job_or_id, self.job_class) else job_or_id)

        if pipeline is not None:
            return pipeline.lrem(self.key, 1, job_id)

        return self.connection.lrem(self.key, 1, job_id)


@contextmanager
    def measure(
        self, request_type: str, name: str, response_length: int = 0, context=None
    ) -> Generator[dict[str, Any]]:
        """Convenience method for firing the event with automatically calculated response time and automatically marking the request as failed if an exception is raised (this is really only useful for the *request* event)

        Example usage (in a task):

        .. code-block:: python

            with self.environment.events.request.measure("requestType", "requestName") as request_meta:
                # do the stuff you want to measure

        You can optionally add/overwrite entries in the request_meta dict and they will be passed to the request event.

        Experimental.
        """
        start_time = time.time()
        start_perf_counter = time.perf_counter()
        request_meta = {
            "request_type": request_type,
            "name": name,
            "response_length": response_length,
            "context": context or {},
            "exception": None,
            "start_time": start_time,
        }
        try:
            yield request_meta
        except Exception as e:
            request_meta["exception"] = e
        finally:
            request_meta["response_time"] = (time.perf_counter() - start_perf_counter) * 1000
            self.fire(**request_meta)


shouldCopyPipedHeader(name: string): boolean {
		const normalizedHeader = name.toLowerCase();

		if (this.isHeaderExplicitlySet(normalizedHeader)) {
			return false;
		}

		return true;
	}


def add_execution(self, execution: 'Execution', pipeline: 'Pipeline', ttl: int = 0, xx: bool = False) -> int:
        """Adds an execution to a registry with expiry time of now + ttl, unless it's -1 which is set to +inf

        Args:
            execution (Execution): The Execution to add.
            pipeline (Pipeline): The Redis Pipeline.
            ttl (int, optional): The time to live. Defaults to 0.
            xx (bool, optional): .... Defaults to False.

        Returns:
            result (int): The ZADD command result
        """
        score: Union[int, str] = ttl if ttl < 0 else current_timestamp() + ttl
        if score == -1:
            score = '+inf'

        return pipeline.zadd(self.key, {execution.composite_key: score}, xx=xx)  # type: ignore


@setupmethod
    def add_template_filter(
        self, f: ft.TemplateFilterCallable, name: str | None = None
    ) -> None:
        """Register a function to use as a custom Jinja filter.

        The :meth:`template_filter` decorator can be used to register a function
        by decorating instead.

        :param f: The function to register.
        :param name: The name to register the filter as. If not given, uses the
            function's name.
        """
        self.jinja_env.filters[name or f.__name__] = f

from __future__ import annotations

import logging
import os
import sys
import typing as t
from datetime import timedelta
from itertools import chain

from werkzeug.exceptions import Aborter
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import BadRequestKeyError
from werkzeug.routing import BuildError
from werkzeug.routing import Map
from werkzeug.routing import Rule
from werkzeug.sansio.response import Response
from werkzeug.utils import cached_property
from werkzeug.utils import redirect as _wz_redirect

from .. import typing as ft
from ..config import Config
from ..config import ConfigAttribute
from ..ctx import _AppCtxGlobals
from ..helpers import _split_blueprint_path
from ..helpers import get_debug_flag
from ..json.provider import DefaultJSONProvider
from ..json.provider import JSONProvider
from ..logging import create_logger
from ..templating import DispatchingJinjaLoader
from ..templating import Environment
from .scaffold import _endpoint_from_view_func
from .scaffold import find_package
from .scaffold import Scaffold
from .scaffold import setupmethod

if t.TYPE_CHECKING:  # pragma: no cover
    from werkzeug.wrappers import Response as BaseResponse

    from ..testing import FlaskClient
    from ..testing import FlaskCliRunner
    from .blueprints import Blueprint

T_shell_context_processor = t.TypeVar(
    "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
)
T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)

def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
    if value is None or isinstance(value, timedelta):
        return value

    return timedelta(seconds=value)

class App(Scaffold):
    """The flask object implements a WSGI application and acts as the central
    object.  It is passed the name of the module or package of the
    application.  Once it is created it will act as a central registry for
    the view functions, the URL rules, template configuration and much more.

    The name of the package is used to resolve resources from inside the
    package or the folder the module is contained in depending on if the
    package parameter resolves to an actual python package (a folder with
    an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).

    For more information about resource loading, see :func:`open_resource`.

    Usually you create a :class:`Flask` instance in your main module or
    in the :file:`__init__.py` file of your package like this::

        from flask import Flask
        app = Flask(__name__)

    .. admonition:: About the First Parameter

        The idea of the first parameter is to give Flask an idea of what
        belongs to your application.  This name is used to find resources
        on the filesystem, can be used by extensions to improve debugging
        information and a lot more.

        So it's important what you provide there.  If you are using a single
        module, `__name__` is always the correct value.  If you however are
        using a package, it's usually recommended to hardcode the name of
        your package there.

        For example if your application is defined in :file:`yourapplication/app.py`
        you should create it with one of the two versions below::

            app = Flask('yourapplication')
            app = Flask(__name__.split('.')[0])

        Why is that?  The application will work even with `__name__`, thanks
        to how resources are looked up.  However it will make debugging more
        painful.  Certain extensions can make assumptions based on the
        import name of your application.  For example the Flask-SQLAlchemy
        extension will look for the code in your application that triggered
        an SQL query in debug mode.  If the import name is not properly set
        up, that debugging information is lost.  (For example it would only
        pick up SQL queries in `yourapplication.app` and not
        `yourapplication.views.frontend`)

    .. versionadded:: 0.7
       The `static_url_path`, `static_folder`, and `template_folder`
       parameters were added.

    .. versionadded:: 0.8
       The `instance_path` and `instance_relative_config` parameters were
       added.

    .. versionadded:: 0.11
       The `root_path` parameter was added.

    .. versionadded:: 1.0
       The ``host_matching`` and ``static_host`` parameters were added.

    .. versionadded:: 1.0
       The ``subdomain_matching`` parameter was added. Subdomain
       matching needs to be enabled manually now. Setting
       :data:`SERVER_NAME` does not implicitly enable it.

    :param import_name: the name of the application package
    :param static_url_path: can be used to specify a different path for the
                            static files on the web.  Defaults to the name
                            of the `static_folder` folder.
    :param static_folder: The folder with static files that is served at
        ``static_url_path``. Relative to the application ``root_path``
        or an absolute path. Defaults to ``'static'``.
    :param static_host: the host to use when adding the static route.
        Defaults to None. Required when using ``host_matching=True``
        with a ``static_folder`` configured.
    :param host_matching: set ``url_map.host_matching`` attribute.
        Defaults to False.
    :param subdomain_matching: consider the subdomain relative to
        :data:`SERVER_NAME` when matching routes. Defaults to False.
    :param template_folder: the folder that contains the templates that should
                            be used by the application.  Defaults to
                            ``'templates'`` folder in the root path of the
                            application.
    :param instance_path: An alternative instance path for the application.
                          By default the folder ``'instance'`` next to the
                          package or module is assumed to be the instance
                          path.
    :param instance_relative_config: if set to ``True`` relative filenames
                                     for loading the config are assumed to
                                     be relative to the instance path instead
                                     of the application root.
    :param root_path: The path to the root of the application files.
        This should only be set manually when it can't be detected
        automatically, such as for namespace packages.
    """

    #: The class of the object assigned to :attr:`aborter`, created by
    #: :meth:`create_aborter`. That object is called by
    #: :func:`flask.abort` to raise HTTP errors, and can be
    #: called directly as well.
    #:
    #: Defaults to :class:`werkzeug.exceptions.Aborter`.
    #:
    #: .. versionadded:: 2.2
    aborter_class = Aborter

    #: The class that is used for the Jinja environment.
    #:
    #: .. versionadded:: 0.11
    jinja_environment = Environment

    #: The class that is used for the :data:`~flask.g` instance.
    #:
    #: Example use cases for a custom class:
    #:
    #: 1. Store arbitrary attributes on flask.g.
    #: 2. Add a property for lazy per-request database connectors.
    #: 3. Return None instead of AttributeError on unexpected attributes.
    #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
    #:
    #: .. versionadded:: 0.10
    #:     Renamed from ``request_globals_class`.
    app_ctx_globals_class = _AppCtxGlobals

    #: The class that is used for the ``config`` attribute of this app.
    #: Defaults to :class:`~flask.Config`.
    #:
    #: Example use cases for a custom class:
    #:
    #: 1. Default values for certain config
# … (truncated at 8000 chars)


def _process_result(value: t.Any) -> t.Any:
            if self._result_callback is not None:
                value = ctx.invoke(self._result_callback, value, **ctx.params)
            return value


export function _array<T extends schemas.$ZodType>(
  Class: util.SchemaClass<schemas.$ZodArray>,
  element: T,
  params?: string | $ZodArrayParams
): schemas.$ZodArray<T> {
  return new Class({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...util.normalizeParams(params),
  }) as any;
}


def check_workers(self, respawn: bool = True) -> None:
        """
        Check whether workers are still alive
        """
        self.log.debug('Checking worker processes')
        self.reap_workers()
        # If we have less number of workers than num_workers,
        # respawn the difference
        if respawn and self.status != self.Status.STOPPED:
            delta = self.num_workers - len(self.worker_dict)
            if delta:
                for i in range(delta):
                    self.start_worker(burst=self._burst, _sleep=self._sleep)


useFetchWorkerCount useFetchTasks useLogViewer useFetchExceptions useFetchStats

export default function useInterval(
  callback: () => void,
  delay: number,
  { shouldRunInterval, immediate }: { shouldRunInterval?: boolean; immediate?: boolean } = {
    shouldRunInterval: true,
    immediate: false,
  },
) {
  const savedCallback = useRef(callback);

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (!shouldRunInterval) {
      return;
    }

    if (immediate) {
      savedCallback.current();
    }

    const interval = setInterval(() => savedCallback.current(), delay);

    return () => {
      clearInterval(interval);
    };
  }, [delay, shouldRunInterval]);
}


def _sort_key(
        self, package: Package, link: Link
    ) -> tuple[int, int, int, Version, tuple[Any, ...], int]:
        """
        Function to pass as the `key` argument to a call to sorted() to sort
        InstallationCandidates by preference.
        Returns a tuple such that tuples sorting as greater using Python's
        default comparison operator are more preferred.
        The preference is as follows:
        First and foremost, candidates with allowed (matching) hashes are
        always preferred over candidates without matching hashes. This is
        because e.g. if the only candidate with an allowed hash is yanked,
        we still want to use that candidate.
        Second, excepting hash considerations, candidates that have been
        yanked (in the sense of PEP 592) are always less preferred than
        candidates that haven't been yanked. Then:
        If not finding wheels, they are sorted by version only.
        If finding wheels, then the sort order is by version, then:
          1. existing installs
          2. wheels ordered via Wheel.support_index_min(self._supported_tags)
          3. source archives
        If prefer_binary was set, then all wheels are sorted above sources.
        Note: it was considered to embed this logic into the Link
              comparison operators, but then different sdist links
              with the same version, would have to be considered equal
        """
        build_tag: tuple[Any, ...] = ()
        binary_preference = 0
        if link.is_wheel:
            wheel = Wheel(link.filename)
            if not wheel.is_supported_by_environment(self._env):
                raise RuntimeError(
                    f"{wheel.filename} is not a supported wheel for this platform. It "
                    "can't be sorted."
                )

            # TODO: Binary preference
            pri = -(wheel.get_minimum_supported_index(self._env.supported_tags) or 0)
            if wheel.build_tag is not None:
                match = re.match(r"^(\d+)(.*)$", wheel.build_tag)
                if not match:
                    raise ValueError(f"Unable to parse build tag: {wheel.build_tag}")
                build_tag_groups = match.groups()
                build_tag = (int(build_tag_groups[0]), build_tag_groups[1])
        else:  # sdist
            support_num = len(self._env.supported_tags)
            pri = -support_num

        has_allowed_hash = int(self._is_link_hash_allowed_for_package(link, package))

        yank_value = int(not link.yanked)

        return (
            has_allowed_hash,
            yank_value,
            binary_preference,
            package.version,
            build_tag,
            pri,
        )


"~validate"(data: unknown): StandardSchemaV1.Result<Output> | Promise<StandardSchemaV1.Result<Output>> {
    const ctx: ParseContext = {
      common: {
        issues: [],
        async: !!(this["~standard"] as any).async,
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data),
    };

    if (!(this["~standard"] as any).async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result)
          ? {
              value: result.value,
            }
          : {
              issues: ctx.common.issues,
            };
      } catch (err: any) {
        if ((err as Error)?.message?.toLowerCase()?.includes("encountered")) {
          (this["~standard"] as any).async = true;
        }
        (ctx as any).common = {
          issues: [],
          async: true,
        };
      }
    }

    return this._parseAsync({ data, path: [], parent: ctx }).then((result) =>
      isValid(result)
        ? {
            value: result.value,
          }
        : {
            issues: ctx.common.issues,
          }
    );
  }


finalize process initializeContext extractDefs

export function toJSONSchema(
  input: schemas.$ZodType | $ZodRegistry<{ id?: string | undefined }>,
  params?: ToJSONSchemaParams | RegistryToJSONSchemaParams
): any {
  if ("_idmap" in input) {
    // Registry case
    const registry = input as $ZodRegistry<{ id?: string | undefined }>;
    const ctx = initializeContext({ ...params, processors: allProcessors });
    const defs: any = {};

    // First pass: process all schemas to build the seen map
    for (const entry of registry._idmap.entries()) {
      const [_, schema] = entry;
      process(schema, ctx as any);
    }

    const schemas: Record<string, JSONSchema.BaseSchema> = {};
    const external = {
      registry,
      uri: (params as RegistryToJSONSchemaParams)?.uri,
      defs,
    };

    // Update the context with external configuration
    ctx.external = external;

    // Second pass: emit each schema
    for (const entry of registry._idmap.entries()) {
      const [key, schema] = entry;
      extractDefs(ctx as any, schema);
      schemas[key] = finalize(ctx as any, schema);
    }

    if (Object.keys(defs).length > 0) {
      const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs,
      };
    }

    return { schemas };
  }

  // Single schema case
  const ctx = initializeContext({ ...params, processors: allProcessors });
  process(input, ctx as any);
  extractDefs(ctx as any, input);
  return finalize(ctx as any, input);
}


next(data) {
        isDone = true;
        resolve(data);
        onDone();
      },


async def aread(self) -> bytes:
        """
        Read and return the request content.
        """
        if not hasattr(self, "_content"):
            assert isinstance(self.stream, typing.AsyncIterable)
            self._content = b"".join([part async for part in self.stream])
            if not isinstance(self.stream, ByteStream):
                # If a streaming request has been read entirely into memory, then
                # we can replace the stream with a raw bytes implementation,
                # to ensure that any non-replayable streams can still be used.
                self.stream = ByteStream(self._content)
        return self._content


def listdir_attr(self, path="."):
        """
        Return a list containing `.SFTPAttributes` objects corresponding to
        files in the given ``path``.  The list is in arbitrary order.  It does
        not include the special entries ``'.'`` and ``'..'`` even if they are
        present in the folder.

        The returned `.SFTPAttributes` objects will each have an additional
        field: ``longname``, which may contain a formatted string of the file's
        attributes, in unix format.  The content of this string will probably
        depend on the SFTP server implementation.

        :param str path: path to list (defaults to ``'.'``)
        :return: list of `.SFTPAttributes` objects

        .. versionadded:: 1.2
        """
        path = self._adjust_cwd(path)
        self._log(DEBUG, "listdir({!r})".format(path))
        t, msg = self._request(CMD_OPENDIR, path)
        if t != CMD_HANDLE:
            raise SFTPError("Expected handle")
        handle = msg.get_binary()
        filelist = []
        while True:
            try:
                t, msg = self._request(CMD_READDIR, handle)
            except EOFError:
                # done with handle
                break
            if t != CMD_NAME:
                raise SFTPError("Expected name response")
            count = msg.get_int()
            for i in range(count):
                filename = msg.get_text()
                longname = msg.get_text()
                attr = SFTPAttributes._from_msg(msg, filename, longname)
                if (filename != ".") and (filename != ".."):
                    filelist.append(attr)
        self._request(CMD_CLOSE, handle)
        return filelist


def decode_wp_content(content, br=True):
    pre_tags = {}
    if content is None or content.strip() == "":
        return ""

    content += "\n"
    if "<pre" in content:
        pre_parts = content.split("
")
        last_pre = pre_parts.pop()
        content = ""
        pre_index = 0

        for pre_part in pre_parts:
            start = pre_part.find("<pre")
            if start == -1:
                content = content + pre_part
                continue
            name = f"

"
            pre_tags[name] = pre_part[start:] + "
"
            content = content + pre_part[0:start] + name
            pre_index += 1
        content = content + last_pre

    content = re.sub(r"
\s*
", "\n\n", content)
    allblocks = (
        "(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|"
        "td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|"
        "map|area|blockquote|address|math|style|p|h[1-6]|hr|"
        "fieldset|noscript|samp|legend|section|article|aside|"
        "hgroup|header|footer|nav|figure|figcaption|details|"
        "menu|summary)"
    )
    content = re.sub(r"(<" + allblocks + r"[^>]*>)", "\n\\1", content)
    content = re.sub(r"(</" + allblocks + r">)", "\\1\n\n", content)
    #    content = content.replace("\r\n", "\n")
    if "<object" in content:
        # no
 inside object/embed
        content = re.sub(r"\s*<param([^>]*)>\s*", "<param\\1>", content)
        content = re.sub(r"\s*</embed>\s*", "</embed>", content)
        #    content = re.sub(r'/\n\n+/', '\n\n', content)
    pgraphs = filter(lambda s: s != "", re.split(r"\n\s*\n", content))
    content = ""
    for p in pgraphs:
        content = content + "
" + p.strip() + "
\n"
    # under certain strange conditions it could create
    # a P of entirely whitespace
    content = re.sub(r"
\s*
", "", content)
    content = re.sub(r"
([^<]+)</(div|address|form)>", "
\\1
</\\2>", content)
    # don't wrap tags
    content = re.sub(r"
\s*(</?" + allblocks + r"[^>]*>)\s*
", "\\1", content)
    # problem with nested lists
    content = re.sub(r"
(", "

", content)
    content = content.replace("

", "

")
    content = re.sub(r"
\s*(</?" + allblocks + "[^>]*>)", "\\1", content)
    content = re.sub(r"(</?" + allblocks + r"[^>]*>)\s*
", "\\1", content)
    if br:

        def _preserve_newline(match):
            return match.group(0).replace("\n", "<WPPreserveNewline />")

        content = re.sub(r"/<(script|style).*?<\/\\1>/s", _preserve_newline, content)
        # optionally make line breaks
        content = re.sub(r"(?<!
)\s*\n", "
\n", content)
        content = content.replace("<WPPreserveNewline />", "\n")
    content = re.sub(r"(</?" + allblocks + r"[^>]*>)\s*
", "\\1", content)
    content = re.sub(
        r"
(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)", "\\1", content
    )
    content = re.sub(r"\n
", "
", content)

    if pre_tags:

        def _multi_replace(dic, string):
            pattern = r"|".join(map(re.escape, dic.keys()))
            return re.sub(pattern, lambda m: dic[m.group()], string)

        content = _multi_replace(pre_tags, content)

    # convert [caption] tags into

    content = re.sub(
        r"\[caption(?:.*?)(?:caption=\"(.*?)\")?\]"
        r"((?:\)?(?:\)(?:\<\/a\>)?)\s?(.*?)\[\/caption\]",
        r"
\n\2\n
\1\3
\n
",
        content,
    )

    return content


function benchMethod() {
					setAutoFreezes[version](freeze)
					setStrictIteration[version](false)
					setEnableArrayMethods[version]()

					let currentState = createInitialState()

					// Perform multiple operations on the same evolving state
					for (let i = 0; i < BENCHMARK_CONFIG.reuseStateIterations; i++) {
						currentState = reducers[version](currentState, actions[action](i))
					}
					setAutoFreezes[version](false)
				}


def restore(self, raw_data) -> Any:
        """Overwrite properties with the provided values stored in Redis.

        Args:
            raw_data (_type_): The raw data to load the job data from

        Raises:
            NoSuchJobError: If there way an error getting the job data
        """
        obj = decode_redis_hash(raw_data)
        try:
            raw_data = obj['data']
        except KeyError:
            raise NoSuchJobError(f'Unexpected job format: {obj}')

        try:
            self.data = zlib.decompress(raw_data)
        except zlib.error:
            # Fallback to uncompressed string
            self.data = raw_data

        self.created_at = str_to_date(v) if (v := obj.get('created_at')) else now()
        self.origin = as_text(obj['origin']) if obj.get('origin') else ''
        self.worker_name = obj['worker_name'].decode() if obj.get('worker_name') else None
        self.description = as_text(obj['description']) if obj.get('description') else None

        self.enqueued_at = str_to_date(v) if (v := obj.get('enqueued_at')) else None
        self.started_at = str_to_date(v) if (v := obj.get('started_at')) else None
        self.ended_at = str_to_date(v) if (v := obj.get('ended_at')) else None

        self.last_heartbeat = str_to_date(v) if (v := obj.get('last_heartbeat')) else None
        self.group_id = as_text(obj['group_id']) if obj.get('group_id') else None
        result = obj.get('result')
        if result:
            try:
                self._result = self.serializer.loads(result)
            except Exception:
                self._result = UNSERIALIZABLE_RETURN_VALUE_PAYLOAD
        self.timeout = parse_timeout(obj.get('timeout')) if obj.get('timeout') else None
        self.result_ttl = int(obj['result_ttl']) if obj.get('result_ttl') else None
        self.failure_ttl = int(obj['failure_ttl']) if obj.get('failure_ttl') else None

        # Beginning from v2.4.1, jobs are created with a status, so the fallback to CREATED
        # is not needed, but we keep it for backwards compatibility
        # In future versions, if a job has no status, an error should be raised
        self._status = JobStatus(as_text(obj['status'])) if obj.get('status') else JobStatus.CREATED

        if obj.get('success_callback_name'):
            self._success_callback_name = obj['success_callback_name'].decode()

        if 'success_callback_timeout' in obj:
            self._success_callback_timeout = int(obj['success_callback_timeout'])

        if obj.get('failure_callback_name'):
            self._failure_callback_name = obj['failure_callback_name'].decode()

        if 'failure_callback_timeout' in obj:
            self._failure_callback_timeout = int(obj['failure_callback_timeout'])

        if obj.get('stopped_callback_name'):
            self._stopped_callback_name = obj['stopped_callback_name'].decode()

        if 'stopped_callback_timeout' in obj:
            self._stopped_callback_timeout = int(obj['stopped_callback_timeout'])

        dep_ids = obj.get('dependency_ids')
        dep_id = obj.get('dependency_id')  # for backwards compatibility
        self._dependency_ids = json.loads(dep_ids.decode()) if dep_ids else [dep_id.decode()] if dep_id else []
        allow_failures = obj.get('allow_dependency_failures')
        self.allow_dependency_failures = bool(int(allow_failures)) if allow_failures else None
        self.enqueue_at_front = bool(int(obj['enqueue_at_front'])) if 'enqueue_at_front' in obj else None
        self.ttl = int(obj['ttl']) if obj.get('ttl') else None
        try:
            self.meta = self.serializer.loads(obj['meta']) if obj.get('meta') else {}
        except Exception:  # depends on the serializer
            self.meta = {'unserialized': obj.get('meta', {})}

        self.number_of_retries = int(obj['number_of_retries']) if obj.get('number_of_retries') else None
        self.retries_left = int(obj['retries_left']) if obj.get('retries_left') else None
        if obj.get('retry_intervals'):
            self.retry_intervals = json.loads(obj['retry_intervals'].decode())

        self.repeats_left = int(obj['repeats_left']) if obj.get('repeats_left') else None
        if obj.get('repeat_intervals'):
            self.repeat_intervals = json.loads(obj['repeat_intervals'].decode())

        raw_exc_info = obj.get('exc_info')
        if raw_exc_info:
            try:
                self._exc_info = as_text(zlib.decompress(raw_exc_info))
            except zlib.error:
                # Fallback to uncompressed string
                self._exc_info = as_text(raw_exc_info)


cuid(message?: errorUtil.ErrMessage) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }


ZodNullable unwrap constructor ZodOptional ZodObject ZodArray ZodTuple

function deepPartialify(schema: ZodTypeAny): any {
  if (schema instanceof ZodObject) {
    const newShape: any = {};

    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape,
    }) as any;
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element),
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item: any) => deepPartialify(item)));
  } else {
    return schema;
  }
}


function createBenchmarks() {
	// All single-operation benchmarks (fresh state each time)
	for (const action in actions) {
		summary(function() {
			bench(`$action: $version (freeze: $freeze)`, function*(args) {
				const version = args.get("version")
				const freeze = args.get("freeze")
				const action = args.get("action")

				const initialState = createInitialState()

				function benchMethod() {
					setAutoFreezes[version](freeze)
					setStrictIteration[version](false)
					setEnableArrayMethods[version]()
					for (let i = 0; i < MAX; i++) {
						reducers[version](initialState, actions[action](i))
					}
					setAutoFreezes[version](false)
				}

				yield benchMethod
			}).args({
				version: Object.keys(reducers),
				freeze,
				action: [action]
			})
		})
	}

	// State reuse benchmarks (tests performance on frozen/evolved state)
	const reuseActions = [
		"update",
		"update-high",
		"remove",
		"remove-high",
		"update-largeObject1",
		"update-largeObject2"
	]
	for (const action of reuseActions) {
		summary(function() {
			bench(`$action-reuse: $version (freeze: $freeze)`, function*(args) {
				const version = args.get("version")
				const freeze = args.get("freeze")
				const action = args.get("action")

				function benchMethod() {
					setAutoFreezes[version](freeze)
					setStrictIteration[version](false)
					setEnableArrayMethods[version]()

					let currentState = createInitialState()

					// Perform multiple operations on the same evolving state
					for (let i = 0; i < BENCHMARK_CONFIG.reuseStateIterations; i++) {
						currentState = reducers[version](currentState, actions[action](i))
					}
					setAutoFreezes[version](false)
				}

				yield benchMethod
			}).args({
				version: Object.keys(reducers),
				freeze,
				action: [action]
			})
		})
	}

	// Mixed operations sequence benchmark
	summary(function() {
		bench(`mixed-sequence: $version (freeze: $freeze)`, function*(args) {
			const version = args.get("version")
			const freeze = args.get("freeze")

			function benchMethod() {
				setAutoFreezes[version](freeze)
				setStrictIteration[version](false)
				setEnableArrayMethods[version]()

				let state = createInitialState()

				// Perform a sequence of different operations (typical workflow)
				state = reducers[version](state, actions.add(1))
				state = reducers[version](state, actions.update(getValidId()))
				state = reducers[version](state, actions["update-high"](2))
				state = reducers[version](state, actions["update-multiple"](3))
				state = reducers[version](state, actions.remove(getValidIndex()))

				setAutoFreezes[version](false)
			}

			yield benchMethod
		}).args({
			version: Object.keys(reducers),
			freeze
		})
	})

	// RTKQ-style benchmark - executes multiple reducer calls in sequence
	summary(function() {
		bench(`rtkq-sequence: $version (freeze: $freeze)`, function*(args) {
			const version = args.get("version")
			const freeze = args.get("freeze")

			function benchMethod() {
				setAutoFreezes[version](freeze)
				setStrictIteration[version](false)
				setEnableArrayMethods[version]()

				let state = createInitialState()
				// Use smaller array size for RTKQ benchmark due to exponential scaling
				// 100 items = ~15ms, 200 items = ~32ms, so 10000 would be impractical
				const arraySize = 100

				// Phase 1: Execute all pending actions
				for (let i = 0; i < arraySize; i++) {
					state = reducers[version](state, rtkqPending(i))
				}

				// Phase 2: Execute all resolved actions
				for (let i = 0; i < arraySize; i++) {
					state = reducers[version](state, rtkqResolved(i))
				}

				setAutoFreezes[version](false)
			}

			yield benchMethod
		}).args({
			version: Object.keys(reducers),
			freeze
		})
	})
}


_parse(input: ParseInput): ParseReturnType<this["_output"]> {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (
      parsedLeft: SyncParseReturnType,
      parsedRight: SyncParseReturnType
    ): SyncParseReturnType<T & U> => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }

      const merged = mergeValues(parsedLeft.value, parsedRight.value);

      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types,
        });
        return INVALID;
      }

      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }

      return { status: status.value, value: merged.data };
    };

    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx,
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx,
        }),
      ]).then(([left, right]: any) => handleParsed(left, right));
    } else {
      return handleParsed(
        this._def.left._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx,
        }),
        this._def.right._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx,
        })
      );
    }
  }


function attempt(attempts: number) {
          const op = opWithLastEventId();

          next$ = callOpts.next(op).subscribe({
            error(error) {
              const shouldRetry = opts.retry({
                op,
                attempts,
                error,
              });
              if (!shouldRetry) {
                observer.error(error);
                return;
              }
              const delayMs = opts.retryDelayMs?.(attempts) ?? 0;

              if (delayMs <= 0) {
                attempt(attempts + 1);
                return;
              }
              callNextTimeout = setTimeout(
                () => attempt(attempts + 1),
                delayMs,
              );
            },
            next(envelope) {
              //
              if (
                (!envelope.result.type || envelope.result.type === 'data') &&
                envelope.result.id
              ) {
                //
                lastEventId = envelope.result.id;
              }

              observer.next(envelope);
            },
            complete() {
              observer.complete();
            },
          });
        }


optional(): ZodOptional<this> {
    return ZodOptional.create(this, this._def) as any;
  }


def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
        """Like :func:`append()` but disallow invalid standalone comment structure.

        Raises ValueError when any `leaf` is appended after a standalone comment
        or when a standalone comment is not the first leaf on the line.
        """
        if (
            self.bracket_tracker.depth == 0
            or self.bracket_tracker.any_open_for_or_lambda()
        ):
            if self.is_comment:
                raise ValueError("cannot append to standalone comments")

            if self.leaves and leaf.type == STANDALONE_COMMENT:
                raise ValueError(
                    "cannot append standalone comments to a populated line"
                )

        self.append(leaf, preformatted=preformatted)


export function isFrozen(obj: any): boolean {
	// Fast path: primitives and null/undefined are always "frozen"
	if (obj === null || !isObjectish(obj)) return true
	return O.isFrozen(obj)
}


def show(self, file: t.IO[t.Any] | None = None) -> None:
        if file is None:
            file = get_text_stderr()

        echo(
            _("Error: {message}").format(message=self.format_message()),
            file=file,
            color=self.show_color,
        )


def get_jobs_to_schedule(self, timestamp: Optional[int] = None, chunk_size: int = 1000) -> list[str]:
        """Get's a list of job IDs that should be scheduled.

        Args:
            timestamp (Optional[int]): _description_. Defaults to None.
            chunk_size (int, optional): _description_. Defaults to 1000.

        Returns:
            jobs (List[str]): A list of Job ids
        """
        score: int = timestamp if timestamp is not None else current_timestamp()
        jobs_to_schedule = self.connection.zrangebyscore(self.key, 0, score, start=0, num=chunk_size)
        return [as_text(job_id) for job_id in jobs_to_schedule]


async def cleanup(self) -> None:
        async for attempt in self._retry():
            with attempt:
                events: list[Event] = []
                async with self._begin_transaction() as conn:
                    # Purge expired job results
                    delete = self._t_job_results.delete().where(
                        self._t_job_results.c.expires_at <= datetime.now(timezone.utc)
                    )
                    await self._execute(conn, delete)

                    # Finish any jobs whose leases have expired
                    now = datetime.now(timezone.utc)
                    query = select(
                        self._t_jobs.c.id,
                        self._t_jobs.c.task_id,
                        self._t_jobs.c.schedule_id,
                        self._t_jobs.c.scheduled_fire_time,
                        self._t_jobs.c.acquired_by,
                        self._t_jobs.c.result_expiration_time,
                    ).where(
                        self._t_jobs.c.acquired_by.isnot(None),
                        self._t_jobs.c.acquired_until < now,
                    )
                    for row in await self._execute(conn, query):
                        result = JobResult(
                            job_id=row.id,
                            outcome=JobOutcome.abandoned,
                            finished_at=now,
                            expires_at=now + row.result_expiration_time,
                        )
                        events.append(
                            await self._release_job(
                                conn,
                                result,
                                row.acquired_by,
                                row.task_id,
                                row.schedule_id,
                                row.scheduled_fire_time,
                            )
                        )

                    # Clean up finished schedules that have no running jobs
                    query = (
                        select(self._t_schedules.c.id, self._t_schedules.c.task_id)
                        .outerjoin(
                            self._t_jobs,
                            self._t_jobs.c.schedule_id == self._t_schedules.c.id,
                        )
                        .where(
                            self._t_schedules.c.next_fire_time.is_(None),
                            self._t_jobs.c.id.is_(None),
                        )
                    )
                    results = await self._execute(conn, query)
                    if finished_schedule_ids := dict(results.all()):
                        delete = self._t_schedules.delete().where(
                            self._t_schedules.c.id.in_(finished_schedule_ids)
                        )
                        await self._execute(conn, delete)

                    for schedule_id, task_id in finished_schedule_ids.items():
                        events.append(
                            ScheduleRemoved(
                                schedule_id=schedule_id,
                                task_id=task_id,
                                finished=True,
                            )
                        )

                # Publish any events produced from the operations
                for event in events:
                    await self._event_broker.publish(event)


nanoid(message?: errorUtil.ErrMessage) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }


def stats_reporter(self) -> NoReturn:
        while True:
            try:
                self._send_stats()
            except RPCError as e:
                logger.error(f"Temporary connection lost to master server: {e}, will retry later.")
            gevent.sleep(WORKER_REPORT_INTERVAL)