import { i as isElectron, n as matchesDomain } from "./set-request-cookies-BJJhsU4A.js";
import { t as _plugin_vue_export_helper_default } from "./_plugin-vue_export-helper-BmmBcIzD.js";
import { t as getSnippet } from "./get-snippet-DBRUSfZ2.js";
import { capitalize, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, mergeModels, mergeProps, normalizeStyle, onBeforeMount, openBlock, ref, renderSlot, resolveDynamicComponent, toDisplayString, unref, useId, useModel, watch, withCtx } from "vue";
import { ScalarButton, ScalarCard, ScalarCardFooter, ScalarCardHeader, ScalarCardSection, ScalarCodeBlock, ScalarCombobox, ScalarListbox, ScalarVirtualText } from "@scalar/components";
import { encode } from "js-base64";
import { isDefined } from "@scalar/helpers/array/is-defined";
import { mergeUrls } from "@scalar/helpers/url/merge-urls";
import { getHttpMethodInfo } from "@scalar/helpers/http/http-info";
import { ScalarIconCaretDown } from "@scalar/icons";
import { replaceVariables } from "@scalar/helpers/regex/replace-variables";
import { getResolvedRef } from "@scalar/workspace-store/helpers/get-resolved-ref";
import { isObject } from "@scalar/helpers/object/is-object";
import { unpackProxyObject } from "@scalar/workspace-store/helpers/unpack-proxy";
import { canMethodHaveBody } from "@scalar/helpers/http/can-method-have-body";
import { resolve } from "@scalar/workspace-store/resolve";
import { freezeElement } from "@scalar/helpers/dom/freeze-element";
import { AVAILABLE_CLIENTS, snippetz } from "@scalar/snippetz";
import { json2xml } from "@scalar/helpers/file/json2xml";
import { normalizeHttpMethod } from "@scalar/helpers/http/normalize-http-method";
//#region src/v2/blocks/operation-code-sample/helpers/get-resolved-ref-deep.ts
/**
* Recursively resolves all $ref objects in a data structure to their actual values.
* Traverses through objects, arrays, and nested structures to find and resolve
* any $ref references at any depth level.
*
* Handles circular references gracefully by detecting them and returning '[circular]'
* to prevent infinite loops.
*/
var getResolvedRefDeep = (node) => {
	const visited = /* @__PURE__ */ new WeakSet();
	const cachedResults = /* @__PURE__ */ new WeakMap();
	const resolveNode = (current) => {
		if (!isObject(current) && !Array.isArray(current)) return current;
		const rawValue = unpackProxyObject(current, { depth: 1 });
		if (cachedResults.has(rawValue)) return cachedResults.get(rawValue);
		if (visited.has(rawValue)) return "[circular]";
		visited.add(rawValue);
		if ("$ref" in current) {
			const result = resolveNode(getResolvedRef(current));
			cachedResults.set(rawValue, result);
			return result;
		}
		if (Array.isArray(current)) {
			const result = current.map(resolveNode);
			cachedResults.set(rawValue, result);
			return result;
		}
		const result = Object.fromEntries(Object.entries(current).map(([key, value]) => [key, resolveNode(value)]));
		cachedResults.set(rawValue, result);
		return result;
	};
	return resolveNode(node);
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/get-example.ts
/** Helper to get example from examples object with fallback to example field */
var getExampleFromExamples = (examples, exampleField, exampleKey) => {
	if (!examples && !exampleField) return;
	const hasExamples = !!examples && Object.keys(examples).length > 0;
	const key = exampleKey || Object.keys(examples ?? {})[0] || "";
	const example = getResolvedRefDeep(examples?.[key]);
	if (example !== void 0) return example;
	if ((!hasExamples || !exampleKey) && exampleField !== void 0) return { value: getResolvedRefDeep(exampleField) };
};
/**
* Resolve an example value for a parameter or requestBody from either `examples` or `content.*.examples`.
* Or the [deprecated] `example` field.
* If no exampleKey is provided it will fallback to the first example in the examples object then the [deprecated]
* `example` field.
* Used both for send-request and generating code snippets.
*/
var getExample = (param, exampleKey, contentType) => {
	if ("content" in param) {
		const content = param.content?.[contentType ?? Object.keys(param.content)[0] ?? ""];
		const result = getExampleFromExamples(content?.examples, content?.example, exampleKey);
		if (result !== void 0) return result;
	}
	if ("examples" in param || "example" in param) {
		const result = getExampleFromExamples(param.examples, param.example, exampleKey);
		if (result !== void 0) return result;
	}
	const resolvedParam = getResolvedRefDeep(param);
	if ("schema" in resolvedParam && resolvedParam.schema) {
		const schema = resolvedParam.schema;
		if ("default" in schema && schema.default !== void 0) return { value: schema.default };
		if ("enum" in schema && schema.enum?.[0] !== void 0) return { value: schema.enum[0] };
		if ("examples" in schema && schema.examples?.[0] !== void 0) return { value: schema.examples[0] };
		if ("example" in schema && schema.example !== void 0) return { value: schema.example };
	}
};
//#endregion
//#region src/v2/blocks/request-block/helpers/get-default-headers.ts
var APP_VERSION = "2.38.2";
/** Default Accept header value to accept all response types. */
var DEFAULT_ACCEPT = "*/*";
/**
* Creates a default header object with the override status determined by existing headers.
*
* @param name The header name
* @param defaultValue The header value
* @param existingHeaders Set of existing header names (lowercase) from the operation
* @returns A DefaultHeader object
*/
var createDefaultHeader = (name, defaultValue, existingHeaders) => ({
	name,
	defaultValue,
	isOverridden: existingHeaders.has(name.toLowerCase())
});
/**
* Generates a list of default headers for an OpenAPI operation and HTTP method.
*
* This function intelligently adds standard HTTP headers based on the request context:
* - Content-Type: Added only if the HTTP method supports a request body and the OpenAPI operation
*   defines a request body content type. Uses the selected content type from the operation or the
*   first defined request body content type.
* - Accept: Derived from the 2xx response content types in the spec (joined as a comma-separated list), falling back to a wildcard.
* - User-Agent: Added in Electron environments (desktop app or proxy) to identify the client.
*
* The function respects OpenAPI operation parameters and marks headers as overridden
* if they are explicitly defined in the operation. It also supports hiding disabled
* headers for specific request examples using x-scalar-disable-parameters.
*
* @param method The HTTP method of the operation (GET, POST, etc.)
* @param operation The OpenAPI OperationObject describing the endpoint
* @param exampleKey The current request example key
* @param hideDisabledHeaders If true, filters out headers marked as disabled for this example
* @returns Array of default header objects with their values and override status
*/
var getDefaultHeaders = ({ method, operation, exampleKey, hideDisabledHeaders = false }) => {
	const existingHeaders = new Set(operation.parameters?.filter((param) => getResolvedRef(param).in === "header").map((param) => getResolvedRef(param).name.toLowerCase()) ?? []);
	const disabledHeaders = operation["x-scalar-disable-parameters"]?.["default-headers"]?.[exampleKey] ?? {};
	const headers = [];
	const requestBody = getResolvedRef(operation.requestBody);
	if (canMethodHaveBody(method) && requestBody) {
		const contentType = requestBody["x-scalar-selected-content-type"]?.[exampleKey] ?? Object.keys(requestBody.content ?? {})[0];
		if (contentType && contentType !== "none") headers.push(createDefaultHeader("Content-Type", contentType, existingHeaders));
	}
	const successResponseKey = Object.keys(operation.responses ?? {}).find((k) => k.startsWith("2"));
	const successResponse = successResponseKey ? getResolvedRef(operation.responses[successResponseKey]) : null;
	const acceptValue = Object.keys(successResponse?.content ?? {}).join(", ") || DEFAULT_ACCEPT;
	headers.push(createDefaultHeader("Accept", acceptValue, existingHeaders));
	if (isElectron() && APP_VERSION) headers.push(createDefaultHeader("User-Agent", `Scalar/${APP_VERSION}`, existingHeaders));
	if (hideDisabledHeaders) return headers.filter((header) => disabledHeaders[header.name.toLowerCase()] !== true);
	return headers;
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/get-example-from-schema.ts
/** Maximum recursion depth to prevent infinite loops in circular references */
var MAX_LEVELS_DEEP = 10;
/** Default name used for additional properties when no custom name is provided */
var DEFAULT_ADDITIONAL_PROPERTIES_NAME = "additionalProperty";
/**
* Pre-computed date/time values to avoid expensive Date operations on every call.
* These are calculated once at module load time for better performance.
*/
var currentISOString = (/* @__PURE__ */ new Date()).toISOString();
var currentDateString = currentISOString.split("T")[0];
var currentTimeString = currentISOString.split("T")[1].split(".")[0];
/**
* Mapping of OpenAPI string formats to example values.
* Used to generate realistic examples for different string formats.
*/
var genericExampleValues = {
	"date-time": currentISOString,
	"date": currentDateString,
	"email": "hello@example.com",
	"hostname": "example.com",
	"idn-email": "jane.doe@example.com",
	"idn-hostname": "example.com",
	"ipv4": "127.0.0.1",
	"ipv6": "51d4:7fab:bfbf:b7d7:b2cb:d4b4:3dad:d998",
	"iri-reference": "/entitiy/1",
	"iri": "https://example.com/entity/123",
	"json-pointer": "/nested/objects",
	"password": "super-secret",
	"regex": "/[a-z]/",
	"relative-json-pointer": "1/nested/objects",
	"time": currentTimeString,
	"uri-reference": "../folder",
	"uri-template": "https://example.com/{id}",
	"uri": "https://example.com",
	"uuid": "123e4567-e89b-12d3-a456-426614174000",
	"object-id": "6592008029c8c3e4dc76256c"
};
/**
* Extract enum values from the propertyNames keyword of an object schema.
* JSON Schema's propertyNames constrains which keys are valid in a map/dict.
*/
var getPropertyNamesEnumValues = (schema) => {
	if (!("propertyNames" in schema) || !schema.propertyNames) return;
	const resolved = resolve.schema(schema.propertyNames);
	if (resolved && "enum" in resolved && Array.isArray(resolved.enum) && resolved.enum.length > 0) return resolved.enum;
};
/**
* Generate example values for string types based on their format.
* Special handling for binary format which returns a File object.
*/
var guessFromFormat = (schema, makeUpRandomData = false, fallback = "") => {
	if ("type" in schema && schema.type === "string" && "format" in schema && schema.format === "binary") return "@filename";
	if (makeUpRandomData && "format" in schema && schema.format) return genericExampleValues[schema.format] ?? fallback;
	return fallback;
};
/**
* WeakMap cache for memoizing resolved example results.
* Uses the resolved schema object as the key for efficient lookups.
*/
var resultCache = /* @__PURE__ */ new WeakMap();
/** Cache required property names per parent schema for O(1) membership checks */
var requiredNamesCache = /* @__PURE__ */ new WeakMap();
/** Normalize schema identity for cache and cycle tracking */
var getSchemaCacheTarget = (schema) => unpackProxyObject(schema, { depth: 1 });
/**
* Retrieves the set of required property names from a schema.
* Caches the result in a WeakMap for efficient lookups.
*/
var getRequiredNames = (parentSchema) => {
	if (!parentSchema) return;
	const cached = requiredNamesCache.get(parentSchema);
	if (cached) return cached;
	if ("required" in parentSchema) {
		const required = parentSchema.required;
		if (Array.isArray(required) && required.length > 0) {
			const set = new Set(required);
			requiredNamesCache.set(parentSchema, set);
			return set;
		}
	}
};
/**
* Cache the result for a schema if it is an object type.
* Primitive values are not cached to avoid unnecessary WeakMap operations.
* Stores a map of cacheKey strings which is made up of the options object.
*/
var cache = (schema, result, cacheKey) => {
	if (typeof result !== "object" || result === null) return result;
	const rawSchema = getSchemaCacheTarget(schema);
	const cacheMap = resultCache.get(rawSchema) ?? /* @__PURE__ */ new Map();
	if (cacheMap) cacheMap.set(cacheKey, result);
	resultCache.set(rawSchema, cacheMap);
	return result;
};
/**
* Check if a schema uses composition keywords (allOf, oneOf, anyOf).
* These require special handling for merging or selecting schemas.
*/
var isComposed = (schema) => !!(schema.allOf || schema.oneOf || schema.anyOf);
/**
* Determine if a property should be omitted based on the options.
* Properties are omitted if they are not required and the option is enabled.
*/
var shouldOmitProperty = (schema, parentSchema, propertyName, options) => {
	if (schema.deprecated || options?.mode === "write" && schema.readOnly || options?.mode === "read" && schema.writeOnly) return true;
	if (options?.omitEmptyAndOptionalProperties !== true) return false;
	if ("type" in schema && (schema.type === "object" || schema.type === "array") || isComposed(schema)) return false;
	if ("examples" in schema && Array.isArray(schema.examples) && schema.examples.length > 0 || "example" in schema && schema.example !== void 0 || "default" in schema && schema.default !== void 0 || "const" in schema && schema.const !== void 0 || "enum" in schema && Array.isArray(schema.enum) && schema.enum.length > 0) return false;
	const name = propertyName ?? schema.title ?? "";
	const requiredNames = getRequiredNames(parentSchema);
	return !(requiredNames ? requiredNames.has(name) : false);
};
/**
* Merge two example values with predictable semantics.
* Arrays are concatenated, objects are merged, otherwise the new value wins.
*/
var mergeExamples = (baseValue, newValue) => {
	if (Array.isArray(baseValue) && Array.isArray(newValue)) return [...baseValue, ...newValue];
	if (baseValue && typeof baseValue === "object" && newValue && typeof newValue === "object") return {
		...baseValue,
		...newValue
	};
	return newValue;
};
/**
* Build an example for an object schema, including properties, patternProperties,
* additionalProperties, and composition (allOf/oneOf/anyOf) merging.
*/
var handleObjectSchema = (schema, options, level, seen, cacheKey) => {
	const response = {};
	if ("properties" in schema && schema.properties) {
		const propertyNames = Object.keys(schema.properties);
		const limit = propertyNames.length;
		for (let i = 0; i < limit; i++) {
			const propertyName = propertyNames[i];
			const propertySchema = resolve.schema(schema.properties[propertyName]);
			if (!propertySchema) continue;
			const propertyXmlName = options?.xml && "xml" in propertySchema ? propertySchema.xml?.name : void 0;
			const value = getExampleFromSchema(propertySchema, options, {
				level: level + 1,
				parentSchema: schema,
				name: propertyName,
				seen
			});
			if (typeof value !== "undefined") response[propertyXmlName ?? propertyName] = value;
		}
	}
	if ("patternProperties" in schema && schema.patternProperties) for (const pattern of Object.keys(schema.patternProperties)) {
		const propertySchema = resolve.schema(schema.patternProperties[pattern]);
		if (!propertySchema) continue;
		response[pattern] = getExampleFromSchema(propertySchema, options, {
			level: level + 1,
			parentSchema: schema,
			name: pattern,
			seen
		});
	}
	if ("additionalProperties" in schema && schema.additionalProperties) {
		const additional = typeof schema.additionalProperties === "boolean" ? schema.additionalProperties : resolve.schema(schema.additionalProperties);
		const isAnyType = schema.additionalProperties === true || typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length === 0;
		const hasCustomName = typeof additional === "object" && "x-additionalPropertiesName" in additional && typeof additional["x-additionalPropertiesName"] === "string" && additional["x-additionalPropertiesName"].trim().length > 0;
		const propertyNamesEnum = hasCustomName ? void 0 : getPropertyNamesEnumValues(schema);
		const additionalName = hasCustomName ? additional["x-additionalPropertiesName"].trim() : DEFAULT_ADDITIONAL_PROPERTIES_NAME;
		const additionalValue = isAnyType ? "anything" : typeof additional === "object" ? getExampleFromSchema(additional, options, {
			level: level + 1,
			seen
		}) : "anything";
		if (propertyNamesEnum && propertyNamesEnum.length > 0) response[String(propertyNamesEnum[0])] = additionalValue;
		else response[additionalName] = additionalValue;
	}
	if (schema.oneOf?.[0]) Object.assign(response, getExampleFromSchema(resolve.schema(schema.oneOf[0]), options, {
		level: level + 1,
		seen
	}));
	else if (schema.anyOf?.[0]) Object.assign(response, getExampleFromSchema(resolve.schema(schema.anyOf[0]), options, {
		level: level + 1,
		seen
	}));
	else if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
		let merged = response;
		for (const item of schema.allOf) {
			const ex = getExampleFromSchema(resolve.schema(item), options, {
				level: level + 1,
				parentSchema: schema,
				seen
			});
			merged = mergeExamples(merged, ex);
		}
		if (merged && typeof merged === "object") Object.assign(response, merged);
	}
	if (options?.xml && "xml" in schema && schema.xml?.name && level === 0) {
		const wrapped = {};
		wrapped[schema.xml.name] = response;
		return cache(schema, wrapped, cacheKey);
	}
	return cache(schema, response, cacheKey);
};
/** Build an example for an array schema, including items, allOf, oneOf/anyOf, and XML wrapping */
var handleArraySchema = (schema, options, level, seen, cacheKey) => {
	const items = "items" in schema ? resolve.schema(schema.items) : void 0;
	const itemsXmlTagName = items && typeof items === "object" && "xml" in items ? items.xml?.name : void 0;
	const wrapItems = !!(options?.xml && "xml" in schema && schema.xml?.wrapped && itemsXmlTagName);
	if (schema.example !== void 0) return cache(schema, wrapItems ? { [itemsXmlTagName]: schema.example } : schema.example, cacheKey);
	if (items && typeof items === "object") {
		if (Array.isArray(items.allOf) && items.allOf.length > 0) {
			const allOf = items.allOf.filter(isDefined);
			const first = resolve.schema(allOf[0]);
			if (first && typeof first === "object" && "type" in first && first.type === "object") {
				const merged = getExampleFromSchema({
					type: "object",
					allOf
				}, options, {
					level: level + 1,
					parentSchema: schema,
					seen
				});
				return cache(schema, wrapItems ? [{ [itemsXmlTagName]: merged }] : [merged], cacheKey);
			}
			const examples = allOf.map((s) => getExampleFromSchema(resolve.schema(s), options, {
				level: level + 1,
				parentSchema: schema,
				seen
			})).filter(isDefined);
			return cache(schema, wrapItems ? examples.map((e) => ({ [itemsXmlTagName]: e })) : examples, cacheKey);
		}
		const union = items.anyOf || items.oneOf;
		if (union && union.length > 0) {
			const first = union[0];
			const ex = getExampleFromSchema(resolve.schema(first), options, {
				level: level + 1,
				parentSchema: schema,
				seen
			});
			return cache(schema, wrapItems ? [{ [itemsXmlTagName]: ex }] : [ex], cacheKey);
		}
	}
	const isObject = items && typeof items === "object" && ("type" in items && items.type === "object" || "properties" in items);
	const isArray = items && typeof items === "object" && ("type" in items && items.type === "array" || "items" in items);
	if (items && typeof items === "object" && ("type" in items && items.type || isObject || isArray)) {
		const ex = getExampleFromSchema(items, options, {
			level: level + 1,
			seen
		});
		return cache(schema, wrapItems ? [{ [itemsXmlTagName]: ex }] : [ex], cacheKey);
	}
	return cache(schema, [], cacheKey);
};
/** Return primitive example value for single-type schemas, or undefined if not primitive */
var getPrimitiveValue = (schema, makeUpRandomData, emptyString) => {
	if ("type" in schema && schema.type && !Array.isArray(schema.type)) switch (schema.type) {
		case "string": return guessFromFormat(schema, makeUpRandomData, emptyString ?? "");
		case "boolean": return true;
		case "integer": return "minimum" in schema && typeof schema.minimum === "number" ? schema.minimum : 1;
		case "number": return "minimum" in schema && typeof schema.minimum === "number" ? schema.minimum : 1;
		case "array": return [];
		default: return;
	}
};
/** Return primitive example value for union-type schemas (type: string[]) */
var getUnionPrimitiveValue = (schema, makeUpRandomData, emptyString) => {
	if ("type" in schema && Array.isArray(schema.type)) {
		if (schema.type.includes("null")) return null;
		const first = schema.type[0];
		if (first) switch (first) {
			case "string": return guessFromFormat(schema, makeUpRandomData, emptyString ?? "");
			case "boolean": return true;
			case "integer": return "minimum" in schema && typeof schema.minimum === "number" ? schema.minimum : 1;
			case "number": return "minimum" in schema && typeof schema.minimum === "number" ? schema.minimum : 1;
			case "null": return null;
			default: return;
		}
	}
};
/** Create stable cache key from the options object */
var createOptionsCacheKey = (options) => JSON.stringify({
	emptyString: options?.emptyString,
	xml: options?.xml,
	mode: options?.mode,
	variables: options?.variables,
	omitEmptyAndOptionalProperties: options?.omitEmptyAndOptionalProperties
});
/**
* Generate an example value from a given OpenAPI SchemaObject.
*
* This function recursively processes OpenAPI schemas to create realistic example data.
* It handles all OpenAPI schema types including primitives, objects, arrays, and
* composition schemas (allOf, oneOf, anyOf).
* Uses a tonne of caching for maximum performance.
*
* @param schema - The OpenAPI SchemaObject to generate an example from.
* @param options - Options to customize example generation.
* @param level - The current recursion depth.
* @param parentSchema - The parent schema, if any.
* @param name - The name of the property being processed.
* @returns An example value for the given schema.
*/
var getExampleFromSchema = (schema, options, { level = 0, parentSchema, name, seen = /* @__PURE__ */ new WeakSet() } = {}) => {
	const _schema = resolve.schema(schema);
	if (!isDefined(_schema)) return;
	const targetValue = getSchemaCacheTarget(_schema);
	if (seen.has(targetValue)) return;
	seen.add(targetValue);
	/** Make the cache key unique per options */
	const cacheKey = createOptionsCacheKey(options);
	const cached = resultCache.get(targetValue)?.get(cacheKey);
	if (typeof cached !== "undefined") {
		seen.delete(targetValue);
		return cached;
	}
	if (level > MAX_LEVELS_DEEP) {
		seen.delete(targetValue);
		return "[Max Depth Exceeded]";
	}
	const makeUpRandomData = !!options?.emptyString;
	if (shouldOmitProperty(_schema, parentSchema, name, options)) {
		seen.delete(targetValue);
		return;
	}
	if ("x-variable" in _schema && _schema["x-variable"]) {
		const value = options?.variables?.[_schema["x-variable"]];
		if (value !== void 0) {
			if ("type" in _schema && (_schema.type === "number" || _schema.type === "integer")) {
				seen.delete(targetValue);
				return cache(_schema, Number(value), cacheKey);
			}
			seen.delete(targetValue);
			return cache(_schema, value, cacheKey);
		}
	}
	if (Array.isArray(_schema.examples) && _schema.examples.length > 0) {
		seen.delete(targetValue);
		return cache(_schema, _schema.examples[0], cacheKey);
	}
	if (_schema.example !== void 0) {
		seen.delete(targetValue);
		return cache(_schema, _schema.example, cacheKey);
	}
	if (_schema.default !== void 0) {
		seen.delete(targetValue);
		return cache(_schema, _schema.default, cacheKey);
	}
	if (_schema.const !== void 0) {
		seen.delete(targetValue);
		return cache(_schema, _schema.const, cacheKey);
	}
	if (Array.isArray(_schema.enum) && _schema.enum.length > 0) {
		seen.delete(targetValue);
		return cache(_schema, _schema.enum[0], cacheKey);
	}
	if ("properties" in _schema || "type" in _schema && _schema.type === "object") {
		const result = handleObjectSchema(_schema, options, level, seen, cacheKey);
		seen.delete(targetValue);
		return result;
	}
	if ("type" in _schema && _schema.type === "array" || "items" in _schema) {
		const result = handleArraySchema(_schema, options, level, seen, cacheKey);
		seen.delete(targetValue);
		return result;
	}
	const primitive = getPrimitiveValue(_schema, makeUpRandomData, options?.emptyString);
	if (primitive !== void 0) {
		seen.delete(targetValue);
		return cache(_schema, primitive, cacheKey);
	}
	const discriminate = _schema.oneOf || _schema.anyOf;
	if (Array.isArray(discriminate) && discriminate.length > 0) {
		for (const item of discriminate) {
			const resolved = resolve.schema(item);
			if (resolved && (!("type" in resolved) || resolved.type !== "null")) {
				seen.delete(targetValue);
				return cache(_schema, getExampleFromSchema(resolved, options, {
					level: level + 1,
					seen
				}), cacheKey);
			}
		}
		seen.delete(targetValue);
		return cache(_schema, null, cacheKey);
	}
	if (Array.isArray(_schema.allOf) && _schema.allOf.length > 0) {
		let merged = void 0;
		const items = _schema.allOf;
		for (const item of items) {
			const ex = getExampleFromSchema(item, options, {
				level: level + 1,
				parentSchema: _schema,
				seen
			});
			if (merged === void 0) merged = ex;
			else if (merged && typeof merged === "object" && ex && typeof ex === "object") merged = mergeExamples(merged, ex);
			else if (ex !== void 0) merged = ex;
		}
		seen.delete(targetValue);
		return cache(_schema, merged ?? null, cacheKey);
	}
	const unionPrimitive = getUnionPrimitiveValue(_schema, makeUpRandomData, options?.emptyString);
	if (unionPrimitive !== void 0) {
		seen.delete(targetValue);
		return cache(_schema, unionPrimitive, cacheKey);
	}
	seen.delete(targetValue);
	return cache(_schema, null, cacheKey);
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/filter-global-cookies.ts
/**
* Filter a global cookie to determine if it should be included with a request to the given URL.
* - Returns false if the cookie is disabled, in the disabledGlobalCookies map, or missing a name.
* - Returns false if the domain does not match.
* - Returns false if the path is specified and does not match the URL pathname.
* - Returns true otherwise.
*/
var filterGlobalCookie = ({ cookie, url, disabledGlobalCookies }) => {
	if (cookie.isDisabled || disabledGlobalCookies[cookie.name.toLowerCase()] === true || !cookie.name) return false;
	const urlObject = new URL(url, "https://example.com");
	if (cookie.domain && !matchesDomain(url, cookie.domain)) return false;
	if (cookie.path && !urlObject.pathname.startsWith(cookie.path)) return false;
	return true;
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/de-serialize-parameter.ts
/** Helper that de-serializes the example value based on the parameter type */
var deSerializeParameter = (example, param) => {
	if ("content" in param) return deSerializeContentExample(example, Object.keys(param.content ?? {})[0] ?? "");
	if ("schema" in param) return deSerializeSchemaExample(example, param.schema);
	return example;
};
/** De-serialize the example value based on the content type */
var deSerializeContentExample = (example, contentType) => {
	if (typeof example === "string" && contentType.includes("json")) try {
		return JSON.parse(example);
	} catch {}
	return example;
};
/** Create a set of all the types we wish to parse as JSON */
var parseableTypesSet = new Set([
	"array",
	"object",
	"boolean",
	"number",
	"integer",
	"null"
]);
/** De-serialize the example value based on the schema type */
var deSerializeSchemaExample = (example, schema) => {
	const resolvedSchema = getResolvedRef(schema);
	if (typeof example === "string" && resolvedSchema && "type" in resolvedSchema) {
		const type = Array.isArray(resolvedSchema.type) ? resolvedSchema.type[0] : resolvedSchema.type;
		if (type && parseableTypesSet.has(type)) try {
			return JSON.parse(example);
		} catch {
			if (type === "array") return example.split(/,\s?/).filter((v) => v !== "");
		}
	}
	return example;
};
//#endregion
//#region src/v2/blocks/request-block/helpers/is-param-disabled.ts
/**
* Determines if a parameter is disabled
*
* First we explicitly check if its been disabled via the `x-disabled` extension.
* Then we check if its an optional parameter and not a path parameter.
*
* @param param - The parameter to check.
* @param example - The example to check.
* @returns true if the parameter is disabled, false otherwise.
*/
var isParamDisabled = (param, example) => {
	const xDisabled = example?.["x-disabled"];
	if (typeof xDisabled === "boolean") return xDisabled;
	return !param.required && param.in !== "path";
};
//#endregion
//#region src/v2/blocks/operation-block/helpers/serialize-parameter.ts
/**
* Shared parameter serialization utilities for OpenAPI style values.
* Used by both build-request-parameters and process-parameters.
*
* @see https://spec.openapis.org/oas/v3.1.1.html#style-values
*/
/**
* Serializes a value based on the content type for content-based query parameters.
* Content-based query parameters do not use style serialization and instead follow
* their content type specification (e.g., application/json should be JSON.stringified).
*
* @param value - The value to serialize
* @param contentType - The content type to use for serialization
* @returns The serialized value as a string
*/
var serializeContentValue = (value, contentType) => {
	if (typeof value === "string") return value;
	if (contentType.includes("json") || typeof value === "object" && value !== null && !Array.isArray(value)) return JSON.stringify(value);
	return String(value);
};
/**
* Serializes a value according to OpenAPI simple style.
* Used for path and header parameters.
*
* Simple style with explode: false
* - Primitive: blue
* - Array: blue,black,brown
* - Object: R,100,G,200,B,150
*
* Simple style with explode: true
* - Primitive: blue
* - Array: blue,black,brown
* - Object: R=100,G=200,B=150
*/
var serializeSimpleStyle = (value, explode) => {
	if (Array.isArray(value)) return value.join(",");
	if (typeof value === "object" && value !== null) {
		const entries = Object.entries(value);
		if (explode) return entries.map(([k, v]) => `${k}=${v}`).join(",");
		return entries.map(([k, v]) => `${k},${v}`).join(",");
	}
	return value;
};
/**
* Serializes a value according to OpenAPI form style.
* Used for query and cookie parameters.
*
* Form style with explode: true (default for query)
* - Primitive: color=blue
* - Array: color=blue&color=black&color=brown (multiple entries)
* - Object: R=100&G=200&B=150 (multiple entries)
*
* Form style with explode: false
* - Primitive: color=blue
* - Array: color=blue,black,brown
* - Object: color=R,100,G,200,B,150
*/
var serializeFormStyle = (value, explode) => {
	if (Array.isArray(value) && explode) return value.map((v) => ({
		key: "",
		value: v
	}));
	if (Array.isArray(value)) return value.join(",");
	if (typeof value === "object" && value !== null && explode) return Object.entries(value).map(([k, v]) => ({
		key: k,
		value: v
	}));
	if (typeof value === "object" && value !== null) return Object.entries(value).map(([k, v]) => `${k},${v}`).join(",");
	return value;
};
/**
* Serializes a value according to OpenAPI form style for cookies.
* This is similar to serializeFormStyle but handles nested objects recursively
* and treats null values specially for cookie serialization.
*
* Form style with explode: true (default for cookies)
* - Primitive: color=blue
* - Array: color=blue&color=black&color=brown (multiple entries)
* - Object: R=100&G=200&B=150 (multiple entries)
*
* Form style with explode: false
* - Primitive: color=blue
* - Array: color=blue,black,brown (null becomes "null")
* - Object: color=R,100,G,200,B,150 (recursively flattened)
*/
var serializeFormStyleForCookies = (value, explode) => {
	if (Array.isArray(value) && explode) return value.map((v) => ({
		key: "",
		value: v
	}));
	if (Array.isArray(value)) return value.map((v) => v === null ? "null" : String(v)).join(",");
	if (typeof value === "object" && value !== null && explode) return Object.entries(value).map(([k, v]) => ({
		key: k,
		value: v
	}));
	if (typeof value === "object" && value !== null) {
		const flattenObject = (obj) => {
			const result = [];
			for (const [key, val] of Object.entries(obj)) if (typeof val === "object" && val !== null && !Array.isArray(val)) result.push(key, ...flattenObject(val));
			else result.push(key, val === null ? "null" : String(val));
			return result;
		};
		return flattenObject(value).join(",");
	}
	return value;
};
/**
* Serializes a value according to OpenAPI spaceDelimited style.
* Only valid for query parameters with array or object values.
*
* SpaceDelimited array: blue black brown
* SpaceDelimited object: R 100 G 200 B 150
*/
var serializeSpaceDelimitedStyle = (value) => {
	if (Array.isArray(value)) return value.join(" ");
	if (typeof value === "object" && value !== null) return Object.entries(value).map(([k, v]) => `${k} ${v}`).join(" ");
	return String(value);
};
/**
* Serializes a value according to OpenAPI pipeDelimited style.
* Only valid for query parameters with array or object values.
*
* PipeDelimited array: blue|black|brown
* PipeDelimited object: R|100|G|200|B|150
*/
var serializePipeDelimitedStyle = (value) => {
	if (Array.isArray(value)) return value.join("|");
	if (typeof value === "object" && value !== null) return Object.entries(value).flat().join("|");
	return String(value);
};
/**
* Serializes a value according to OpenAPI deepObject style.
* Only valid for query parameters with explode: true.
*
* DeepObject: color[R]=100&color[G]=200&color[B]=150
* Nested: user[name][first]=Alex&user[name][last]=Smith&user[role]=admin
*/
var serializeDeepObjectStyle = (paramName, value) => {
	const result = [];
	/**
	* Recursively flattens nested objects into deepObject notation.
	*/
	const flatten = (obj, prefix) => {
		for (const [key, val] of Object.entries(obj)) {
			const fullKey = `${prefix}[${key}]`;
			if (typeof val === "object" && val !== null && !Array.isArray(val)) flatten(val, fullKey);
			else result.push({
				key: fullKey,
				value: String(val)
			});
		}
	};
	if (typeof value === "object" && value !== null && !Array.isArray(value)) flatten(value, paramName);
	return result;
};
//#endregion
//#region src/v2/blocks/operation-code-sample/components/ExamplePicker.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1$1 = { class: "min-w-0 flex-1 truncate" };
//#endregion
//#region src/v2/blocks/operation-code-sample/components/ExamplePicker.vue
var ExamplePicker_default = /* @__PURE__ */ defineComponent({
	inheritAttrs: false,
	__name: "ExamplePicker",
	props: /* @__PURE__ */ mergeModels({ examples: { default: () => ({}) } }, {
		"modelValue": { required: true },
		"modelModifiers": {}
	}),
	emits: ["update:modelValue"],
	setup(__props) {
		const selectedExampleKey = useModel(__props, "modelValue");
		const exampleOptions = computed(() => Object.entries(__props.examples).map(([key, example]) => ({
			id: key,
			label: example?.summary ?? key
		})));
		const selectedExample = computed({
			get: () => exampleOptions.value.find(({ id }) => id === selectedExampleKey.value),
			set: (v) => selectedExampleKey.value = v?.id ?? ""
		});
		return (_ctx, _cache) => {
			return openBlock(), createBlock(unref(ScalarListbox), {
				modelValue: selectedExample.value,
				"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectedExample.value = $event),
				class: "w-fit min-w-32",
				options: exampleOptions.value,
				placement: "bottom-start",
				teleport: ""
			}, {
				default: withCtx(() => [createVNode(unref(ScalarButton), mergeProps({
					class: "text-c-2 hover:text-c-1 flex h-full w-fit min-w-0 gap-1.5 px-1.5 py-0.75 text-base font-normal",
					"data-testid": "example-picker",
					variant: "ghost"
				}, _ctx.$attrs), {
					default: withCtx(() => [createElementVNode("div", _hoisted_1$1, toDisplayString(selectedExample.value?.label ?? "Select an example"), 1), createVNode(unref(ScalarIconCaretDown), {
						class: "ui-open:rotate-180 mt-0.25 size-3 transition-transform duration-100",
						weight: "bold"
					})]),
					_: 1
				}, 16)]),
				_: 1
			}, 8, ["modelValue", "options"]);
		};
	}
});
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-body.ts
/**
* Converts an object to an array of form parameters
* @param obj - The object to convert
* @returns Array of form parameters with name and value properties
*/
var objectToFormParams = (obj) => {
	const params = [];
	/** Ensure we do not include disabled items */
	const entries = Array.isArray(obj) ? obj.filter((item) => !item.isDisabled).map((item) => [item.name, item.value]) : Object.entries(obj);
	for (const [key, value] of entries) {
		if (value === void 0 || value === null) continue;
		if (value instanceof File) {
			const file = unpackProxyObject(value);
			params.push({
				name: key,
				value: `@${file.name}`
			});
		} else if (Array.isArray(value)) for (const item of value) if (item instanceof File) {
			const file = unpackProxyObject(item);
			params.push({
				name: key,
				value: `@${file.name}`
			});
		} else params.push({
			name: key,
			value: String(item)
		});
		else if (typeof value === "object") {
			const nestedParams = objectToFormParams(value);
			for (const param of nestedParams) params.push({
				name: `${key}.${param.name}`,
				value: param.value
			});
		} else params.push({
			name: key,
			value: String(value)
		});
	}
	return params;
};
/**
* Processes the request body and returns the processed data
* Returns undefined if no example is found
*/
var processBody = ({ requestBody, contentType, example }) => {
	const _contentType = contentType || Object.keys(requestBody.content)[0] || "";
	const formatBinaryFile = (file) => {
		return `@${unpackProxyObject(file).name || "filename"}`;
	};
	const isFormData = _contentType === "multipart/form-data" || _contentType === "application/x-www-form-urlencoded";
	const isXml = _contentType === "application/xml";
	const _example = getExample(requestBody, example, contentType)?.value;
	if (typeof _example !== "undefined") {
		const exampleValue = _example !== null && typeof _example === "object" ? unpackProxyObject(_example) : _example;
		if (isFormData && typeof exampleValue === "object" && exampleValue !== null) return {
			mimeType: _contentType,
			params: objectToFormParams(exampleValue)
		};
		if (isXml && typeof exampleValue === "object" && exampleValue !== null) return {
			mimeType: _contentType,
			text: json2xml(exampleValue)
		};
		if (exampleValue instanceof File) return {
			mimeType: _contentType,
			text: formatBinaryFile(exampleValue)
		};
		return {
			mimeType: _contentType,
			text: typeof exampleValue === "string" ? exampleValue : JSON.stringify(exampleValue)
		};
	}
	const contentSchema = getResolvedRef(requestBody.content[_contentType]?.schema);
	if (typeof contentSchema !== "undefined") {
		const extractedExample = getExampleFromSchema(contentSchema, {
			mode: "write",
			xml: isXml
		});
		if (extractedExample !== void 0) {
			if (isFormData && typeof extractedExample === "object" && extractedExample !== null) return {
				mimeType: _contentType,
				params: objectToFormParams(extractedExample)
			};
			if (isXml && typeof extractedExample === "object" && extractedExample !== null) return {
				mimeType: _contentType,
				text: json2xml(extractedExample)
			};
			return {
				mimeType: _contentType,
				text: typeof extractedExample === "string" ? extractedExample : JSON.stringify(extractedExample)
			};
		}
	}
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-parameters.ts
/** Ensures we don't have any references in the parameters */
var deReferenceParams = (params) => (params ?? []).map((param) => getResolvedRef(param));
/**
* Get the style and explode values for a parameter according to OpenAPI 3.1.1 specification.
* Handles defaults and validation for parameter location restrictions.
*/
var getParameterStyleAndExplode = (param) => {
	if (param.in === "header") return {
		style: "simple",
		explode: "explode" in param && param.explode !== void 0 ? param.explode : false
	};
	if (param.in === "cookie") return {
		style: "form",
		explode: "explode" in param && param.explode !== void 0 ? param.explode : true
	};
	const defaultStyle = {
		path: "simple",
		query: "form",
		header: "simple",
		cookie: "form"
	}[param.in];
	const style = "style" in param && param.style ? param.style : defaultStyle;
	return {
		style,
		explode: "explode" in param && param.explode !== void 0 ? param.explode : style === "form"
	};
};
/**
* Extract the value for a parameter from example data or schema.
* Prioritizes example data over schema examples.
* Returns null if the parameter is disabled so we can skip it.
*/
var getParameterValue = (param, example, contentType) => {
	const exampleValue = getExample(param, example, contentType);
	if (isParamDisabled(param, exampleValue)) return;
	if (exampleValue?.value !== void 0) return deSerializeParameter(exampleValue.value, param);
	if (!("schema" in param) || !param.schema) return;
	const options = param.in === "path" ? { emptyString: `{${param.name}}` } : {};
	return getExampleFromSchema(getResolvedRef(param.schema), options);
};
/**
* Process OpenAPI parameters and return the updated properties.
* Handles path, query, and header parameters with various styles and explode options.
*
* @see https://spec.openapis.org/oas/latest.html#style-values
*/
var processParameters = ({ harRequest, parameters, example }) => {
	const newHeaders = [...harRequest.headers];
	const newQueryString = [...harRequest.queryString];
	let newUrl = harRequest.url;
	const deReferencedParams = deReferenceParams(parameters);
	for (const param of deReferencedParams) {
		if (!param.in || !param.name) continue;
		const paramValue = getParameterValue(param, example, void 0);
		if (paramValue === void 0) continue;
		const { style, explode } = getParameterStyleAndExplode(param);
		switch (param.in) {
			case "path":
				newUrl = processPathParameters(newUrl, param, paramValue, style, explode);
				break;
			case "query":
				if ("content" in param && param.content) {
					const serializedValue = serializeContentValue(paramValue, Object.keys(param.content)[0] ?? "application/json");
					newQueryString.push({
						name: param.name,
						value: serializedValue
					});
					break;
				}
				switch (style) {
					case "form": {
						const serialized = serializeFormStyle(paramValue, explode);
						if (Array.isArray(serialized)) for (const entry of serialized) {
							const key = entry.key || param.name;
							newQueryString.push({
								name: key,
								value: String(entry.value)
							});
						}
						else newQueryString.push({
							name: param.name,
							value: String(serialized)
						});
						break;
					}
					case "spaceDelimited": {
						const serialized = serializeSpaceDelimitedStyle(paramValue);
						newQueryString.push({
							name: param.name,
							value: serialized
						});
						break;
					}
					case "pipeDelimited": {
						const serialized = serializePipeDelimitedStyle(paramValue);
						newQueryString.push({
							name: param.name,
							value: serialized
						});
						break;
					}
					case "deepObject":
						if (explode) {
							const entries = serializeDeepObjectStyle(param.name, paramValue);
							for (const entry of entries) newQueryString.push({
								name: entry.key,
								value: entry.value
							});
						}
						break;
					default: newQueryString.push({
						name: param.name,
						value: String(paramValue)
					});
				}
				break;
			case "header": {
				const serialized = serializeSimpleStyle(paramValue, explode);
				newHeaders.push({
					name: param.name,
					value: String(serialized)
				});
				break;
			}
			case "cookie": {
				const serialized = serializeFormStyleForCookies(paramValue, explode);
				if (Array.isArray(serialized)) for (const entry of serialized) {
					const key = entry.key || param.name;
					const value = entry.value === null ? "null" : String(entry.value);
					harRequest.cookies.push({
						name: key,
						value
					});
				}
				else {
					const value = serialized === null ? "null" : String(serialized);
					harRequest.cookies.push({
						name: param.name,
						value
					});
				}
				break;
			}
		}
	}
	return {
		url: newUrl,
		headers: newHeaders,
		queryString: newQueryString,
		cookies: harRequest.cookies
	};
};
/**
* Process path parameters according to OpenAPI specification.
* Handles matrix, label, and simple styles with explode options.
*
* @param url - The URL to process
* @param param - The parameter object
* @param paramValue - The value of the parameter
* @param style - The style of the parameter (matrix, label, simple)
* @param explode - Whether to explode the parameter
* @returns The updated URL with processed path parameters
*/
var processPathParameters = (url, param, paramValue, style, explode) => {
	switch (style) {
		case "matrix":
			if (explode) {
				if (Array.isArray(paramValue)) {
					const values = paramValue.map((v) => `${param.name}=${v}`).join(";");
					return url.replace(`{;${param.name}}`, `;${values}`);
				}
				if (typeof paramValue === "object" && paramValue !== null) {
					const values = Object.entries(paramValue).map(([k, v]) => `${k}=${v}`).join(";");
					return url.replace(`{;${param.name}}`, `;${values}`);
				}
				return url.replace(`{;${param.name}}`, `;${param.name}=${paramValue}`);
			}
			if (Array.isArray(paramValue)) return url.replace(`{;${param.name}}`, `;${param.name}=${paramValue.join(",")}`);
			if (typeof paramValue === "object" && paramValue !== null) {
				const values = Object.entries(paramValue).map(([k, v]) => `${k},${v}`).join(",");
				return url.replace(`{;${param.name}}`, `;${param.name}=${values}`);
			}
			return url.replace(`{;${param.name}}`, `;${param.name}=${paramValue}`);
		case "label":
			if (explode) {
				if (Array.isArray(paramValue)) return url.replace(`{.${param.name}}`, `.${paramValue.join(".")}`);
				if (typeof paramValue === "object" && paramValue !== null) {
					const values = Object.entries(paramValue).map(([k, v]) => `${k}=${v}`).join(".");
					return url.replace(`{.${param.name}}`, `.${values}`);
				}
				return url.replace(`{.${param.name}}`, `.${paramValue}`);
			}
			if (Array.isArray(paramValue)) return url.replace(`{.${param.name}}`, `.${paramValue.join(",")}`);
			if (typeof paramValue === "object" && paramValue !== null) {
				const values = Object.entries(paramValue).map(([k, v]) => `${k},${v}`).join(",");
				return url.replace(`{.${param.name}}`, `.${values}`);
			}
			return url.replace(`{.${param.name}}`, `.${paramValue}`);
		case "simple": {
			const serialized = serializeSimpleStyle(paramValue, explode);
			return url.replace(`{${param.name}}`, String(serialized));
		}
		default: return url.replace(`{${param.name}}`, String(paramValue));
	}
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-security-schemes.ts
/**
* Process security schemes into whichever parameters they are applicable to
*
* TODO: we probably want to be able to disable YOUR_SECRET_TOKEN placeholder text + or allow it to be customzied
*/
var processSecuritySchemes = (securitySchemes) => {
	const result = {
		headers: [],
		queryString: [],
		cookies: []
	};
	for (const scheme of securitySchemes) {
		if (scheme.type === "apiKey") {
			const value = scheme["x-scalar-secret-token"] || "YOUR_SECRET_TOKEN";
			if (!scheme.name) continue;
			const param = {
				name: scheme.name,
				value
			};
			switch (scheme.in) {
				case "header":
					result.headers.push(param);
					break;
				case "query":
					result.queryString.push(param);
					break;
				case "cookie":
					result.cookies.push(param);
					break;
			}
			continue;
		}
		if (scheme.type === "http") {
			if (scheme.scheme === "basic") {
				const value = `${scheme["x-scalar-secret-username"] || ""}:${scheme["x-scalar-secret-password"] || ""}`;
				const auth = value === ":" ? "username:password" : encode(value);
				result.headers.push({
					name: "Authorization",
					value: `Basic ${auth}`
				});
			} else if (scheme.scheme === "bearer") {
				const token = scheme["x-scalar-secret-token"] || "YOUR_SECRET_TOKEN";
				result.headers.push({
					name: "Authorization",
					value: `Bearer ${token}`
				});
			}
			continue;
		}
		if (scheme.type === "oauth2" && scheme.flows) {
			const token = Object.values(scheme.flows).find((f) => f["x-scalar-secret-token"])?.["x-scalar-secret-token"] || "YOUR_SECRET_TOKEN";
			result.headers.push({
				name: "Authorization",
				value: `Bearer ${token}`
			});
		}
	}
	return result;
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/operation-to-har/process-server-url.ts
/**
* Processes a server URL by replacing variables with their default values and merging with the path
*/
var processServerUrl = (server, path) => {
	if (!server?.url) return path;
	const serverUrl = server.url;
	if (server.variables) return mergeUrls(replaceVariables(serverUrl, Object.entries(server.variables).reduce((defaults, [variableName, variableConfig]) => {
		if (variableConfig.default !== void 0) defaults[variableName] = variableConfig.default;
		return defaults;
	}, {})), path);
	return mergeUrls(serverUrl, path);
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/operation-to-har/operation-to-har.ts
/**
* Converts an OpenAPI Operation to a HarRequest format for generating HTTP request snippets.
*
* This function transforms OpenAPI 3.1 operation objects into HAR (HTTP Archive) format requests,
* which can be used to generate code snippets for various programming languages and HTTP clients.
*
* The conversion handles:
* - Server URL processing and path parameter substitution
* - Query parameter formatting based on OpenAPI parameter styles
* - Request body processing with content type handling
* - Security scheme integration (API keys, etc.)
*
* The resulting HarRequest object follows the HAR specification and includes:
* - HTTP method and URL
* - Headers and query parameters
* - Request body (if present)
* - Cookie information
* - Size calculations for headers and body
*
* @see https://w3c.github.io/web-performance/specs/HAR/Overview.html
* @see https://spec.openapis.org/oas/v3.1.0#operation-object
*/
var operationToHar = ({ includeDefaultHeaders = false, operation, contentType, method, path, server = null, example, securitySchemes, globalCookies }) => {
	const defaultHeaders = includeDefaultHeaders ? getDefaultHeaders({
		method,
		operation,
		exampleKey: example ?? "default",
		hideDisabledHeaders: true
	}).filter((header) => !header.isOverridden) : [];
	const disabledGlobalCookies = operation["x-scalar-disable-parameters"]?.["global-cookies"]?.[example ?? "default"] ?? {};
	const harRequest = {
		method,
		url: processServerUrl(server, path),
		headers: defaultHeaders.map((header) => ({
			name: header.name,
			value: header.defaultValue
		})),
		queryString: [],
		postData: void 0,
		httpVersion: "HTTP/1.1",
		cookies: [],
		headersSize: -1,
		bodySize: -1
	};
	if (operation.parameters) {
		const { url, headers, queryString, cookies } = processParameters({
			harRequest,
			parameters: operation.parameters,
			example
		});
		const filteredGlobalCookies = globalCookies?.filter((cookie) => filterGlobalCookie({
			cookie,
			url,
			disabledGlobalCookies
		}))?.map((cookie) => ({
			name: cookie.name,
			value: cookie.value
		})) ?? [];
		harRequest.url = url;
		harRequest.headers = headers;
		harRequest.queryString = queryString;
		harRequest.cookies = [...filteredGlobalCookies, ...cookies];
	}
	const body = getResolvedRef(operation.requestBody);
	if (body?.content) {
		const postData = processBody({
			requestBody: body,
			contentType,
			example
		});
		if (postData) {
			harRequest.postData = postData;
			harRequest.bodySize = postData.text?.length ?? -1;
			if (postData.mimeType) {
				const existingContentTypeHeader = harRequest.headers.find((header) => header.name.toLowerCase() === "content-type");
				if (existingContentTypeHeader && !existingContentTypeHeader.value) existingContentTypeHeader.value = postData.mimeType;
				else if (!existingContentTypeHeader) harRequest.headers.push({
					name: "Content-Type",
					value: postData.mimeType
				});
			}
		}
	}
	if (securitySchemes) {
		const { headers, queryString, cookies } = processSecuritySchemes(securitySchemes);
		harRequest.headers.push(...headers);
		harRequest.queryString.push(...queryString);
		harRequest.cookies.push(...cookies);
	}
	let headersSize = 0;
	for (const h of harRequest.headers) headersSize += (h.name?.length ?? 0) + 2 + (h.value?.length ?? 0) + 2;
	harRequest.headersSize = headersSize;
	return harRequest;
};
//#endregion
//#region src/v2/blocks/operation-code-sample/components/HttpMethod.vue
var HttpMethod_default = /* @__PURE__ */ defineComponent({
	__name: "HttpMethod",
	props: {
		as: {},
		property: {},
		short: { type: Boolean },
		method: {}
	},
	setup(__props) {
		const props = __props;
		/** Grabs the method info object which contains abbreviation, color, and background color etc */
		const httpMethodInfo = computed(() => getHttpMethodInfo(String(props.method || "")));
		/** Full method name */
		const normalized = computed(() => normalizeHttpMethod(props.method));
		return (_ctx, _cache) => {
			return openBlock(), createBlock(resolveDynamicComponent(__props.as ?? "span"), {
				class: "uppercase",
				style: normalizeStyle({ [__props.property || "color"]: httpMethodInfo.value.colorVar })
			}, {
				default: withCtx(() => [renderSlot(_ctx.$slots, "default"), createTextVNode(" " + toDisplayString(__props.short ? httpMethodInfo.value.short : normalized.value), 1)]),
				_: 3
			}, 8, ["style"]);
		};
	}
});
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/find-client.ts
var DEFAULT_CLIENT = "shell/curl";
/** Type guard to check if a string is a valid client id */
var isClient = (id) => AVAILABLE_CLIENTS.includes(id);
/**
* Finds and returns the appropriate client option from a list of client option groups.
*
* This function is used to determine which client should be initially selected in the
* request example block. It prioritizes a specific client ID if provided, otherwise
* falls back to the first available option.
*
* @param options - Array of client option groups, each containing a label and array of client options
* @param id - Optional client identifier to search for (e.g., 'js/fetch', 'python/requests')

* @returns The selected client option. If a specific ID is provided and found, returns that client.
*          If the ID is not found or not provided, returns the first available client option.
*
* @example
* ```typescript
* const clientGroups = [
*   {
*     label: 'JavaScript',
*     options: [
*       { id: 'js/fetch', label: 'Fetch API', lang: 'js' },
*       { id: 'js/axios', label: 'Axios', lang: 'js' }
*     ]
*   }
* ]
*
* // Find specific client
* const client = findClient(clientGroups, 'js/fetch')
* // Returns: { id: 'js/fetch', label: 'Fetch API', lang: 'js' }
*
* // Find first available client
* const firstClient = findClient(clientGroups)
* // Returns: { id: 'js/fetch', label: 'Fetch API', lang: 'js' }
* ```
*/
var findClient = (clientGroups, clientId) => {
	const firstOption = clientGroups[0]?.options[0];
	if (clientId) for (const group of clientGroups) {
		const option = group.options.find((option) => option.id === clientId);
		if (option) return option;
	}
	if (!firstOption?.id.startsWith("custom")) for (const group of clientGroups) {
		const option = group.options.find((option) => option.id === DEFAULT_CLIENT);
		if (option) return option;
	}
	return firstOption;
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/generate-client-options.ts
/** Helper to generate an ID for custom code samples */
var generateCustomId = (example) => `custom/${example.lang}`;
/**
* Generate client options for the request example block by filtering by allowed clients
*
* @param allowedClients - The list of allowed clients to include in the options
* @returns A list of client option groups
*/
var generateClientOptions = (allowedClients = AVAILABLE_CLIENTS) => {
	/** Create set of allowlist for quicker lookups */
	const allowedClientsSet = new Set(allowedClients);
	return snippetz().clients().flatMap((group) => {
		const options = group.clients.flatMap((plugin) => {
			const id = `${group.key}/${plugin.client}`;
			if (!allowedClientsSet.has(id)) return [];
			return {
				id,
				lang: plugin.client === "curl" ? "curl" : group.key,
				title: `${capitalize(group.title)} ${plugin.title}`,
				label: plugin.title,
				targetKey: group.key,
				targetTitle: group.title,
				clientKey: plugin.client
			};
		});
		if (options.length === 0) return [];
		return {
			label: group.title,
			options
		};
	});
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/get-clients.ts
/**
* Merges custom code samples with the client options
*
* @param customCodeSamples - The custom code samples from the operation to merge with the client options
* @param clientOptions - The client options to merge with the custom code samples
* @returns A list of client option groups
*/
var getClients = (customCodeSamples, clientOptions) => {
	if (customCodeSamples.length) return [{
		label: "Code Examples",
		options: customCodeSamples.map((sample) => {
			const id = generateCustomId(sample);
			const label = sample.label || sample.lang || id;
			return {
				id,
				lang: sample.lang || "plaintext",
				title: label,
				label,
				clientKey: "custom"
			};
		})
	}, ...clientOptions];
	return clientOptions;
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/get-custom-code-samples.ts
/**
* Grabs any custom code samples from the operation
*
* @param operation - The operation to get the custom code samples from
* @returns An array of custom code samples which exist in the operation
*/
var getCustomCodeSamples = (operation) => {
	return [
		"x-custom-examples",
		"x-codeSamples",
		"x-code-samples"
	].flatMap((key) => operation[key] ?? []);
};
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/get-secrets.ts
/** Extract secrets from security schemes */
var getSecrets = (securitySchemes) => securitySchemes.flatMap((scheme) => {
	if (scheme.type === "apiKey") return scheme["x-scalar-secret-token"];
	if (scheme?.type === "http") return [
		scheme["x-scalar-secret-token"],
		scheme["x-scalar-secret-username"],
		scheme["x-scalar-secret-password"],
		encode(`${scheme["x-scalar-secret-username"]}:${scheme["x-scalar-secret-password"]}`)
	];
	if (scheme.type === "oauth2") return Object.values(scheme.flows).map((flow) => flow["x-scalar-secret-token"]);
	return [];
}).filter(Boolean);
//#endregion
//#region src/v2/blocks/operation-code-sample/helpers/generate-code-snippet.ts
/** Generate the code snippet for the selected example OR operation */
var generateCodeSnippet = ({ clientId, customCodeSamples, includeDefaultHeaders = false, operation, method, path, example, contentType, server, securitySchemes, globalCookies }) => {
	try {
		if (!clientId) return "";
		if (clientId.startsWith("custom")) return customCodeSamples.find((example) => generateCustomId(example) === clientId)?.source ?? "Custom example not found";
		const harRequest = operationToHar({
			operation,
			contentType,
			method,
			path,
			server,
			securitySchemes,
			example,
			globalCookies,
			includeDefaultHeaders
		});
		const [targetKey, clientKey] = clientId.split("/");
		const [error, payload] = getSnippet(targetKey, clientKey, harRequest);
		if (error) {
			console.error("[generateCodeSnippet]", error);
			return error.message ?? "Error generating code snippet";
		}
		return payload;
	} catch (error) {
		console.error("[generateCodeSnippet]", error);
		return "Error generating code snippet";
	}
};
//#endregion
//#region src/v2/blocks/operation-code-sample/components/OperationCodeSample.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = ["innerHTML"];
var _hoisted_2 = ["id"];
var _hoisted_3 = {
	key: 0,
	class: "request-card-footer-addon"
};
var _hoisted_4 = { class: "request-header" };
//#endregion
//#region src/v2/blocks/operation-code-sample/components/OperationCodeSample.vue
var OperationCodeSample_default = /* @__PURE__ */ _plugin_vue_export_helper_default(/* @__PURE__ */ defineComponent({
	__name: "OperationCodeSample",
	props: /* @__PURE__ */ mergeModels({
		integration: {},
		clientOptions: {},
		selectedClient: {},
		selectedServer: { default: null },
		selectedContentType: {},
		selectedExample: {},
		eventBus: {},
		securitySchemes: { default: () => [] },
		method: {},
		path: {},
		operation: {},
		fallback: { type: Boolean },
		generateLabel: { type: Function },
		isWebhook: { type: Boolean },
		globalCookies: {}
	}, {
		"selectedExample": { default: "" },
		"selectedExampleModifiers": {}
	}),
	emits: ["update:selectedExample"],
	setup(__props) {
		/** Grab the examples for the given content type */
		const requestBodyExamples = computed(() => {
			const content = getResolvedRef(__props.operation.requestBody)?.content ?? {};
			const contentType = __props.selectedContentType || Object.keys(content)[0];
			if (!contentType) return {};
			return content[contentType]?.examples ?? {};
		});
		/** The currently selected example key with v-model support */
		const selectedExampleKey = useModel(__props, "selectedExample");
		onBeforeMount(() => {
			selectedExampleKey.value ||= Object.keys(requestBodyExamples.value)[0] ?? "";
		});
		/** Grab any custom code samples from the operation */
		const customCodeSamples = computed(() => getCustomCodeSamples(__props.operation));
		/** Merge custom code samples with the client options */
		const clients = computed(() => getClients(customCodeSamples.value, __props.clientOptions));
		/** The locally selected client which would include code samples from this operation only */
		const localSelectedClient = ref(findClient(clients.value, __props.selectedClient));
		/** If the globally selected client changes we can update the local one */
		watch(() => __props.selectedClient, (newClient) => {
			const client = findClient(clients.value, newClient);
			if (client) localSelectedClient.value = client;
		});
		/** Generate HAR data for webhook requests */
		const webhookHar = computed(() => {
			if (!__props.isWebhook) return null;
			try {
				return operationToHar({
					operation: __props.operation,
					method: __props.method,
					path: __props.path,
					example: selectedExampleKey.value
				});
			} catch (error) {
				console.error("[webhookHar]", error);
				return null;
			}
		});
		/** Generate the code snippet for the selected example */
		const generatedCode = computed(() => {
			if (__props.isWebhook) return webhookHar.value?.postData?.text ?? "";
			return generateCodeSnippet({
				includeDefaultHeaders: __props.integration === "client",
				clientId: localSelectedClient.value?.id,
				customCodeSamples: customCodeSamples.value,
				operation: __props.operation,
				method: __props.method,
				path: __props.path,
				contentType: __props.selectedContentType,
				server: __props.selectedServer,
				securitySchemes: __props.securitySchemes,
				example: selectedExampleKey.value,
				globalCookies: __props.globalCookies
			});
		});
		/** The language for the code block, used for syntax highlighting */
		const codeBlockLanguage = computed(() => {
			if (__props.isWebhook) return webhookLanguage.value;
			return localSelectedClient.value?.lang;
		});
		/** Determine the language for webhook content based on MIME type */
		const webhookLanguage = computed(() => {
			if (!webhookHar.value?.postData) return "json";
			const contentType = webhookHar.value.postData.mimeType;
			if (contentType?.includes("json")) return "json";
			if (contentType?.includes("xml")) return "xml";
			if (contentType?.includes("yaml") || contentType?.includes("yml")) return "yaml";
			if (contentType?.includes("text/plain")) return "text";
			return "json";
		});
		/**  Block secrets from being shown in the code block */
		const secretCredentials = computed(() => getSecrets(__props.securitySchemes));
		/** Grab the ref to freeze the ui as the clients change so there's no jump as the size of the dom changes */
		const elem = ref(null);
		/** Set custom example, or update the selected HTTP client globally */
		const selectClient = (option) => {
			if (elem.value) {
				const unfreeze = freezeElement(elem.value.$el);
				setTimeout(() => {
					unfreeze();
				}, 300);
			}
			localSelectedClient.value = option;
			if (option && !option.id.startsWith("custom")) __props.eventBus.emit("workspace:update:selected-client", option.id);
		};
		const VIRTUALIZATION_THRESHOLD = 2e4;
		const shouldVirtualize = computed(() => (generatedCode.value.length ?? 0) > VIRTUALIZATION_THRESHOLD);
		const id = useId();
		return (_ctx, _cache) => {
			return generatedCode.value ? (openBlock(), createBlock(unref(ScalarCard), {
				key: 0,
				ref_key: "elem",
				ref: elem,
				class: "request-card dark-mode"
			}, {
				default: withCtx(() => [
					createVNode(unref(ScalarCardHeader), { class: "pr-2.5" }, createSlots({
						default: withCtx(() => [
							_cache[2] || (_cache[2] = createElementVNode("span", { class: "sr-only" }, "Request Example for", -1)),
							createVNode(HttpMethod_default, {
								as: "span",
								class: "request-method",
								method: __props.method
							}, null, 8, ["method"]),
							__props.generateLabel ? (openBlock(), createElementBlock("span", {
								key: 0,
								innerHTML: __props.generateLabel()
							}, null, 8, _hoisted_1)) : createCommentVNode("", true),
							renderSlot(_ctx.$slots, "header", {}, void 0, true)
						]),
						_: 2
					}, [!__props.isWebhook && clients.value.length ? {
						name: "actions",
						fn: withCtx(() => [createVNode(unref(ScalarCombobox), {
							class: "max-h-80",
							modelValue: localSelectedClient.value,
							options: clients.value,
							placement: "bottom-end",
							teleport: "",
							"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => selectClient($event))
						}, {
							default: withCtx(() => [createVNode(unref(ScalarButton), {
								class: "text-c-2 hover:text-c-1 flex h-full w-fit gap-1.5 px-0.5 py-0 text-base font-normal",
								"data-testid": "client-picker",
								variant: "ghost"
							}, {
								default: withCtx(() => [createTextVNode(toDisplayString(localSelectedClient.value?.title) + " ", 1), createVNode(unref(ScalarIconCaretDown), {
									class: "ui-open:rotate-180 mt-0.25 size-3 transition-transform duration-100",
									weight: "bold"
								})]),
								_: 1
							})]),
							_: 1
						}, 8, ["modelValue", "options"])]),
						key: "0"
					} : void 0]), 1024),
					createVNode(unref(ScalarCardSection), { class: "request-editor-section custom-scroll p-0" }, {
						default: withCtx(() => [createElementVNode("div", {
							id: `${unref(id)}-example`,
							class: "code-snippet"
						}, [!shouldVirtualize.value ? (openBlock(), createBlock(unref(ScalarCodeBlock), {
							key: 0,
							class: "bg-b-2 h-full",
							content: generatedCode.value,
							hideCredentials: secretCredentials.value,
							lang: codeBlockLanguage.value,
							lineNumbers: ""
						}, null, 8, [
							"content",
							"hideCredentials",
							"lang"
						])) : (openBlock(), createBlock(unref(ScalarVirtualText), {
							key: 1,
							containerClass: "custom-scroll scalar-code-block border rounded-b flex flex-1 max-h-screen",
							contentClass: "language-plaintext whitespace-pre font-code text-base",
							lineHeight: 20,
							text: generatedCode.value
						}, null, 8, ["text"]))], 8, _hoisted_2)]),
						_: 1
					}),
					Object.keys(requestBodyExamples.value).length > 1 || _ctx.$slots.footer ? (openBlock(), createBlock(unref(ScalarCardFooter), {
						key: 0,
						class: "request-card-footer bg-b-3"
					}, {
						default: withCtx(() => [Object.keys(requestBodyExamples.value).length > 1 ? (openBlock(), createElementBlock("div", _hoisted_3, [Object.keys(requestBodyExamples.value).length ? (openBlock(), createBlock(ExamplePicker_default, {
							key: 0,
							modelValue: selectedExampleKey.value,
							"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => selectedExampleKey.value = $event),
							examples: requestBodyExamples.value
						}, null, 8, ["modelValue", "examples"])) : createCommentVNode("", true)])) : createCommentVNode("", true), renderSlot(_ctx.$slots, "footer", { exampleName: selectedExampleKey.value }, void 0, true)]),
						_: 3
					})) : createCommentVNode("", true)
				]),
				_: 3
			}, 512)) : __props.fallback ? (openBlock(), createBlock(unref(ScalarCard), {
				key: 1,
				class: "request-card dark-mode"
			}, {
				default: withCtx(() => [createVNode(unref(ScalarCardSection), { class: "request-card-simple" }, {
					default: withCtx(() => [createElementVNode("div", _hoisted_4, [createVNode(HttpMethod_default, {
						as: "span",
						class: "request-method",
						method: __props.method
					}, null, 8, ["method"]), renderSlot(_ctx.$slots, "header", {}, void 0, true)]), renderSlot(_ctx.$slots, "footer", { exampleName: selectedExampleKey.value }, void 0, true)]),
					_: 3
				})]),
				_: 3
			})) : createCommentVNode("", true);
		};
	}
}), [["__scopeId", "data-v-cbc307e3"]]);
//#endregion
export { getDefaultHeaders as C, getExampleFromSchema as S, getResolvedRefDeep as T, serializeSimpleStyle as _, getClients as a, deSerializeParameter as b, findClient as c, ExamplePicker_default as d, serializeContentValue as f, serializePipeDelimitedStyle as g, serializeFormStyleForCookies as h, getCustomCodeSamples as i, isClient as l, serializeFormStyle as m, generateCodeSnippet as n, generateClientOptions as o, serializeDeepObjectStyle as p, getSecrets as r, DEFAULT_CLIENT as s, OperationCodeSample_default as t, HttpMethod_default as u, serializeSpaceDelimitedStyle as v, getExample as w, filterGlobalCookie as x, isParamDisabled as y };

//# sourceMappingURL=operation-code-sample-ZUTueV3v.js.map