merge(options?: OptionsInit | Options) {
		if (!options) {
			return;
		}

		if (options instanceof Options) {
			// Create a copy of the #init array to avoid infinite loop
			// when merging an Options instance with itself
			const initArray = [...options.#init];
			for (const init of initArray) {
				this.merge(init);
			}

			return;
		}

		options = cloneRaw(options);

		init(this, options, this);
		init(options, options, this);

		this.#merging = true;

		try {
			let push = false;

			for (const key in options) {
				// `got.extend()` options
				if (key === 'mutableDefaults' || key === 'handlers') {
					continue;
				}

				// Never merge `url`
				if (key === 'url') {
					continue;
				}

				// Never merge `preserveHooks` - it's a control flag, not a persistent option
				if (key === 'preserveHooks') {
					continue;
				}

				// `isStream` is set internally by `got.stream()`, not by user options
				if (key === 'isStream') {
					continue;
				}

				if (!(key in this)) {
					throw new Error(`Unexpected option: ${key}`);
				}

				// @ts-expect-error Type 'unknown' is not assignable to type 'never'.
				const value = options[key as keyof Options];
				if (value === undefined) {
					continue;
				}

				// @ts-expect-error Type 'unknown' is not assignable to type 'never'.
				this[key as keyof Options] = value;

				push = true;
			}

			if (push) {
				this.#init.push(options);
			}
		} finally {
			this.#merging = false;
		}
	}

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 handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        if not self._current:
            if tag == "a" and self._match_class(attrs, "package-snippet"):
                self._current = Result()
                self._nest_anchors = 1
        else:
            if tag == "span" and self._match_class(attrs, "package-snippet__name"):
                self._data_callback = functools.partial(setattr, self._current, "name")
            elif tag == "span" and self._match_class(attrs, "package-snippet__version"):
                self._data_callback = functools.partial(
                    setattr, self._current, "version"
                )
            elif tag == "p" and self._match_class(
                attrs, "package-snippet__description"
            ):
                self._data_callback = functools.partial(
                    setattr, self._current, "description"
                )
            elif tag == "a":
                self._nest_anchors += 1


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,
              );
            },


@hookimpl(tryfirst=True)
def pytest_runtest_setup(item: Item) -> None:
    skipped = evaluate_skip_marks(item)
    if skipped:
        raise skip.Exception(skipped.reason, _use_item_location=True)

    item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)
    if xfailed and not item.config.option.runxfail and not xfailed.run:
        xfail("[NOTRUN] " + xfailed.reason)


def _generate_pickle_name(gt: Path, cache_dir: Path | None = None) -> str:
    head, tail = os.path.splitext(gt)
    if tail == ".txt":
        tail = ""
    name = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
    if cache_dir:
        return os.path.join(cache_dir, os.path.basename(name))
    else:
        return name


def print_stats(stats: RequestStats, current=True) -> None:
    for line in get_stats_summary(stats, current):
        console_logger.info(line)
    console_logger.info("")


def render_progress(self) -> None:
        if self.hidden:
            return

        if not self._is_atty:
            # Only output the label once if the output is not a TTY.
            if self._last_line != self.label:
                self._last_line = self.label
                echo(self.label, file=self.file, color=self.color)
            return

        buf = []
        # Update width in case the terminal has been resized
        if self.autowidth:
            import shutil

            old_width = self.width
            self.width = 0
            clutter_length = term_len(self.format_progress_line())
            new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
            if new_width < old_width and self.max_width is not None:
                buf.append(BEFORE_BAR)
                buf.append(" " * self.max_width)
                self.max_width = new_width
            self.width = new_width

        clear_width = self.width
        if self.max_width is not None:
            clear_width = self.max_width

        buf.append(BEFORE_BAR)
        line = self.format_progress_line()
        line_len = term_len(line)
        if self.max_width is None or self.max_width < line_len:
            self.max_width = line_len

        buf.append(line)
        buf.append(" " * (clear_width - line_len))
        line = "".join(buf)
        # Render the line only if it changed.

        if line != self._last_line:
            self._last_line = line
            echo(line, file=self.file, color=self.color, nl=False)
            self.file.flush()


function dontMutateFrozenCollections() {
	die(2)
}


def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]:
        """
        A byte-iterator over the raw response content.
        """
        if self.is_stream_consumed:
            raise StreamConsumed()
        if self.is_closed:
            raise StreamClosed()
        if not isinstance(self.stream, SyncByteStream):
            raise RuntimeError("Attempted to call a sync iterator on an async stream.")

        self.is_stream_consumed = True
        self._num_bytes_downloaded = 0
        chunker = ByteChunker(chunk_size=chunk_size)

        with request_context(request=self._request):
            for raw_stream_bytes in self.stream:
                self._num_bytes_downloaded += len(raw_stream_bytes)
                for chunk in chunker.decode(raw_stream_bytes):
                    yield chunk

        for chunk in chunker.flush():
            yield chunk

        self.close()


function generatePatchesAndFinalize(state: ImmerState, rootScope: ImmerScope) {
	const shouldFinalize =
		state.modified_ &&
		!state.finalized_ &&
		(state.type_ === ArchType.Set ||
			(state.type_ === ArchType.Array &&
				(state as ProxyArrayState).allIndicesReassigned_) ||
			(state.assigned_?.size ?? 0) > 0)

	if (shouldFinalize) {
		const {patchPlugin_} = rootScope
		if (patchPlugin_) {
			const basePath = patchPlugin_!.getPath(state)

			if (basePath) {
				patchPlugin_!.generatePatches_(state, basePath, rootScope)
			}
		}

		markStateFinalized(state)
	}
}


def referrer(self, response_url: str, request_url: str) -> str | None:
        if (
            self.tls_protected(response_url)
            and self.potentially_trustworthy(request_url)
        ) or not self.tls_protected(response_url):
            return self.origin_referrer(response_url)
        return None


def fetch_dependencies(self, watch: bool = False, pipeline: Optional['Pipeline'] = None) -> list['Job']:
        """Fetch all of a job's dependencies. If a pipeline is supplied, and
        watch is true, then set WATCH on all the keys of all dependencies.

        Returned jobs will use self's connection, not the pipeline supplied.

        If a job has been deleted from redis, it is not returned.

        Args:
            watch (bool, optional): Whether to WATCH the keys. Defaults to False.
            pipeline (Optional[Pipeline]): The Redis' pipeline to use. Defaults to None.

        Returns:
            jobs (list[Job]): A list of Jobs
        """
        connection = pipeline if pipeline is not None else self.connection

        if watch and self._dependency_ids:
            connection.watch(*[self.key_for(dependency_id) for dependency_id in self._dependency_ids])

        dependencies_list = self.fetch_many(
            self._dependency_ids, connection=self.connection, serializer=self.serializer
        )
        jobs = [job for job in dependencies_list if job]
        return jobs


@contextmanager
    def reconnect_on_error(self):
        """Context manager that catches connection errors and reconnects.

        Wraps a block of code so that any :attr:`_connection_errors` raised
        inside it trigger a call to :meth:`_reconnect`.  If reconnection
        itself raises a connection error the consumer is considered
        unrecoverable and a :exc:`RuntimeError` is raised to signal that
        the Celery application must be restarted.
        """
        try:
            yield
        except self._connection_errors:
            try:
                self._reconnect()
            except self._connection_errors as exc:
                logger.critical(E_RETRY_LIMIT_EXCEEDED)
                raise RuntimeError(E_RETRY_LIMIT_EXCEEDED) from exc


def spider_closed(self, spider: Spider, reason: str) -> None:
        self.log()
        if self.task and self.task.running:
            self.task.stop()


def find_all(
        self, node_type: type[_NodeBound] | tuple[type[_NodeBound], ...]
    ) -> t.Iterator[_NodeBound]:
        """Find all the nodes of a given type.  If the type is a tuple,
        the check is performed for any of the tuple items.
        """
        for child in self.iter_child_nodes():
            if isinstance(child, node_type):
                yield child  # type: ignore
            yield from child.find_all(node_type)


export function getTransformer(
  transformer:
    | TransformerOptions<{ transformer: false }>['transformer']
    | TransformerOptions<{ transformer: true }>['transformer']
    | undefined,
): CombinedDataTransformer {
  const _transformer =
    transformer as CoercedTransformerParameters['transformer'];
  if (!_transformer) {
    return {
      input: {
        serialize: (data) => data,
        deserialize: (data) => data,
      },
      output: {
        serialize: (data) => data,
        deserialize: (data) => data,
      },
    };
  }
  if ('input' in _transformer) {
    return _transformer;
  }
  return {
    input: _transformer,
    output: _transformer,
  };
}


@classmethod
    def get_jobs_with_met_dependencies(cls, jobs: Iterable['Job'], pipeline: Pipeline):
        jobs_with_met_dependencies = []
        jobs_with_unmet_dependencies = []
        for job in jobs:
            while True:
                try:
                    pipeline.watch(*[Job.key_for(dependency_id) for dependency_id in job._dependency_ids])
                    job.register_dependency(pipeline=pipeline)
                    if job.dependencies_are_met(pipeline=pipeline):
                        jobs_with_met_dependencies.append(job)
                    else:
                        jobs_with_unmet_dependencies.append(job)
                    pipeline.execute()
                except WatchError:
                    continue
                break
        return jobs_with_met_dependencies, jobs_with_unmet_dependencies


strip(): ZodObject<T, "strip", Catchall> {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip",
    }) as any;
  }


export function getClientArgs<TOptions, TFeatureFlags extends FeatureFlags>(
  queryKey: TRPCQueryKey<TFeatureFlags['keyPrefix']>,
  opts: TOptions,
  infiniteParams?: {
    pageParam: any;
    direction: 'forward' | 'backward';
  },
) {
  const queryKeyData = readQueryKey(queryKey);

  let input = queryKeyData.args?.input;
  if (infiniteParams) {
    input = {
      ...(queryKeyData.args?.input ?? {}),
      ...(infiniteParams.pageParam !== undefined
        ? { cursor: infiniteParams.pageParam }
        : {}),
      direction: infiniteParams.direction,
    };
  }
  return [queryKeyData.path.join('.'), input, (opts as any)?.trpc] as const;
}


private async _makeRequest(): Promise<void> {
		const {options} = this;
		const headers = options.getInternalHeaders();
		const {username, password} = options;
		const cookieJar = options.cookieJar as PromiseCookieJar | undefined;

		for (const key in headers) {
			if (is.undefined(headers[key])) {
				options.deleteInternalHeader(key);
			} else if (is.null(headers[key])) {
				throw new TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${key}\` header`);
			}
		}

		if (options.decompress && is.undefined(headers['accept-encoding'])) {
			const encodings = ['gzip', 'deflate'];
			if (supportsBrotli) {
				encodings.push('br');
			}

			if (supportsZstd) {
				encodings.push('zstd');
			}

			options.setInternalHeader('accept-encoding', encodings.join(', '));
		}

		if (username || password) {
			const credentials = Buffer.from(`${username}:${password}`).toString('base64');
			options.setInternalHeader('authorization', `Basic ${credentials}`);
		}

		// Set cookies
		if (cookieJar) {
			let cookieString = '';
			cookieString = await cookieJar.getCookieString(options.url!.toString());

			if (is.nonEmptyString(cookieString)) {
				options.setInternalHeader('cookie', cookieString);
			}
		}

		let request: ReturnType<Options['getRequestFunction']> | undefined;

		for (const hook of options.hooks.beforeRequest) {
			// eslint-disable-next-line no-await-in-loop
			const result = await hook(options as NormalizedOptions, {retryCount: this.retryCount});

			if (!is.undefined(result)) {
				// @ts-expect-error Skip the type mismatch to support abstract responses
				request = () => result;
				break;
			}
		}

		request ??= options.getRequestFunction();

		const url = options.url as URL;

		this._requestOptions = options.createNativeRequestOptions() as NativeRequestOptions;

		if (options.cache) {
			(this._requestOptions as any)._request = request;
			(this._requestOptions as any).cache = options.cache;
			(this._requestOptions as any).body = options.body;
			(this._requestOptions as any).beforeCacheHooks = options.hooks.beforeCache;
			(this._requestOptions as any).gotRequest = this;

			try {
				this._prepareCache(options.cache as StorageAdapter);
			} catch (error: unknown) {
				throw new CacheError(normalizeError(error), this);
			}
		}

		// Cache support
		const function_ = options.cache ? this._createCacheableRequest : request;

		try {
			// We can't do `await fn(...)`,
			// because stream `error` event can be emitted before `Promise.resolve()`.
			let requestOrResponse = function_!(url, this._requestOptions);

			if (is.promise(requestOrResponse)) {
				requestOrResponse = await requestOrResponse;
			}

			if (isClientRequest(requestOrResponse!)) {
				this._onRequest(requestOrResponse);
			} else if (this.writableEnded) {
				void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
			} else {
				this.once('finish', () => {
					void this._onResponse(requestOrResponse as IncomingMessageWithTimings);
				});

				this._sendBody();
			}
		} catch (error) {
			if (error instanceof CacheableCacheError) {
				throw new CacheError(error, this);
			}

			throw error;
		}
	}

import process from 'node:process';
import {Buffer} from 'node:buffer';
import {Duplex, type Readable} from 'node:stream';
import {addAbortListener} from 'node:events';
import http, {ServerResponse, type ClientRequest, type RequestOptions} from 'node:http';
import type {Socket} from 'node:net';
import {byteLength} from 'byte-counter';
import {chunk} from 'chunk-data';
import CacheableRequest, {
	CacheError as CacheableCacheError,
	type CacheableRequestFunction,
	type CacheableOptions,
} from 'cacheable-request';
import decompressResponse from 'decompress-response';
import type {KeyvStoreAdapter} from 'keyv';
import type KeyvType from 'keyv';
import is, {isBuffer} from '@sindresorhus/is';
import type ResponseLike from 'responselike';
import timer, {type ClientRequestWithTimings, type Timings, type IncomingMessageWithTimings} from './utils/timer.js';
import getBodySize from './utils/get-body-size.js';
import proxyEvents from './utils/proxy-events.js';
import timedOut, {TimeoutError as TimedOutTimeoutError} from './timed-out.js';
import stripUrlAuth from './utils/strip-url-auth.js';
import WeakableMap from './utils/weakable-map.js';
import calculateRetryDelay from './calculate-retry-delay.js';
import Options, {
	type PromiseCookieJar,
	type NativeRequestOptions,
	type RetryOptions,
	type OptionsError,
	type OptionsInit,
	type NormalizedOptions,
} from './options.js';
import {
	cacheDecodedBody,
	isResponseOk,
	type PlainResponse,
	type Response,
} from './response.js';
import isClientRequest from './utils/is-client-request.js';
import isUnixSocketURL, {getUnixSocketPath} from './utils/is-unix-socket-url.js';
import {
	RequestError,
	ReadError,
	MaxRedirectsError,
	HTTPError,
	TimeoutError,
	UploadError,
	CacheError,
	AbortError,
} from './errors.js';
import {
	generateRequestId,
	publishRequestCreate,
	publishRequestStart,
	publishResponseStart,
	publishResponseEnd,
	publishRetry,
	publishError,
	publishRedirect,
} from './diagnostics-channel.js';

type Error = NodeJS.ErrnoException;

export type Progress = {
	percent: number;
	transferred: number;
	total?: number;
};

const supportsBrotli = is.string(process.versions.brotli);
const supportsZstd = is.string(process.versions.zstd);
const isUtf8Encoding = (encoding?: BufferEncoding): boolean => encoding === undefined || encoding.toLowerCase().replace('-', '') === 'utf8';
const textEncoder = new TextEncoder();
const concatUint8Arrays = (chunks: readonly Uint8Array[]): Uint8Array => {
	let totalLength = 0;
	for (const chunk of chunks) {
		totalLength += chunk.byteLength;
	}

	const result = new Uint8Array(totalLength);
	let offset = 0;

	for (const chunk of chunks) {
		result.set(chunk, offset);
		offset += chunk.byteLength;
	}

	return result;
};

const methodsWithoutBody: ReadonlySet<string> = new Set(['GET', 'HEAD']);

export type GotEventFunction<T> =
	/**
	`request` event to get the request object of the request.

	 __Tip__: You can use `request` event to abort requests.

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

	got.stream('https://github.com')
		.on('request', request => setTimeout(() => request.destroy(), 50));
	```
	*/
	((name: 'request', listener: (request: ClientRequest) => void) => T)

	/**
	The `response` event to get the response object of the final request.
	*/
	& (<R extends Response>(name: 'response', listener: (response: R) => void) => T)

	/**
	The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
	*/
	& (<R extends Response, N extends Options>(name: 'redirect', listener: (response: R, nextOptions: N) => void) => T)

	/**
	Progress events for uploading (sending a request) and downloading (receiving a response).
	The `progress` argument is an object like:

	```
	{
		percent: 0.1,
		transferred: 1024,
		total: 10240
	}
	```

	If the `content-length` header is missing, `total` will be `undefined`.

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

	const response = await got('https://sindresorhus.com')
		.on('downloadProgress', progress => {
			// Report download progress
		})
		.on('uploadProgress', progress => {
			// Report upload progress
		});

	console.log(response);
	```
	*/
	& ((name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void) => T)
	/**
	To enable retrying on a Got stream, it is required to have a `retry` handler attached.

	When this event is emitted, you should reset the stream you were writing to and prepare the body again.

	See `got.options.retry` for more information.
	*/
	& ((name: 'retry', listener: (retryCount: number, error: RequestError, createRetryStream: (options?: OptionsInit) => Request) => void) => T);

export type RequestEvents<T> = {
	on: GotEventFunction<T>;
	once: GotEventFunction<T>;
	off: GotEventFunction<T>;
};

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

const cacheableStore = new WeakableMap<string | StorageAdapter, CacheableRequestFunction>();

const redirectCodes: ReadonlySet<number> = new Set([300, 301, 302, 303, 304, 307, 308]);
const transientWriteErrorCodes: ReadonlySet<string> = new Set(['EPIPE', 'ECONNRESET']);

// Track errors that have been processed by beforeError hooks to preserve custom error types
const errorsProcessedByHooks = new WeakSet<Error>();

const proxiedRequestEvents = [
	'socket',
	'connect',
	'continue',
	'information',
	'upgrade',
] as const;

const noop = (): void => {};

const isTransientWriteError = (error: Error): boolean => {
	const {code} = error;
	return typeof code === 'string' && transientWriteErrorCodes.has(code);
};

const normalizeError = (error: unknown): Error => {
	if (error instanceof globalThis.Error) {
		return error;
	}

	if (is.object(error)) {
		const errorLike = error as Partial<Error & {code?: string; input?: string}>;
		const message = typeof errorLike.message === 'string' ? errorLike.message : 'Non-error object thrown';
		const normalizedError = new globalThis.Error(message, {cause: error}) as Error & {code?: string; input?: string};

		if (typeof errorLike.stack === 'string') {
			normalizedError.stack = errorLike.stack;
		}

		if (typeof errorLike.code === 'string') {
			normalizedError.code = errorLike.code;
		}

		if (typeof errorLike.input === 'string') {
			normalizedError.input = errorLike.input;
		}

		return normalizedError;
	}

	return new globalThis.Error(String(error));
};

type UrlType = ConstructorParameters<typeof Options>[0];
type OptionsType = ConstructorParameters<typeof Options>[1];
type DefaultsType = ConstructorParameters<typeof Options>[2];
const getSanitizedUrl = (options?: Options): string => options?.url ? stripUrlAuth(options.url) : '';

export default class Request extends Duplex implements RequestEvents<Request> {
	// @ts-expect-error - Ignoring for now.
	override ['constructor']: typeof Request;

	_noPipe?: boolean;

	// @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
	options: Options;
	response?: PlainResponse;
	requestUrl?: URL;
	redirectUrls: URL[] = [];
	retryCount = 0;
	_stopReading = false;

	declare private _requestOptions: NativeRequestOptions;

	private _stopRetry = noop;
	private _downloadedSize = 0;
	private _uploadedSize = 0;
	private readonly _pipedServerResponses = new Set<ServerResponse>();
	private _request?: ClientRequest;
	private _responseSize?: number;
	private _bodySize?: number;
	private _unproxyEvents = noop;
	private _isFromCache?: boolean;
	private _triggerRead = false;
	private readonly _jobs: Array<() => void> = [];
	private _cancelTimeouts = noop;
	private readonly _removeListeners = noop;
	private _nativeResponse?: IncomingMessageWithTimings;
	private _flushed = false;
	private _aborted = false;
	private _expectedContentLength?: number;
	private _compressedBytesCount?: number;
	private _skipRequestEndInFinal = false;
	private _incrementalBodyDecoder?: TextDecoder;
	private _incrementalDecodedBodyChunks: string[] = [];
	private readonly _requestId = generateRequestId();

	// We need thi
# … (truncated at 8000 chars)


export async function* withPing<TValue>(
  iterable: AsyncIterable<TValue>,
  pingIntervalMs: number,
): AsyncGenerator<TValue | typeof PING_SYM> {
  await using iterator = iteratorResource(iterable);

  // declaration outside the loop for garbage collection reasons
  let result:
    | null
    | IteratorResult<TValue>
    | typeof disposablePromiseTimerResult;

  let nextPromise = iterator.next();

  while (true) {
    using pingPromise = timerResource(pingIntervalMs);

    result = await Unpromise.race([nextPromise, pingPromise.start()]);

    if (result === disposablePromiseTimerResult) {
      // cancelled

      yield PING_SYM;
      continue;
    }

    if (result.done) {
      return result.value;
    }

    nextPromise = iterator.next();
    yield result.value;

    // free up reference for garbage collection
    result = null;
  }
}


function load(key: TKey): Promise<TValue> {
    const item: BatchItem<TKey, TValue> = {
      aborted: false,
      key,
      batch: null,
      resolve: throwFatalError,
      reject: throwFatalError,
    };

    const promise = new Promise<TValue>((resolve, reject) => {
      item.reject = reject;
      item.resolve = resolve;

      pendingItems ??= [];
      pendingItems.push(item);
    });

    dispatchTimer ??= setTimeout(dispatch);

    return promise;
  }


def get_heartbeat_ttl(self, job: 'Job') -> int:
        """Get's the TTL for the next heartbeat.

        Args:
            job (Job): The Job

        Returns:
            int: The heartbeat TTL.
        """
        if job.timeout and job.timeout > 0:
            remaining_execution_time = job.timeout - self.current_job_working_time
            return int(min(remaining_execution_time, self.job_monitoring_interval)) + 60
        else:
            return self.job_monitoring_interval + 60


@async_variant(sync_do_unique)  # type: ignore
async def do_unique(
    environment: "Environment",
    value: "t.AsyncIterable[V] | t.Iterable[V]",
    case_sensitive: bool = False,
    attribute: str | int | None = None,
) -> "t.Iterator[V]":
    return sync_do_unique(
        environment, await auto_to_list(value), case_sensitive, attribute
    )


def build_config_setting_validator(val: str) -> bool:
    try:
        value = build_config_setting_normalizer(val)
    except JSONDecodeError:
        return False

    if not isinstance(value, dict):
        return False

    for key, item in value.items():
        # keys should be string
        if not isinstance(key, str):
            return False

        # items are allowed to be a string
        if isinstance(item, str):
            continue

        # list items should only contain strings
        is_valid_list = isinstance(item, list) and all(isinstance(i, str) for i in item)
        if not is_valid_list:
            return False

    return True


public register(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {
    const { promise: end, resolve } = withResolvers<void>();

    this.outgoingRequests.push({
      id: String(message.id),
      message,
      end,
      callbacks: {
        next: callbacks.next,
        complete: () => {
          callbacks.complete();
          resolve();
        },
        error: (e) => {
          callbacks.error(e);
          resolve();
        },
      },
    });

    return () => {
      this.delete(message.id);
      callbacks.complete();
      resolve();
    };
  }


def tokeniter(
        self,
        source: str,
        name: str | None,
        filename: str | None = None,
        state: str | None = None,
    ) -> t.Iterator[tuple[int, str, str]]:
        """This method tokenizes the text and returns the tokens in a
        generator. Use this method if you just want to tokenize a template.

        .. versionchanged:: 3.0
            Only ``\\n``, ``\\r\\n`` and ``\\r`` are treated as line
            breaks.
        """
        lines = newline_re.split(source)[::2]

        if not self.keep_trailing_newline and lines[-1] == "":
            del lines[-1]

        source = "\n".join(lines)
        pos = 0
        lineno = 1
        stack = ["root"]

        if state is not None and state != "root":
            assert state in ("variable", "block"), "invalid state"
            stack.append(state + "_begin")

        statetokens = self.rules[stack[-1]]
        source_length = len(source)
        balancing_stack: list[str] = []
        newlines_stripped = 0
        line_starting = True

        while True:
            # tokenizer loop
            for regex, tokens, new_state in statetokens:
                m = regex.match(source, pos)

                # if no match we try again with the next rule
                if m is None:
                    continue

                # we only match blocks and variables if braces / parentheses
                # are balanced. continue parsing with the lower rule which
                # is the operator rule. do this only if the end tags look
                # like operators
                if balancing_stack and tokens in (
                    TOKEN_VARIABLE_END,
                    TOKEN_BLOCK_END,
                    TOKEN_LINESTATEMENT_END,
                ):
                    continue

                # tuples support more options
                if isinstance(tokens, tuple):
                    groups: t.Sequence[str] = m.groups()

                    if isinstance(tokens, OptionalLStrip):
                        # Rule supports lstrip. Match will look like
                        # text, block type, whitespace control, type, control, ...
                        text = groups[0]
                        # Skipping the text and first type, every other group is the
                        # whitespace control for each type. One of the groups will be
                        # -, +, or empty string instead of None.
                        strip_sign = next(g for g in groups[2::2] if g is not None)

                        if strip_sign == "-":
                            # Strip all whitespace between the text and the tag.
                            stripped = text.rstrip()
                            newlines_stripped = text[len(stripped) :].count("\n")
                            groups = [stripped, *groups[1:]]
                        elif (
                            # Not marked for preserving whitespace.
                            strip_sign != "+"
                            # lstrip is enabled.
                            and self.lstrip_blocks
                            # Not a variable expression.
                            and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)
                        ):
                            # The start of text between the last newline and the tag.
                            l_pos = text.rfind("\n") + 1

                            if l_pos > 0 or line_starting:
                                # If there's only whitespace between the newline and the
                                # tag, strip it.
                                if whitespace_re.fullmatch(text, l_pos):
                                    groups = [text[:l_pos], *groups[1:]]

                    for idx, token in enumerate(tokens):
                        # failure group
                        if isinstance(token, Failure):
                            raise token(lineno, filename)
                        # bygroup is a bit more complex, in that case we
                        # yield for the current token the first named
                        # group that matched
                        elif token == "#bygroup":
                            for key, value in m.groupdict().items():
                                if value is not None:
                                    yield lineno, key, value
                                    lineno += value.count("\n")
                                    break
                            else:
                                raise RuntimeError(
                                    f"{regex!r} wanted to resolve the token dynamically"
                                    " but no group matched"
                                )
                        # normal group
                        else:
                            data = groups[idx]

                            if data or token not in ignore_if_empty:
                                yield lineno, token, data  # type: ignore[misc]

                            lineno += data.count("\n") + newlines_stripped
                            newlines_stripped = 0

                # strings as token just are yielded as it.
                else:
                    data = m.group()

                    # update brace/parentheses balance
                    if tokens == TOKEN_OPERATOR:
                        if data == "{":
                            balancing_stack.append("}")
                        elif data == "(":
                            balancing_stack.append(")")
                        elif data == "[":
                            balancing_stack.append("]")
                        elif data in ("}", ")", "]"):
                            if not balancing_stack:
                                raise TemplateSyntaxError(
                                    f"unexpected '{data}'", lineno, name, filename
                                )

                            expected_op = balancing_stack.pop()

                            if expected_op != data:
                                raise TemplateSyntaxError(
                                    f"unexpected '{data}', expected '{expected_op}'",
                                    lineno,
                                    name,
                                    filename,
                                )

                    # yield items
                    if data or tokens not in ignore_if_empty:
                        yield lineno, tokens, data

                    lineno += data.count("\n")

                line_starting = m.group()[-1:] == "\n"
                # fetch new position into new variable so that we can check
                # if there is a internal parsing error which would result
                # in an infinite loop
                pos2 = m.end()

                # handle state changes
                if new_state is not None:
                    # remove the uppermost state
                    if new_state == "#pop":
                        stack.pop()
                    # resolve the new state by group checking
                    elif new_state == "#bygroup":
                        for key, value in m.groupdict().items():
                            if value is not None:
                                stack.append(key)
                                break
                        else:
                            raise RuntimeError(
                                f"{regex!r} wanted to resolve the new state dynamically"
                                f" but no group matched"
                            )
                    # direct state name given
                    else:
                        stack.append(new_state)

                    statetokens = self.rules[stack[-1]]
                # we are still at the same position and no stack change.
                # this means a loop without break condition, avoid that and
                # raise error
                elif pos2 == pos:
                    raise RuntimeError(
                        f"{regex!r} yielded empty string without stack change"
                    )

                # publish new function and start again
                pos = pos2
                break
            # if loop terminated without break we haven't found a single match
            # either we are at the end of the file or we have a problem
            else:
                # end of text
                if pos >= source_length:
                    return

                # something went wrong
                raise TemplateSyntaxError(
                    f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename
                )


markChanged prepareMapCopy each assertUnrevoked

clear() {
			const state: MapState = this[DRAFT_STATE]
			assertUnrevoked(state)
			if (latest(state).size) {
				prepareMapCopy(state)
				markChanged(state)
				state.assigned_ = new Map()
				each(state.base_, key => {
					state.assigned_!.set(key, false)
				})
				state.copy_!.clear()
			}
		}


static mergeObjectSync(
    status: ParseStatus,
    pairs: {
      key: SyncParseReturnType<any>;
      value: SyncParseReturnType<any>;
      alwaysSet?: boolean;
    }[]
  ): SyncParseReturnType {
    const finalObject: any = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted") return INVALID;
      if (value.status === "aborted") return INVALID;
      if (key.status === "dirty") status.dirty();
      if (value.status === "dirty") status.dirty();

      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }

    return { status: status.value, value: finalObject };
  }


def set_state(self, state: str, pipeline: Optional['Pipeline'] = None):
        """Sets the worker's state.

        Args:
            state (str): The state
            pipeline (Optional[Pipeline], optional): The pipeline to use. Defaults to None.
        """
        self._state = state
        connection = pipeline if pipeline is not None else self.connection
        connection.hset(self.key, 'state', state)


add enableArrayMethods set handleInsertedValues enableMapSet processResult

export function handleValue(
	target: any,
	handledSet: Set<any>,
	rootScope: ImmerScope
) {
	if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
		// optimization: if an object is not a draft, and we don't have to
		// deepfreeze everything, and we are sure that no drafts are left in the remaining object
		// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.
		// This benefits especially adding large data tree's without further processing.
		// See add-data.js perf test
		return target
	}

	// Skip if already handled, frozen, or not draftable
	if (
		isDraft(target) ||
		handledSet.has(target) ||
		!isDraftable(target) ||
		isFrozen(target)
	) {
		return target
	}

	handledSet.add(target)

	// Process ALL properties/entries
	each(target, (key, value) => {
		if (isDraft(value)) {
			const state: ImmerState = value[DRAFT_STATE]
			if (isSameScope(state, rootScope)) {
				// Replace draft with finalized value

				const updatedValue = getFinalValue(state)

				set(target, key, updatedValue, target.type_)

				markStateFinalized(state)
			}
		} else if (isDraftable(value)) {
			// Recursively handle nested values
			handleValue(value, handledSet, rootScope)
		}
	})

	return target
}


_parse(input: ParseInput): ParseReturnType<this["_output"]> {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType,
      });
      return INVALID;
    }

    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);

    return OK(
      promisified.then((data: any) => {
        return this._def.type.parseAsync(data, {
          path: ctx.path,
          errorMap: ctx.common.contextualErrorMap,
        });
      })
    );
  }


private _prepareCache(cache: string | StorageAdapter) {
		if (cacheableStore.has(cache)) {
			return;
		}

		const cacheableRequest = new CacheableRequest(
			((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
				/**
				Wraps the cacheable-request handler to run beforeCache hooks.
				These hooks control caching behavior by:
				- Directly mutating the response object (changes apply to what gets cached)
				- Returning `false` to prevent caching
				- Returning `void`/`undefined` to use default caching behavior

				Hooks use direct mutation - they can modify response.headers, response.statusCode, etc.
				Mutations take effect immediately and determine what gets cached.
				*/
				const wrappedHandler = handler
					? (response: IncomingMessageWithTimings) => {
						const {beforeCacheHooks, gotRequest} = requestOptions as any;

						// Early return if no hooks - cache the original response
						if (!beforeCacheHooks || beforeCacheHooks.length === 0) {
							handler(response);
							return;
						}

						try {
							// Call each beforeCache hook with the response
							// Hooks can directly mutate the response - mutations take effect immediately
							for (const hook of beforeCacheHooks) {
								const result = hook(response);

								if (result === false) {
									// Prevent caching by adding no-cache headers
									// Mutate the response directly to add headers
									response.headers['cache-control'] = 'no-cache, no-store, must-revalidate';
									response.headers.pragma = 'no-cache';
									response.headers.expires = '0';
									handler(response);
									// Don't call remaining hooks - we've decided not to cache
									return;
								}

								if (is.promise(result)) {
									// BeforeCache hooks must be synchronous because cacheable-request's handler is synchronous
									throw new TypeError('beforeCache hooks must be synchronous. The hook returned a Promise, but this hook must return synchronously. If you need async logic, use beforeRequest hook instead.');
								}

								if (result !== undefined) {
									// Hooks should return false or undefined only
									// Mutations work directly - no need to return the response
									throw new TypeError('beforeCache hook must return false or undefined. To modify the response, mutate it directly.');
								}
								// Else: void/undefined = continue
							}
						} catch (error: unknown) {
							const normalizedError = normalizeError(error);
							// Convert hook errors to RequestError and propagate
							// This is consistent with how other hooks handle errors
							if (gotRequest) {
								gotRequest._beforeError(normalizedError instanceof RequestError ? normalizedError : new RequestError(normalizedError.message, normalizedError, gotRequest));
								// Don't call handler when error was propagated successfully
								return;
							}

							// If gotRequest is missing, log the error to aid debugging
							// We still call the handler to prevent the request from hanging
							console.error('Got: beforeCache hook error (request context unavailable):', normalizedError);
							// Call handler with response (potentially partially modified)
							handler(response);
							return;
						}

						// All hooks ran successfully
						// Cache the response with any mutations applied
						handler(response);
					}
					: handler;

				const result = (requestOptions as any)._request(requestOptions, wrappedHandler);

				// TODO: remove this when `cacheable-request` supports async request functions.
				if (is.promise(result)) {
					// We only need to implement the error handler in order to support HTTP2 caching.
					// The result will be a promise anyway.
					// @ts-expect-error ignore
					result.once = (event: string, handler: (reason: unknown) => void) => {
						if (event === 'error') {
							(async () => {
								try {
									await result;
								} catch (error) {
									handler(error);
								}
							})();
						} else if (event === 'abort' || event === 'destroy') {
							// The empty catch is needed here in case when
							// it rejects before it's `await`ed in `_makeRequest`.
							(async () => {
								try {
									const request = (await result) as ClientRequest;
									request.once(event, handler);
								} catch {}
							})();
						} else {
							/* istanbul ignore next: safety check */
							throw new Error(`Unknown HTTP2 promise event: ${event}`);
						}

						return result;
					};
				}

				return result;
			}) as typeof http.request,
			cache as StorageAdapter,
		);
		cacheableStore.set(cache, cacheableRequest.request());
	}


async def release_job(self, scheduler_id: str, job: Job, result: JobResult) -> None:
        async for attempt in self._retry():
            with attempt:
                async with self._client.start_session() as session:
                    event = await self._release_job(
                        session,
                        result,
                        scheduler_id,
                        job.task_id,
                        job.schedule_id,
                        job.scheduled_fire_time,
                    )

                    # Notify other schedulers
                    await self._event_broker.publish(event)


def get_version(connection: 'Redis') -> tuple[int, int, int]:
    """
    Returns tuple of Redis server version.
    This function also correctly handles 4 digit redis server versions.

    Args:
        connection (Redis): The Redis connection.

    Returns:
        version (Tuple[int, int, int]): A tuple representing the semantic versioning format (eg. (5, 0, 9))
    """
    try:
        # Getting the connection info for each job tanks performance, we can cache it on the connection object
        if not getattr(connection, '__rq_redis_server_version', None):
            # Cast the version string to a tuple of integers. Some Redis implementations may return a float.
            version_str = str(connection.info('server')['redis_version'])
            version_parts = [int(i) for i in version_str.split('.')[:3]]
            # Ensure the version tuple has exactly three elements
            while len(version_parts) < 3:
                version_parts.append(0)
            setattr(
                connection,
                '__rq_redis_server_version',
                tuple(version_parts),
            )
        return getattr(connection, '__rq_redis_server_version')
    except ResponseError:  # fakeredis doesn't implement Redis' INFO command
        return (5, 0, 9)


def next_if(self, expr: str) -> Token | None:
        """Perform the token test and return the token if it matched.
        Otherwise the return value is `None`.
        """
        if self.current.test(expr):
            return next(self)

        return None


def initial(self, request, *args, **kwargs):
        """
        Runs anything that needs to occur prior to calling the method handler.
        """
        self.format_kwarg = self.get_format_suffix(**kwargs)

        # Perform content negotiation and store the accepted info on the request
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg

        # Determine the API version, if versioning is in use.
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        # Ensure that the incoming request is permitted
        self.perform_authentication(request)
        self.check_permissions(request)
        self.check_throttles(request)


def check_throttles(self, request):
        """
        Check if request should be throttled.
        Raises an appropriate exception if the request is throttled.
        """
        throttle_durations = []
        for throttle in self.get_throttles():
            if not throttle.allow_request(request, self):
                throttle_durations.append(throttle.wait())

        if throttle_durations:
            # Filter out `None` values which may happen in case of config / rate
            # changes, see #1438
            durations = [
                duration for duration in throttle_durations
                if duration is not None
            ]

            duration = max(durations, default=None)
            self.throttled(request, duration)


def read(self) -> bytes:
        """
        Read and return the response content.
        """
        if not hasattr(self, "_content"):
            self._content = b"".join(self.iter_bytes())
        return self._content


setMutationDefaults trpcMutationOptions createUtilityFunctions useAction experimental_createActionHook

public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {
    return this.requestAsPromise<unknown, unknown>({
      type: 'mutation',
      path,
      input,
      context: opts?.context,
      signal: opts?.signal,
    });
  }


def get_bucket(
        self,
        environment: "Environment",
        name: str,
        filename: str | None,
        source: str,
    ) -> Bucket:
        """Return a cache bucket for the given template.  All arguments are
        mandatory but filename may be `None`.
        """
        key = self.get_cache_key(name, filename)
        checksum = self.get_source_checksum(source)
        bucket = Bucket(environment, key, checksum)
        self.load_bytecode(bucket)
        return bucket


def _try_requires_both(
        self,
        other: Incompatibility,
        this_line: int | None,
        other_line: int | None,
    ) -> str | None:
        if len(self._terms) == 1 or len(other.terms) == 1:
            return None

        this_positive = self._single_term_where(lambda term: term.is_positive())
        if this_positive is None:
            return None

        other_positive = other._single_term_where(lambda term: term.is_positive())
        if other_positive is None:
            return None

        if this_positive.dependency != other_positive.dependency:
            return None

        this_negatives = " or ".join(
            [self._terse(term) for term in self._terms if not term.is_positive()]
        )

        other_negatives = " or ".join(
            [self._terse(term) for term in other.terms if not term.is_positive()]
        )

        buffer = [self._terse(this_positive, allow_every=True) + " "]
        is_dependency = isinstance(self.cause, DependencyCauseError) and isinstance(
            other.cause, DependencyCauseError
        )

        if is_dependency:
            buffer.append("depends on")
        else:
            buffer.append("requires")

        buffer.append(f" both {this_negatives}")
        if this_line is not None:
            buffer.append(f" ({this_line})")

        buffer.append(f" and {other_negatives}")

        if other_line is not None:
            buffer.append(f" ({other_line})")

        return "".join(buffer)


def create_deprecated_class(
    name: str,
    new_class: type,
    clsdict: dict[str, Any] | None = None,
    warn_category: type[Warning] = ScrapyDeprecationWarning,
    warn_once: bool = True,
    old_class_path: str | None = None,
    new_class_path: str | None = None,
    subclass_warn_message: str = "{cls} inherits from deprecated class {old}, please inherit from {new}.",
    instance_warn_message: str = "{cls} is deprecated, instantiate {new} instead.",
) -> type:
    """
    Return a "deprecated" class that causes its subclasses to issue a warning.
    Subclasses of ``new_class`` are considered subclasses of this class.
    It also warns when the deprecated class is instantiated, but do not when
    its subclasses are instantiated.

    It can be used to rename a base class in a library. For example, if we
    have

        class OldName(SomeClass):
            # ...

    and we want to rename it to NewName, we can do the following::

        class NewName(SomeClass):
            # ...

        OldName = create_deprecated_class('OldName', NewName)

    Then, if user class inherits from OldName, warning is issued. Also, if
    some code uses ``issubclass(sub, OldName)`` or ``isinstance(sub(), OldName)``
    checks they'll still return True if sub is a subclass of NewName instead of
    OldName.
    """

    # https://github.com/python/mypy/issues/4177
    class DeprecatedClass(new_class.__class__):  # type: ignore[misc,name-defined]
        # pylint: disable=no-self-argument
        deprecated_class: type | None = None
        warned_on_subclass: bool = False

        def __new__(  # pylint: disable=bad-classmethod-argument
            metacls, name: str, bases: tuple[type, ...], clsdict_: dict[str, Any]
        ) -> type:
            cls = super().__new__(metacls, name, bases, clsdict_)
            if metacls.deprecated_class is None:
                metacls.deprecated_class = cls
            return cls

        def __init__(cls, name: str, bases: tuple[type, ...], clsdict_: dict[str, Any]):
            meta = cls.__class__
            old = meta.deprecated_class
            if old in bases and not (warn_once and meta.warned_on_subclass):
                meta.warned_on_subclass = True
                msg = subclass_warn_message.format(
                    cls=_clspath(cls),
                    old=_clspath(old, old_class_path),
                    new=_clspath(new_class, new_class_path),
                )
                if warn_once:
                    msg += " (warning only on first subclass, there may be others)"
                warnings.warn(msg, warn_category, stacklevel=2)
            super().__init__(name, bases, clsdict_)

        # see https://www.python.org/dev/peps/pep-3119/#overloading-isinstance-and-issubclass
        # and https://docs.python.org/reference/datamodel.html#customizing-instance-and-subclass-checks
        # for implementation details
        def __instancecheck__(cls, inst: Any) -> bool:
            return any(cls.__subclasscheck__(c) for c in (type(inst), inst.__class__))

        def __subclasscheck__(cls, sub: type) -> bool:
            if cls is not DeprecatedClass.deprecated_class:
                # we should do the magic only if second `issubclass` argument
                # is the deprecated class itself - subclasses of the
                # deprecated class should not use custom `__subclasscheck__`
                # method.
                return super().__subclasscheck__(sub)

            if not inspect.isclass(sub):
                raise TypeError("issubclass() arg 1 must be a class")

            mro = getattr(sub, "__mro__", ())
            return any(c in {cls, new_class} for c in mro)

        def __call__(cls, *args: Any, **kwargs: Any) -> Any:
            old = DeprecatedClass.deprecated_class
            if cls is old:
                msg = instance_warn_message.format(
                    cls=_clspath(cls, old_class_path),
                    new=_clspath(new_class, new_class_path),
                )
                warnings.warn(msg, warn_category, stacklevel=2)
            return super().__call__(*args, **kwargs)

    deprecated_cls = DeprecatedClass(name, (new_class,), clsdict or {})

    try:
        frm = inspect.stack()[1]
        parent_module = inspect.getmodule(frm[0])
        if parent_module is not None:
            deprecated_cls.__module__ = parent_module.__name__
    except Exception as e:
        # Sometimes inspect.stack() fails (e.g. when the first import of
        # deprecated class is in jinja2 template). __module__ attribute is not
        # important enough to raise an exception as users may be unable
        # to fix inspect.stack() errors.
        warnings.warn(f"Error detecting parent module: {e!r}")

    return deprecated_cls


def _init_pyproject(
        self,
        project_path: Path,
        allow_interactive: bool = True,
        layout_name: str = "standard",
        readme_format: str = "md",
        allow_layout_creation_on_empty: bool = False,
    ) -> int:
        from poetry.core.vcs.git import GitConfig

        from poetry.config.config import Config
        from poetry.layouts import layout
        from poetry.pyproject.toml import PyProjectTOML

        is_interactive = self.io.is_interactive() and allow_interactive

        pyproject = PyProjectTOML(project_path / "pyproject.toml")

        if pyproject.file.exists():
            if pyproject.is_poetry_project():
                self.line_error(
                    "<error>A pyproject.toml file with a project and/or"
                    " a poetry section already exists.</error>"
                )
                return 1

            if pyproject.data.get("build-system"):
                self.line_error(
                    "<error>A pyproject.toml file with a defined build-system already"
                    " exists.</error>"
                )
                return 1

        vcs_config = GitConfig()

        if is_interactive:
            self.line("")
            self.line(
                "This command will guide you through creating your"
                " <info>pyproject.toml</> config."
            )
            self.line("")

        name = self.option("name")
        if not name:
            name = project_path.name.lower()

            if is_interactive:
                question = self.create_question(
                    f"Package name [<comment>{name}</comment>]: ", default=name
                )
                name = self.ask(question)

        version = "0.1.0"

        if is_interactive:
            question = self.create_question(
                f"Version [<comment>{version}</comment>]: ", default=version
            )
            version = self.ask(question)

        description = self.option("description") or ""
        if not description and is_interactive:
            description = self.ask(self.create_question("Description []: ", default=""))

        author = self.option("author")
        if not author and vcs_config.get("user.name"):
            author = vcs_config["user.name"]
            author_email = vcs_config.get("user.email")
            if author_email:
                author += f" <{author_email}>"

        if is_interactive:
            question = self.create_question(
                f"Author [<comment>{author}</comment>, n to skip]: ", default=author
            )
            question.set_validator(lambda v: self._validate_author(v, author))
            author = self.ask(question)

        authors = [author] if author else []

        license_name = self.option("license")
        if not license_name and is_interactive:
            license_name = self.ask(self.create_question("License []: ", default=""))

        python = self.option("python")
        if not python:
            config = Config.create()
            python = (
                ">="
                + Python.get_preferred_python(config, self.io).minor_version.to_string()
            )

            if is_interactive:
                question = self.create_question(
                    f"Compatible Python versions [<comment>{python}</comment>]: ",
                    default=python,
                )
                python = self.ask(question)

        if is_interactive:
            self.line("")

        requirements: Requirements = {}
        if self.option("dependency"):
            requirements = self._format_requirements(
                self._determine_requirements(self.option("dependency"))
            )

        question_text = "Would you like to define your main dependencies interactively?"
        help_message = """\
        You can specify a package in the following forms:
          - A single name (requests): this will search for matches on PyPI
          - A name and a constraint (requests@^2.23.0)
          - A git url (git+https://github.com/python-poetry/poetry.git)
          - A git url with a revision\
         (git+https://github.com/python-poetry/poetry.git#develop)
          - A file path (../my-package/my-package.whl)
          - A directory (../my-package/)
          - A url (https://example.com/packages/my-package-0.1.0.tar.gz)
        """

        help_displayed = False
        if is_interactive and self.confirm(question_text, True):
            self.line(help_message)
            help_displayed = True
            requirements.update(
                self._format_requirements(self._determine_requirements([]))
            )
            self.line("")

        dev_requirements: Requirements = {}
        if self.option("dev-dependency"):
            dev_requirements = self._format_requirements(
                self._determine_requirements(self.option("dev-dependency"))
            )

        question_text = (
            "Would you like to define your development dependencies interactively?"
        )
        if is_interactive and self.confirm(question_text, True):
            if not help_displayed:
                self.line(help_message)

            dev_requirements.update(
                self._format_requirements(self._determine_requirements([]))
            )

            self.line("")

        layout_ = layout(layout_name)(
            name,
            version,
            description=description,
            author=authors[0] if authors else None,
            readme_format=readme_format,
            license=license_name,
            python=python,
            dependencies=requirements,
            dev_dependencies=dev_requirements,
        )

        create_layout = not project_path.exists() or (
            allow_layout_creation_on_empty and not any(project_path.iterdir())
        )

        if create_layout:
            layout_.create(project_path, with_pyproject=False)

        content = layout_.generate_project_content(project_path)
        for section, item in content.items():
            pyproject.data.append(section, item)

        if is_interactive:
            self.line("<info>Generated file</info>")
            self.line("")
            self.line(pyproject.data.as_string().replace("\r\n", "\n"))
            self.line("")

        if is_interactive and not self.confirm("Do you confirm generation?", True):
            self.line_error("<error>Command aborted</error>")

            return 1

        pyproject.save()

        if create_layout:
            path = project_path.resolve()

            with suppress(ValueError):
                path = path.relative_to(Path.cwd())

            self.line(
                f"Created package <info>{layout_._package_name}</> in"
                f" <fg=blue>{path.as_posix()}</>"
            )

        return 0


static async mergeObjectAsync(
    status: ParseStatus,
    pairs: { key: ParseReturnType<any>; value: ParseReturnType<any> }[]
  ): Promise<SyncParseReturnType<any>> {
    const syncPairs: ObjectPair[] = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value,
      });
    }
    return ParseStatus.mergeObjectSync(status, syncPairs);
  }


hasPendingRequests getRequests hasPendingSubscriptions setupWebSocketListeners reconnect

public getPendingRequests() {
    return Object.values(this.pendingRequests);
  }


def resolve_color_default(color: bool | None = None) -> bool | None:
    """Internal helper to get the default value of the color flag.  If a
    value is passed it's returned unchanged, otherwise it's looked up from
    the current context.
    """
    if color is not None:
        return color

    ctx = get_current_context(silent=True)

    if ctx is not None:
        return ctx.color

    return None


export function getQueryKey<TProcedureOrRouter extends ProcedureOrRouter>(
  procedureOrRouter: TProcedureOrRouter,
  ..._params: GetParams<TProcedureOrRouter>
) {
  const [input, type] = _params;

  // @ts-expect-error - we don't expose _def on the type layer
  const path = procedureOrRouter._def().path as string[];
  const queryKey = getQueryKeyInternal(path, input, type ?? 'any');
  return queryKey;
}


export function _isoDuration<T extends schemas.$ZodISODuration>(
  Class: util.SchemaClass<T>,
  params?: string | $ZodISODurationParams | $ZodCheckISODurationParams
): T {
  return new Class({
    type: "string",
    format: "duration",
    check: "string_format",
    ...util.normalizeParams(params),
  });
}


@classmethod
    def normalize(cls, policy: str) -> list[str]:
        if boolean_validator(policy):
            if boolean_normalizer(policy):
                return [":all:"]
            else:
                return [":none:"]

        return list(
            {
                name.strip() if cls.is_reserved(name) else canonicalize_name(name)
                for name in policy.strip().split(",")
                if name
            }
        )


def _define_ref(self, name: str, load: tuple[str, str | None] | None = None) -> str:
        ident = f"l_{self.level}_{name}"
        self.refs[name] = ident
        if load is not None:
            self.loads[ident] = load
        return ident


def get_html_report(
    environment,
    show_download_link=True,
    theme="",
):
    request_stats = environment.runner.stats

    start_time = format_utc_timestamp(request_stats.start_time)

    if end_ts := request_stats.last_request_timestamp:
        end_time = format_utc_timestamp(end_ts)
    else:
        end_ts = request_stats.start_time
        end_time = start_time

    host = None
    if environment.host:
        host = environment.host
    elif environment.runner.user_classes:
        all_hosts = {l.host for l in environment.runner.user_classes}
        if len(all_hosts) == 1:
            host = list(all_hosts)[0]

    requests_statistics = list(chain(stats.sort_stats(request_stats.entries), [request_stats.total]))
    failures_statistics = stats.sort_stats(request_stats.errors)
    exceptions_statistics = [
        {**exc, "nodes": ", ".join(exc["nodes"])} for exc in environment.runner.exceptions.values()
    ]

    if request_stats.history and request_stats.history[-1]["time"] < end_time:
        stats.update_stats_history(environment.runner, end_time)
    history = request_stats.history

    is_distributed = isinstance(environment.runner, MasterRunner)
    user_spawned = (
        environment.runner.reported_user_classes_count if is_distributed else environment.runner.user_classes_count
    )

    if environment.runner.state in [STATE_STOPPED, STATE_STOPPING]:
        user_spawned = environment.runner.final_user_classes_count

    task_data = {
        "per_class": get_ratio(environment.user_classes, user_spawned, False),
        "total": get_ratio(environment.user_classes, user_spawned, True),
    }

    return render_template_from(
        "report.html",
        template_args={
            "is_report": True,
            "requests_statistics": [stat.to_dict() for stat in requests_statistics],
            "failures_statistics": [stat.to_dict() for stat in failures_statistics],
            "exceptions_statistics": [stat for stat in exceptions_statistics],
            "response_time_statistics": [
                {
                    "name": stat.name,
                    "method": stat.method or "",
                    **{
                        str(percentile): stat.get_response_time_percentile(percentile)
                        for percentile in PERCENTILES_FOR_HTML_REPORT
                    },
                }
                for stat in requests_statistics
            ],
            "start_time": start_time,
            "end_time": end_time,
            "duration": format_duration(request_stats.start_time, end_ts),
            "host": str(host),
            "history": history,
            "show_download_link": show_download_link,
            "locustfile": str(environment.locustfile),
            "tasks": task_data,
            "percentiles_to_chart": stats.PERCENTILES_TO_CHART,
            "profile": str(environment.profile) if environment.profile else None,
        },
        theme="dark" if theme == "dark" else "light",
    )


def remove(self, job: Union[Job, str], pipeline: Optional['Pipeline'] = None, delete_job: bool = False):
        """Removes job from registry and deletes it if `delete_job == True`

        Args:
            job (Job|str): The Job to remove from the registry, or job_id
            pipeline (Pipeline|None): The Redis Pipeline. Defaults to None.
            delete_job (bool, optional): If should delete the job.. Defaults to False.
        """
        connection = pipeline if pipeline is not None else self.connection
        job_id = job.id if isinstance(job, self.job_class) else job
        result = connection.zrem(self.key, job_id)
        if delete_job:
            if isinstance(job, self.job_class):
                job_instance = job
            else:
                job_instance = Job.fetch(job_id, connection=connection, serializer=self.serializer)
            job_instance.delete()
        return result


min(minLength: number, message?: errorUtil.ErrMessage) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message),
    });
  }


def delete_dependents(self, pipeline: Optional['Pipeline'] = None):
        """Delete jobs depending on this job.

        Args:
            pipeline (Optional[Pipeline], optional): Redis' pipeline. Defaults to None.
        """
        connection = pipeline if pipeline is not None else self.connection
        for dependent_id in self.dependent_ids:
            try:
                job = Job.fetch(dependent_id, connection=self.connection, serializer=self.serializer)
                job.delete(pipeline=pipeline, remove_from_queue=False)
            except NoSuchJobError:
                # It could be that the dependent job was never saved to redis
                pass
        connection.delete(self.dependents_key)


def get_status(self, refresh: bool = True) -> JobStatus:
        """Gets the Job Status

        Args:
            refresh (bool, optional): Whether to refresh the Job. Defaults to True.

        Raises:
            InvalidJobOperation: If refreshing and nothing is returned from the `HGET` operation.

        Returns:
            status (JobStatus): The Job Status
        """
        if refresh:
            status = self.connection.hget(self.key, 'status')
            if not status:
                raise InvalidJobOperation(f'Failed to retrieve status for job: {self.id}')
            self._status = JobStatus(as_text(status))
        return self._status


export function pick(schema: schemas.$ZodObject, mask: Record<string, unknown>): any {
  const currDef = schema._zod.def;

  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".pick() cannot be used on object schemas containing refinements");
  }

  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape: Writeable<schemas.$ZodShape> = {};
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key]) continue;
        newShape[key] = currDef.shape[key]!;
      }

      assignProp(this, "shape", newShape); // self-caching
      return newShape;
    },
    checks: [],
  });

  return clone(schema, def) as any;
}


export default function useForm() {
  const [errors, setErrors] = useState<Errors>({});
  const [isValid, setIsValid] = useState<boolean>(true);

  const validate = (
    name: string,
    value: string,
    rules: ValidationRules,
    { onlyDelete } = { onlyDelete: false },
  ) => {
    const newErrors = { ...errors };
    let errorMessage;
    const failedMatch =
      rules.match &&
      Array.isArray(rules.match) &&
      rules.match.find(({ pattern }) => !new RegExp(pattern).test(value));

    if (rules.minLength && value.length < rules.minLength) {
      errorMessage = `Please enter at least ${rules.minLength} characters`;
    } else if (failedMatch) {
      errorMessage = failedMatch.message || 'Invalid format';
    } else if (
      rules.match &&
      !Array.isArray(rules.match) &&
      !new RegExp(rules.match.pattern).test(value)
    ) {
      errorMessage = rules.match.message || 'Invalid format';
    } else {
      delete newErrors[name];
    }

    if (errorMessage && !onlyDelete) {
      newErrors[name] = errorMessage;
    }

    setErrors(newErrors);
    setIsValid(Object.keys(newErrors).length === 0);
  };

  const register = (name: string, rules: ValidationRules, mode = 'onChange') => {
    const alertLevelProps =
      errors[name] && rules.level
        ? {
            color: rules.level,
            focused: true,
            FormHelperTextProps: {
              sx: { color: (theme: Theme) => theme.palette.warning.main },
            },
          }
        : {};

    return {
      ...alertLevelProps,
      name,
      onChange: ({ target: { value } }: ChangeEvent<HTMLInputElement>) =>
        validate(name, value, rules, { onlyDelete: true }),
      [mode]: ({ target: { value } }: ChangeEvent<HTMLInputElement>) =>
        validate(name, value, rules),
      error: !!errors[name] && !rules.level,
      helperText: errors[name] || '',
    };
  };

  return { register, isValid };
}


def get_ratio(user_classes: list[type[User]], user_spawned: dict[str, int], total: bool) -> dict[str, dict[str, float]]:
    user_count = sum(user_spawned.values()) or 1
    ratio_percent: dict[type[User], float] = {u: user_spawned.get(u.__name__, 0) / user_count for u in user_classes}

    task_dict: dict[str, dict[str, float]] = {}
    for u, r in ratio_percent.items():
        d = {"ratio": r}
        d["tasks"] = _get_task_ratio(u.tasks, total, r)
        task_dict[u.__name__] = d

    return task_dict


@functools.lru_cache
    def _wait_for_workers_report_after_ramp_up(self) -> float:
        """
        The amount of time to wait after a ramp-up in order for all the workers to report their state
        to the master. If not supplied by the user, it is 1000ms by default. If the supplied value is a number,
        it is taken as-is. If the supplied value is a pattern like "some_number * WORKER_REPORT_INTERVAL",
        the value will be "some_number * WORKER_REPORT_INTERVAL". The most sensible value would be something
        like "1.25 * WORKER_REPORT_INTERVAL". However, some users might find it too high, so it is left
        to a relatively small value of 1000ms by default.
        """
        locust_wait_for_workers_report_after_ramp_up = os.getenv("LOCUST_WAIT_FOR_WORKERS_REPORT_AFTER_RAMP_UP")
        if locust_wait_for_workers_report_after_ramp_up is None:
            return 1.0

        match = re.search(
            r"^(?P<coeff>(\d+)|(\d+\.\d+))[ ]*\*[ ]*WORKER_REPORT_INTERVAL$",
            locust_wait_for_workers_report_after_ramp_up,
        )
        if match is None:
            assert float(locust_wait_for_workers_report_after_ramp_up) >= 0
            return float(locust_wait_for_workers_report_after_ramp_up)
        else:
            return float(match.group("coeff")) * WORKER_REPORT_INTERVAL


export function isFormData(value: unknown): value is FormData {
  if (typeof FormData === 'undefined') {
    // FormData is not supported
    return false;
  }
  return value instanceof FormData;
}


def update_stats_history(runner: Runner, timestamp: str | None = None) -> None:
    stats = runner.stats
    timestamp = timestamp or format_utc_timestamp(time.time())
    current_response_time_percentiles = {
        f"response_time_percentile_{percentile}": [
            timestamp,
            stats.total.get_current_response_time_percentile(percentile) or 0,
        ]
        for percentile in PERCENTILES_TO_CHART
    }

    r = {
        **current_response_time_percentiles,
        "current_rps": [timestamp, stats.total.current_rps or 0],
        "current_fail_per_sec": [timestamp, stats.total.current_fail_per_sec or 0],
        "total_avg_response_time": [timestamp, proper_round(stats.total.avg_response_time, digits=2)],
        "user_count": [timestamp, runner.user_count or 0],
        "time": timestamp,
    }
    stats.history.append(r)


export function createTRPCOptionsResult(value: {
  path: string[];
}): TRPCQueryOptionsResult['trpc'] {
  const path = value.path.join('.');

  return {
    path,
  };
}


def parse_composite_key(composite_key: str) -> tuple[str, str]:
    """Method returns a parsed composite key.

    Args:
        composite_key (str): the composite key to parse

    Returns:
        tuple[str, str]: tuple of job id and the execution id
    """
    result = composite_key.split(':')
    if len(result) == 1:
        # StartedJobRegistry contains a composite key under the sorted set
        # a single job_id should've never ended up in the set, but
        # just in case there's a regression (tests don't show any)
        warnings.warn(
            f'Composite key must contain job_id:execution_id, got {composite_key}',
            DeprecationWarning,
        )
        return (result[0], '')
    job_id, execution_id = result
    return (job_id, execution_id)


each shouldUseStrictIteration isDraftable shallowCopy isFrozen

function currentImpl(value: any): any {
	if (!isDraftable(value) || isFrozen(value)) return value
	const state: ImmerState | undefined = value[DRAFT_STATE]
	let copy: any
	let strict = true // Default to strict for compatibility
	if (state) {
		if (!state.modified_) return state.base_
		// Optimization: avoid generating new drafts during copying
		state.finalized_ = true
		copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_)
		strict = state.scope_.immer_.shouldUseStrictIteration()
	} else {
		copy = shallowCopy(value, true)
	}
	// recurse
	each(
		copy,
		(key, childValue) => {
			set(copy, key, currentImpl(childValue))
		},
		strict
	)
	if (state) {
		state.finalized_ = false
	}
	return copy
}


def build_response(self, req, resp):
        """Builds a :class:`Response <requests.Response>` object from a urllib3
        response. This should not be called from user code, and is only exposed
        for use when subclassing the
        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`

        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
        :param resp: The urllib3 response object.
        :rtype: requests.Response
        """
        response = Response()

        # Fallback to None if there's no status_code, for whatever reason.
        response.status_code = getattr(resp, "status", None)

        # Make headers case-insensitive.
        response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))

        # Set encoding.
        response.encoding = get_encoding_from_headers(response.headers)
        response.raw = resp
        response.reason = response.raw.reason

        if isinstance(req.url, bytes):
            response.url = req.url.decode("utf-8")
        else:
            response.url = req.url

        # Add new cookies from the server.
        extract_cookies_to_jar(response.cookies, req, resp)

        # Give the Response some context.
        response.request = req
        response.connection = self

        return response


def add_argument(self, *args, **kwargs) -> configargparse.Action:
        """
        This method supports the same args as ArgumentParser.add_argument(..)
        as well as the additional args below.

        Arguments:
            include_in_web_ui: If True (default), the argument will show in the UI.
            is_secret: If True (default is False) and include_in_web_ui is True, the argument will show in the UI with a password masked text input.
            is_required: If True (default is False) and include_in_web_ui is True, the argument will show in the UI as a required form field.
            is_multiple: If True (default is False) and include_in_web_ui is True, the argument will show in the UI as a multiple select form field.

        Returns:
            argparse.Action: the new argparse action
        """
        include_in_web_ui = kwargs.pop("include_in_web_ui", True)
        is_secret = kwargs.pop("is_secret", False)
        is_required = kwargs.pop("is_required", False)
        is_multiple = kwargs.pop("is_multiple", False)
        action = super().add_argument(*args, **kwargs)
        action.include_in_web_ui = include_in_web_ui
        action.is_secret = is_secret
        action.is_required = is_required
        action.is_multiple = is_multiple
        return action


get agent(): Agents {
		return this.#internals.agent;
	}


next(event) {
            const transformed = transformResult(event, transformer.output);

            if (!transformed.ok) {
              observer.error(TRPCClientError.from(transformed.error));
              return;
            }

            observer.next({
              result: transformed.result,
            });
          },


createDraft enableMapSet prepareSetCopy get

export function createProxyProxy<T extends Objectish>(
	base: T,
	parent?: ImmerState
): [Drafted<T, ProxyState>, ProxyState] {
	const baseIsArray = isArray(base)
	const state: ProxyState = {
		type_: baseIsArray ? ArchType.Array : (ArchType.Object as any),
		// Track which produce call this is associated with.
		scope_: parent ? parent.scope_ : getCurrentScope()!,
		// True for both shallow and deep changes.
		modified_: false,
		// Used during finalization.
		finalized_: false,
		// Track which properties have been assigned (true) or deleted (false).
		// actually instantiated in `prepareCopy()`
		assigned_: undefined,
		// The parent draft state.
		parent_: parent,
		// The base state.
		base_: base,
		// The base proxy.
		draft_: null as any, // set below
		// The base copy with any updated values.
		copy_: null,
		// Called by the `produce` function.
		revoke_: null as any,
		isManual_: false,
		// `callbacks` actually gets assigned in `createProxy`
		callbacks_: undefined as any
	}

	// the traps must target something, a bit like the 'real' base.
	// but also, we need to be able to determine from the target what the relevant state is
	// (to avoid creating traps per instance to capture the state in closure,
	// and to avoid creating weird hidden properties as well)
	// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)
	// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb
	let target: T = state as any
	let traps: ProxyHandler<object | Array<any>> = objectTraps
	if (baseIsArray) {
		target = [state] as any
		traps = arrayTraps
	}

	const {revoke, proxy} = Proxy.revocable(target, traps)
	state.draft_ = proxy as any
	state.revoke_ = revoke
	return [proxy as any, state]
}


def _download(self, operation: Install | Update) -> Path:
        link = self._chooser.choose_for(operation.package)

        if link.yanked:
            # Store yanked warnings in a list and print after installing, so they can't
            # be overlooked. Further, printing them in the concerning section would have
            # the risk of overwriting the warning, so it is only briefly visible.
            message = (
                f"The file chosen for install of {operation.package.pretty_name} "
                f"{operation.package.pretty_version} ({link.show_url}) is yanked."
            )
            if link.yanked_reason:
                message += f" Reason for being yanked: {link.yanked_reason}"
            self._yanked_warnings.append(message)

        return self._download_link(operation, link)


values(): IterableIterator<any> {
			const iterator = this.keys()
			return {
				[Symbol.iterator]: () => this.values(),
				next: () => {
					const r = iterator.next()
					/* istanbul ignore next */
					if (r.done) return r
					const value = this.get(r.value)
					return {
						done: false,
						value
					}
				}
			} as any
		}


open wsLink setupWebSocketListeners handleIncomingRequest

private send(
    messageOrMessages: TRPCClientOutgoingMessage | TRPCClientOutgoingMessage[],
  ) {
    if (!this.activeConnection.isOpen()) {
      throw new Error('Active connection is not open');
    }

    const messages =
      messageOrMessages instanceof Array
        ? messageOrMessages
        : [messageOrMessages];
    this.activeConnection.ws.send(
      this.encoder.encode(messages.length === 1 ? messages[0] : messages),
    );
  }


export function _multipleOf(
  value: number | bigint,
  params?: string | $ZodCheckMultipleOfParams
): checks.$ZodCheckMultipleOf {
  return new checks.$ZodCheckMultipleOf({
    check: "multiple_of",
    ...util.normalizeParams(params),
    value,
  });
}


def auth_interactive(self, username, handler, submethods=""):
        """
        response_list = handler(title, instructions, prompt_list)
        """
        # Unlike most siblings, this auth method _does_ require other
        # superclass handlers (eg userauth info request) to understand
        # what's going on, so we still set some self attributes.
        self.auth_method = "keyboard_interactive"
        self.interactive_handler = handler

        def finish(m):
            # Empty string for deprecated language tag field, per RFC 4256:
            # https://www.rfc-editor.org/rfc/rfc4256#section-3.1
            m.add_string("")
            m.add_string(submethods)

        return self.send_auth_request(username, "keyboard-interactive", finish)


def new_dispatch(
        self, target_user_count: int, spawn_rate: float, user_classes: list[type[User]] | None = None
    ) -> None:
        """
        Initialize a new dispatch cycle.

        :param target_user_count: The desired user count at the end of the dispatch cycle
        :param spawn_rate: The spawn rate
        :param user_classes: The user classes to be used for the new dispatch
        """
        if user_classes is not None and self._user_classes != sorted(user_classes, key=attrgetter("__name__")):
            self._user_classes = sorted(user_classes, key=attrgetter("__name__"))
            self._user_generator = self._user_gen()

        self._target_user_count = target_user_count

        self._spawn_rate = spawn_rate

        self._user_count_per_dispatch_iteration = max(1, math.floor(self._spawn_rate))

        self._wait_between_dispatch = self._user_count_per_dispatch_iteration / self._spawn_rate

        self._initial_users_on_workers = self._users_on_workers

        self._users_on_workers = self._fast_users_on_workers_copy(self._initial_users_on_workers)

        self._current_user_count = self.get_current_user_count()

        self._dispatcher_generator = self._dispatcher()

        self._dispatch_iteration_durations.clear()


def new_func(
        self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any
    ) -> t.Any:
        # Only optimize if the frame is not volatile
        if self.optimizer is not None and not frame.eval_ctx.volatile:
            new_node = self.optimizer.visit(node, frame.eval_ctx)

            if new_node != node:
                return self.visit(new_node, frame)

        return f(self, node, frame, **kwargs)


def get_source(
        self, environment: "Environment", template: str
    ) -> tuple[str, str | None, t.Callable[[], bool] | None]:
        """Get the template source, filename and reload helper for a template.
        It's passed the environment and template name and has to return a
        tuple in the form ``(source, filename, uptodate)`` or raise a
        `TemplateNotFound` error if it can't locate the template.

        The source part of the returned tuple must be the source of the
        template as a string. The filename should be the name of the
        file on the filesystem if it was loaded from there, otherwise
        ``None``. The filename is used by Python for the tracebacks
        if no loader extension is used.

        The last item in the tuple is the `uptodate` function.  If auto
        reloading is enabled it's always called to check if the template
        changed.  No arguments are passed so the function must store the
        old state somewhere (for example in a closure).  If it returns `False`
        the template will be reloaded.
        """
        if not self.has_source_access:
            raise RuntimeError(
                f"{type(self).__name__} cannot provide access to the source"
            )
        raise TemplateNotFound(template)