import type { MarkdownRenderHook } from '@scalar/helpers/markdown/markdown-render-hook'; import type { PartialDeep } from 'type-fest'; import type { AvailableClient, ClientId, TargetId } from '../snippetz/index.js'; import type { ApiClientTranslations } from './api-client-translations.js'; import type { PluginAuthState, PluginNavigationEntry } from './api-reference-plugin.js'; /** Some common properties used in all security schemes */ type SecuirtySchemeCommon = { description: string | undefined; }; type ExtendedSecurityScheme = { uid: any; /** The name key that links a security requirement to a security object */ nameKey: string; }; type SecuritySchemeApiKeyIn = 'query' | 'header' | 'cookie'; type OasSecurityApiKey = { type: 'apiKey'; /** REQUIRED. The name of the header, query or cookie parameter to be used. */ name: string; /** REQUIRED. The location of the API key. Valid values are "query", "header" or "cookie". */ in: SecuritySchemeApiKeyIn; /** REQUIRED. The API key to be sent in the Authorization header or as a cookie. */ value: string; /** Prefix added to header API keys only, separated from the raw credential by one space. */ 'x-scalar-token-prefix'?: string; }; export type SecuritySchemeApiKey = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityApiKey; type OasSecurityHttp = { type: 'http'; /** REQUIRED. The name of the HTTP Authorization scheme to be used in the Authorization header as defined in * [RFC7235]. The values used SHOULD be registered in the IANA Authentication Scheme registry. */ scheme: 'basic' | 'bearer'; /** A hint to the client to identify how the bearer token is formatted. * Bearer tokens are usually generated by an authorization server, so * this information is primarily for documentation purposes. */ bearerFormat: 'JWT' | string; /** The username to be sent in the Authorization header. */ username: string; /** The password to be sent in the Authorization header. */ password: string; /** The token to be sent in the Authorization header. */ token: string; }; export type SecuritySchemeHttp = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityHttp; type OasSecurityOpenIdConnect = { type: 'openIdConnect'; /** REQUIRED. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the * form of a URL. The OpenID Connect standard requires the use of TLS. */ openIdConnectUrl: string; /** Defaults applied to matching flows after OpenID Connect discovery. */ flows?: PartialDeep; /** Scopes selected by default after discovery. */ 'x-default-scopes'?: string[]; }; export type SecuritySchemeOpenIdConnect = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityOpenIdConnect; type FlowsCommon = { /** * The URL to be used for obtaining refresh tokens. This MUST be in the form of a * URL. The OAuth2 standard requires the use of TLS. */ 'refreshUrl'?: string; /** * REQUIRED. The available scopes for the OAuth2 security scheme. A map * between the scope name and a short description for it. The map MAY be empty. */ 'scopes'?: Record; 'selectedScopes'?: string[]; /** Extension to save the client Id associated with an oauth flow */ 'x-scalar-client-id'?: string; /** The auth token */ 'token'?: string; /** Additional query parameters for the OAuth authorization request. Example: { prompt: 'consent', audience: 'scalar' }. */ 'x-scalar-security-query'?: Record; /** Additional body parameters for the OAuth token request. Example: { audience: 'foo' }. */ 'x-scalar-security-body'?: Record; /** Extension to specify custom token name in the response (defaults to 'access_token') */ 'x-tokenName'?: string; /** Display order of this flow's tab in the auth UI (ascending). Flows with an order come first. */ 'x-order'?: number; /** When true, this flow's tab is hidden from the auth UI. */ 'x-scalar-ignore'?: boolean; }; type PkceOptions = 'SHA-256' | 'plain' | 'no'; type CredentialsLocationExtension = 'header' | 'body'; type OasSecurityOauth2FlowImplicit = { type: 'oauth2'; 'x-default-scopes'?: string[]; flows: { deviceAuthorization: FlowsCommon & { type: 'deviceAuthorization'; deviceAuthorizationUrl: string; tokenUrl: string; clientSecret: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; }; implicit: FlowsCommon & { type: 'implicit'; authorizationUrl: string; 'x-scalar-redirect-uri'?: string; }; password: FlowsCommon & { type: 'password'; tokenUrl: string; clientSecret: string; username: string; password: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; }; clientCredentials: FlowsCommon & { type: 'clientCredentials'; tokenUrl: string; clientSecret: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; }; authorizationCode: FlowsCommon & { type: 'authorizationCode'; authorizationUrl: string; tokenUrl: string; clientSecret: string; 'x-scalar-credentials-location'?: CredentialsLocationExtension; 'x-usePkce'?: PkceOptions; 'x-scalar-redirect-uri'?: string; }; }; }; export type SecuritySchemeOauth2 = SecuirtySchemeCommon & ExtendedSecurityScheme & OasSecurityOauth2FlowImplicit; export type SecurityScheme = SecuritySchemeApiKey | SecuritySchemeHttp | SecuritySchemeOpenIdConnect | SecuritySchemeOauth2; /** * Authentication configuration for the API reference. * This config is not validated so does not need a zod schema */ export type AuthenticationConfiguration = { /** * Specifies the preferred security scheme(s) to use for authentication. * Can be one of: * - A single security scheme name (string) * - An array of security scheme names (OR relationship) * - An array containing strings or arrays of strings (AND/OR relationship) */ preferredSecurityScheme?: string | (string | string[])[] | null; /** * Setting security schemes this way will allow you to override any value in your openapi document * You will also be able to set additional values such as api tokens etc. * * Set them via the nameKey in your components.securitySchemes.[nameKey] * * @example * ```ts * { * authentication: { * preferredSecurityScheme: 'apiKeyHeader', * securitySchemes: { * apiKeyHeader: { * value: 'tokenValue' * }, * httpBearer: { * token: 'xyz token value' * }, * httpBasic: { * username: 'username', * password: 'password' * }, * oauth2: { * flows: { * authorizationCode: { * token: 'auth code token' * } * } * }, * }, * } * } * ``` * */ securitySchemes?: Record>; /** * Allows adding authentication which is not in the document. * When true, generic options (API Key, HTTP Basic, OAuth2, etc.) are shown in the auth dropdown. * @default false */ createAnySecurityScheme?: boolean; /** * Restricts visible authentication choices and forms to these scheme names. * Omit to show all schemes; an empty array hides all choices, including generic creation. * This does not change authentication sent with requests or API security requirements. */ allowedSecuritySchemes?: string[]; }; export type SpecificationExtension = { name: string; component: unknown; renderer?: unknown; }; export type ViewComponent = { component: unknown; renderer?: unknown; props?: Record; sidebar?: { /** Whether to show an entry for this view in the sidebar */ show: boolean; /** Label to display in the sidebar */ label: string; }; }; /** * A document format that API Reference does not support natively (it supports OpenAPI and AsyncAPI). * * The plugin detects documents of its format, optionally normalizes them, builds their sidebar entries, * and renders the whole document. Loading, the document selector, routing and the sidebar are handled * by API Reference. */ export type PluginDocumentType = { /** Stable identifier, stored on every claimed document as `x-scalar-document-type`. */ type: string; /** Whether this type handles the raw (parsed) document. Checked before OpenAPI and AsyncAPI. */ detect: (document: Record) => boolean; /** * Optional hook to upgrade, validate or normalize the document before it is stored. API Reference * keeps two stores, so this can run more than once per document: keep it free of side effects. */ ingest?: (document: Record, context: { documentName: string; }) => Record | Promise>; /** Resolve `$ref`s with the configured fetch before storing the document. Defaults to `false`. */ bundle?: boolean; /** Build the sidebar entries for the document. */ traverse: (context: { documentName: string; documentId: string; document: Record; }) => PluginNavigationEntry[]; /** * Renders the document in place of the built-in content. * * The component receives `document`, `documentName`, `documents` (every document in the workspace, * read-only), `navigation` (its sidebar entries), `eventBus` and `options`. Each rendered entry should * use the entry `id` as its element id, so sidebar navigation and deep links can scroll to it. To keep * the sidebar and the URL in sync while scrolling, emit `intersecting:nav-item` with the entry `id` on * the `eventBus` when an entry scrolls into view. */ content: { component: unknown; renderer?: unknown; props?: Record; }; }; export type LifecycleHooks = { onInit?: ({ config, auth }: { config: Partial; auth: PluginAuthState; }) => void; onConfigChange?: ({ config, auth }: { config: Partial; auth: PluginAuthState; }) => void; onDestroy?: () => void; }; export type ApiReferencePlugin = () => { name: string; extensions: SpecificationExtension[]; views?: { 'content.start'?: ViewComponent[]; 'content.end'?: ViewComponent[]; }; /** Document formats this plugin teaches API Reference to load and render. */ documentTypes?: PluginDocumentType[]; hooks?: LifecycleHooks; apiClientPlugins?: any[]; /** Enhance sanitized Markdown after it renders in the browser. */ markdown?: MarkdownRenderHook; }; export type ExternalUrls = { dashboardUrl: string; registryUrl: string; proxyUrl: string; apiBaseUrl: string; }; export type BaseConfiguration = { /** The title of the OpenAPI document. */ title?: string; /** The slug of the OpenAPI document used in the URL. If none is passed, the title will be used. If no title is used, it will just use the index. */ slug?: string; /** Prefill authentication */ authentication?: any; /** Base URL for the API server */ baseServerURL?: string; /** Whether to hide the client button */ hideClientButton: boolean; /** URL to a request proxy for the API client */ proxyUrl?: string; /** Default OAuth 2.0 redirect URI used to prefill auth flows in the API client. */ oauth2RedirectUri?: string; /** Key used with CTRL/CMD to open the search modal (defaults to 'k' e.g. CMD+k) */ searchHotKey?: 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z'; /** List of OpenAPI server objects */ servers?: any[]; /** Whether to show the sidebar */ showSidebar: boolean; /** Whether and when to show the developer tools. */ showDeveloperTools: 'localhost' | 'always' | 'never'; /** @deprecated Use showDeveloperTools instead */ showToolbar: 'localhost' | 'always' | 'never'; /** Whether to use the operation summary or the operation path for the sidebar and search */ operationTitleSource: 'summary' | 'path'; /** A string to use one of the color presets */ theme: 'default' | 'alternate' | 'moon' | 'purple' | 'solarized' | 'bluePlanet' | 'deepSpace' | 'saturn' | 'kepler' | 'elysiajs' | 'fastify' | 'mars' | 'laserwave' | 'halloween' | 'none'; /** Integration type identifier */ _integration?: 'adonisjs' | 'astro' | 'docusaurus' | 'dotnet' | 'elysiajs' | 'express' | 'fastapi' | 'fastify' | 'go' | 'hono' | 'html' | 'laravel' | 'litestar' | 'nestjs' | 'nextjs' | 'nitro' | 'nuxt' | 'platformatic' | 'react' | 'rust' | 'svelte' | 'vue' | null; /** onRequestSent is fired when a request is sent */ onRequestSent?: (input: string) => void; /** Whether to persist auth to local storage */ persistAuth: boolean; /** Enables / disables telemetry */ telemetry: boolean; /** External service URLs used by Scalar packages */ externalUrls: ExternalUrls; }; /** User-facing label for the components.schemas section in the sidebar, content, and search. */ export type ModelsSectionLabel = 'Models' | 'Schemas' | (string & {}); /** Default label for the components.schemas section. Preserves the historical `Models` wording and the `#models` hash. */ export declare const DEFAULT_MODELS_SECTION_LABEL: ModelsSectionLabel; /** Built-in locale identifiers shipped with the API Reference UI. */ export type ApiReferenceBuiltInLocale = 'en' | 'ru' | 'es' | 'fr' | 'de' | 'zh-CN' | 'zh-TW' | 'ar' | 'pt'; /** Locale identifier used to select built-in translations. */ export type ApiReferenceLocale = ApiReferenceBuiltInLocale | (string & {}); /** Text direction used by the rendered API Reference. */ export type ApiReferenceTextDirection = 'ltr' | 'rtl'; /** Text direction configuration. `auto` derives the direction from the locale. */ export type ApiReferenceTextDirectionPreference = ApiReferenceTextDirection | 'auto'; export type { ApiClientTranslations } from './api-client-translations.js'; /** User-facing UI copy for API Reference shell labels. */ export type ApiReferenceTranslations = { /** Optional API Client strings. The client supplies its own English fallback. */ apiClient?: ApiClientTranslations; common: { description: string; httpMethod: string; path: string; copyDefault: string; copyExample: string; streamItem: string; }; search: { label: string; inputLabel: string; open: string; placeholder: string; clear: string; noResults: string; keyboardShortcut: string; command: string; control: string; results: string; navigate: string; select: string; instructions: string; entryHeading: string; entryOperation: string; entryTag: string; entryTagGroup: string; entryChannel: string; entryMessage: string; entryWebhook: string; }; navigation: { introduction: string; closeGroup: string; closeMenu: string; openGroup: string; openMenu: string; operations: string; webhooks: string; channels: string; endpoints: string; showAllEndpoints: string; sidebarFor: string; mainContent: string; collapsed: string; }; server: { label: string; select: string; }; info: { termsOfService: string; }; asyncapi: { /** Label for the root AsyncAPI application identifier. */ applicationIdentifier: string; /** Label for the actual channel address, distinct from its identifier. */ address: string; /** Displayed when a channel address is absent or null. */ unknownAddress: string; servers: string; protocols: string; }; clientLibraries: { heading: string; more: string; selectAll: string; /** Accessible name for the search field inside the client picker */ searchLabel: string; /** Accessible name describing what the client picker does */ changeClient: string; }; operation: { codeSampleUnavailable: string; codeSample: string; body: string; cookies: string; headers: string; pathParameters: string; queryParameters: string; requestBody: string; responses: string; testRequest: string; webhook: string; audience: string; selectedContentType: string; callbacks: string; }; response: { exampleResponses: string; xmlGenerationLimit: string; xmlGenerationFailed: string; noBody: string; showSchema: string; status: string; }; schema: { example: string; examples: string; default: string; schema: string; variants: string; discriminatorValue: string; noAllowedValues: string; emptyObject: string; showAdditionalProperties: string; showOneMoreProperty: string; showMoreProperties: string; forName: string; showSchemaDetails: string; oneOf: string; anyOf: string; allOf: string; not: string; unknownType: string; propertyCount: string; headerCount: string; recursiveReference: string; recursive: string; additionalProperties: string; const: string; deprecated: string; discriminator: string; enum: string; format: string; greaterThan: string; keys: string; lessThan: string; max: string; min: string; maxLength: string; minLength: string; multipleOf: string; nullable: string; propertyNames: string; pattern: string; copyPattern: string; readOnly: string; required: string; hideValues: string; showAllValues: string; type: string; unique: string; values: string; writeOnly: string; typeInteger: string; formatInt32: string; formatInt64: string; formatDate: string; formatDateTime: string; formatPassword: string; formatBase64: string; formatBinary: string; }; download: { openapi: string; asyncapi: string; /** Accessible name distinguishing the download buttons, e.g. "Download OpenAPI Document as JSON" */ asFormat: string; }; models: { label: string; }; actions: { copyAsMarkdown: string; copied: string; copyMarkdownFailed: string; copyLink: string; copyLinkTo: string; copyToClipboard: string; copyEndpointUrl: string; showMore: string; }; agent: { askAi: string; askAiAgent: string; close: string; }; mcp: { generate: string; connect: string; }; sdk: { /** Label for the button that opens the dashboard to generate an SDK */ generate: string; }; developerTools: { title: string; configure: string; share: string; deploy: string; scalarConfiguration: string; theme: string; layout: string; layoutOptions: string; intro: string; disableToolbarBefore: string; disableToolbarAfter: string; localhostOnly: string; layoutModern: string; layoutClassic: string; showSidebar: string; defaultOpenFirstTag: string; defaultOpenAllTags: string; expandAll: string; expandAllParameters: string; expandAllSchemaProperties: string; hideModelNames: string; orderRequiredPropertiesFirst: string; orderSchemaPropertiesBy: string; alphabeticalOrder: string; documentOrder: string; expandAllResponses: string; hideClientButton: string; hideDarkModeToggle: string; hideModels: string; hideSearch: string; showOperationId: string; hideTestRequestButton: string; scalarDocs: string; deployDescription: string; shareTitle: string; shareDescription: string; uploadDocument: string; temporaryLinkExpiration: string; deployOnScalar: string; deployFree: string; additionalFeaturesMightRequire: string; generate: string; passwordProtection: string; customDomains: string; freeFormContent: string; cdnInfrastructure: string; pullFromGitHub: string; markdownMdx: string; spectralLinting: string; jsonSchemaHosting: string; askAi: string; mcpServers: string; unableToExportDocument: string; unknownError: string; waitlistEmail: string; waitlistPlaceholder: string; joinWaitlist: string; waitlistSuccess: string; waitlistError: string; waitlistRateLimit: string; waitlistBack: string; waitlistDone: string; deployApiButton: string; deployFrameworkButton: string; deployApiTitle: string; deployFrameworkTitle: string; deployApiDescription: string; hostingScaleTitle: string; hostingScaleDescription: string; hostingIdleTitle: string; hostingIdleDescription: string; hostingDeploysTitle: string; hostingDeploysDescription: string; hostingPlans: string; hostingSeePlans: string; }; exploreScalar: { /** The sidebar call to action that opens the dialog */ cta: string; headline: string; title: string; generateTitle: string; generateDescription: string; platformTitle: string; platformDescription: string; signUp: string; bookDemo: string; getDemo: string; messageMarc: string; /** Tooltip on the X logo, in Marc's own voice */ dmMarc: string; close: string; opensInNewTab: string; popupBlocked: string; back: string; openBookingPage: string; }; gettingStarted: { swaggerEditor: string; description: string; showExample: string; uploadFile: string; integrations: string; theming: string; features: string; customize: string; customizeDescription: string; testing: string; testingDescription: string; search: string; searchDescription: string; hosting: string; hostingDescription: string; openApiSwagger: string; openApiSwaggerDescription: string; codeSamples: string; codeSamplesDescription: string; }; footer: { poweredByScalar: string; }; authentication: { detailsRequired: string; detailsOptional: string; apiKey: string; mutualTLS: string; apiKeyCookie: string; apiKeyHeader: string; apiKeyQuery: string; title: string; accepts: string; allOf: string; authentication: string; optional: string; oneOf: string; required: string; requires: string; scopes: string; }; }; /** * Recursively flattens a nested translations object into a union of dot-path keys. * For example, `{ search: { label: string } }` becomes `'search.label'`. */ type TranslationDotPaths = { [Key in keyof T & string]: T[Key] extends string ? `${Prefix}${Key}` : T[Key] extends Record ? TranslationDotPaths : never; }[keyof T & string]; /** Dot-path key into {@link ApiReferenceTranslations} (for example, `search.label` or `schema.oneOf`). */ export type ApiReferenceTranslationKey = TranslationDotPaths; /** API Reference localization configuration. */ export type ApiReferenceLocalization = { /** Locale used for built-in UI translations. */ locale?: ApiReferenceLocale; /** Text direction. `auto` derives direction from locale. */ direction?: ApiReferenceTextDirectionPreference; /** Custom UI translations. Values are merged with the built-in locale and English fallback. */ translations?: PartialDeep; }; type ExtendedConfiguration = { /** The layout to use for the references */ layout: 'modern' | 'classic'; /** @deprecated Use proxyUrl instead */ proxy?: string; /** * Custom fetch function for custom logic. Can be used to add custom headers, handle auth, etc. * * @deprecated Use `customFetch` instead. */ fetch?: typeof fetch; /** * Custom fetch function used both when loading the OpenAPI document and when sending requests from the API client. * * Can be used to add custom headers, attach credentials (for example `credentials: 'include'`), handle auth, etc. */ customFetch?: typeof fetch; /** Plugins for the API reference */ plugins?: ApiReferencePlugin[]; /** * URLs of ESM modules that provide additional plugins for the API reference. * * Each module is loaded with a dynamic `import()` before the API reference mounts, and its * default export is registered as a plugin (the same shape as the `plugins` entries). * * Unlike `plugins`, this option is JSON-serializable, so integrations that pass their * configuration as JSON can load plugins without replacing the whole bundle. * * Note: This is only supported by the standalone browser build (`Scalar.createApiReference`). * When you render the `ApiReference` component yourself, import the plugin and pass it via * `plugins` instead. * * @example ['https://cdn.jsdelivr.net/npm/@example/scalar-plugin/dist/plugin.js'] */ pluginUrls?: string[]; /** Allows the user to inject an editor for the spec */ isEditable: boolean; /** Whether to show models in the sidebar, search, and content. */ hideModels: boolean; /** Show structural types instead of model names in schema type labels and operation headings. */ hideModelNames?: boolean; /** Label for the components.schemas section (`Models`, `Schemas`, or any custom string). */ modelsSectionLabel?: ModelsSectionLabel; /** API Reference UI localization configuration. */ localization?: ApiReferenceLocalization; /** Sets the file type of the document to download, set to `none` to hide the download button */ documentDownloadType: 'both' | 'yaml' | 'json' | 'direct' | 'none'; /** @deprecated Use `documentDownloadType: 'none'` instead */ hideDownloadButton?: boolean; /** Whether to show the "Test Request" button */ hideTestRequestButton: boolean; /** Whether to show the sidebar search bar */ hideSearch: boolean; /** Whether to show the operationId */ showOperationId: boolean; /** Whether to show the x-badges of operations, webhooks, tags, tag groups and models in the sidebar */ showBadgesInSidebar: boolean; /** Extension keys to display on Paths Objects, Path Items, operations, parameters, response headers, and schema fields. Custom plugin components take precedence. */ showExtensions?: string[]; /** Whether dark mode is on or off initially (light mode) */ darkMode?: boolean; /** forceDarkModeState makes it always this state no matter what */ forceDarkModeState?: 'dark' | 'light'; /** Whether to show the dark mode toggle */ hideDarkModeToggle: boolean; /** If used, passed data will be added to the HTML header. @see https://unhead.unjs.io/usage/composables/use-seo-meta */ metaData?: any; /** Path to a favicon image */ favicon?: string; /** * List of httpsnippet clients to hide from the clients menu. By default hides Unirest, pass `[]` to show all clients * * An entry can be a target (`'node'`), a client name (`'fetch'`), or a full id (`'node/fetch'`). The record form is * keyed by target, with `true` to hide the whole target or a list of client names to hide within it. */ hiddenClients?: Partial[]>> | Array | AvailableClient> | true; /** * Whether to save and restore the selected code sample client using local storage. * @default true */ persistSelectedClient?: boolean; /** Determine the HTTP client that is selected by default */ defaultHttpClient?: { targetKey: TargetId; clientKey: ClientId; } | { targetKey: 'custom'; clientKey: string; }; /** * Clients shown as tabs in the "Client Libraries" block, in order. The rest stay available in the "More" menu. */ featuredClients?: Array; /** * Show built-in HTTP clients alongside `x-scalar-sdk-installation` tabs in the introduction. * @default false */ showDefaultClientsWithSdkInstallation?: boolean; /** * Initial view for the request body editor with structured (JSON/YAML) bodies. * * Use `form` to open the schema-driven form view by default, or `raw` for the code editor. * When a body cannot be shown as a form, Scalar falls back to `raw`. A document can override * this per source with the `x-scalar-default-request-body-view` extension. * * @default 'raw' */ defaultRequestBodyView?: 'form' | 'raw'; /** Use indexed dotted names for nested multipart and URL-encoded form fields, such as `items[0].name`. */ multipartNaming?: MultipartNaming; /** Custom CSS to be added to the page */ customCss?: string; /** onServerChange is fired on selected server change */ onServerChange?: (input: string) => void; /** onDocumentSelect is fired when the config is selected */ onDocumentSelect?: () => void | Promise; /** Callback fired when the reference is fully loaded */ onLoaded?: (slug: string) => void | Promise; /** Fired before the outbound request is built; callback receives a mutable request builder. Experimental API. */ onBeforeRequest?: ((input: { request: Request; requestBuilder: any; envVariables: Record; }) => void | Promise) | undefined; /** Fired right before the outbound request is sent; callback receives the exact fetch Request that goes over the wire. Experimental API. */ onRequestBuilt?: ((input: { request: Request; requestBuilder: any; envVariables: Record; }) => void | Promise) | undefined; /** Fired before response processing. Return a Response to replace it, or nothing to keep it. */ onResponseReceived?: (input: { response: Response; request: Request; }) => Response | void | Promise; /** onShowMore is fired when the user clicks the "Show more" button on the references */ onShowMore?: (tagId: string) => void | Promise; /** onSidebarClick is fired when the user clicks on a sidebar item */ onSidebarClick?: (href: string) => void | Promise; /** Sync navigation with the browser URL. Set to false to leave the host URL and history alone. Defaults to true. */ urlRouting?: boolean; /** Route using paths instead of hashes, your server MUST support this. @experimental */ pathRouting?: { basePath: string; }; /** MCP (Model Context Protocol) configuration. When provided, enables MCP integration with the given name and url. */ mcp?: { /** Display name for the MCP server */ name?: string; /** URL of the MCP server */ url?: string; /** When true, disables the MCP integration */ disabled?: boolean; }; /** Customize the heading portion of the hash */ generateHeadingSlug?: (input: { slug?: string; }) => string; /** Customize the model portion of the hash */ generateModelSlug?: (input: { name?: string; }) => string; /** Customize the tag portion of the hash */ generateTagSlug?: (input: { name?: string; }) => string; /** Customize the operation portion of the hash */ generateOperationSlug?: (input: { path: string; operationId?: string; method: string; summary?: string; }) => string; /** Customize the webhook portion of the hash */ generateWebhookSlug?: (input: { name: string; method?: string; }) => string; /** * Customize the browser tab title. * * Called whenever the section in view changes — on sidebar clicks, on scroll, and when switching documents. * Receives the title of the section currently in view and the active OpenAPI document. */ setPageTitle?: (input: { title: string; document: { title: string; slug: string; }; }) => string; /** To handle redirects, pass a function that receives the current path/hash and passes that to history.replaceState */ redirect?: (input: string) => string | null | undefined; /** Whether to include default fonts */ withDefaultFonts: boolean; /** Whether to expand the first tag in the sidebar when no specific URL target is present */ defaultOpenFirstTag: boolean; /** Whether to expand all tags by default. Warning: this can cause performance issues on big documents */ defaultOpenAllTags: boolean; /** Whether to expand all models by default. Warning: this can cause performance issues on big documents */ expandAllModelSections: boolean; /** Whether to show parameter details by default. Set to false to collapse each parameter. */ expandAllParameters: boolean; /** Whether to expand all responses by default. Warning: this can cause performance issues on big documents */ expandAllResponses: boolean; /** Whether to expand all nested schema properties. Warning: this can cause performance issues on big documents */ expandAllSchemaProperties: boolean; /** Maximum initially visible top-level request body properties. Defaults to 12; 0 shows all without expanding nested properties. */ maxVisibleRequestBodyProperties: number; /** Function to sort tags */ tagsSorter?: 'alpha' | ((a: any, b: any) => number); /** Function to sort operations */ operationsSorter?: 'alpha' | 'method' | ((a: any, b: any) => number); /** Order the schema properties by */ orderSchemaPropertiesBy: 'alpha' | 'preserve'; /** Arrow-key navigation over the schema disclosure toggles */ schemaKeyboardNav: boolean; /** Sort the schema properties by required ones first */ orderRequiredPropertiesFirst: boolean; }; /** Naming convention for multipart and URL-encoded request fields. */ export type MultipartNaming = 'indexed-dot'; export type SourceConfiguration = { /** Authentication overrides merged with the shared configuration. Arrays replace shared arrays. */ authentication?: AuthenticationConfiguration; default?: boolean; /** URL to an OpenAPI/Swagger document */ url?: string; /** Directly embed the OpenAPI document. Can be a string, object, function returning an object, or null. It is recommended to pass a URL instead of content. */ content?: string | null | Record | (() => string | any); /** The title of the OpenAPI document. Used for the page title and the document name in the dropdown. With multiple `sources`, set this per source. */ title?: string; /** The slug of the OpenAPI document used in the URL. If none is passed, the title will be used. With multiple `sources`, set this per source. */ slug?: string; /** @deprecated Use `url` and `content` on the top level instead. */ spec?: { url?: string; content?: string | null | Record | (() => string | any); }; /** Agent Scalar configuration */ agent?: { key?: string; disabled?: boolean; /** When true, hide the control to add more APIs in the agent chat. Only preloaded/registry documents are shown; the public API list is not offered. */ hideAddApi?: boolean; }; }; export type ApiReferenceConfigurationRaw = Omit & { authentication?: AuthenticationConfiguration; }; export type ApiReferenceConfiguration = ApiReferenceConfigurationRaw & { /** @deprecated * This type now refers to the base configuration that does not include the sources. * Use the type `ApiReferenceConfigurationWithSource` instead. */ url?: SourceConfiguration['url']; /** @deprecated * This type now refers to the base configuration that does not include the sources. * Use the type `ApiReferenceConfigurationWithSource` instead. */ content?: SourceConfiguration['content']; /** * Fired before the outbound request is built and sent. Mutate the **request builder** so the eventual fetch call * reflects your changes (method, path, headers, body, and related fields). * * The `request` passed here is **not** the object sent over the wire; the actual request is rebuilt from the builder * afterwards. Use `onRequestBuilt` instead when you need the exact outgoing request (for example, to hash a * `multipart/form-data` body for request signing). * * **Experimental:** The builder matches {@link https://github.com/scalar/scalar/blob/main/packages/workspace-store/src/request-example/builder/request-factory.ts RequestFactory} * (`import type { RequestFactory } from '@scalar/workspace-store/request-example'`). That shape is still experimental and may change in minor releases. * * @param input - Hook argument from the integration layer. * @param input.request - **Deprecated** when treated as a fetch API `Request`. Prefer thinking of this value as the * mutable builder ({@link https://github.com/scalar/scalar/blob/main/packages/workspace-store/src/request-example/builder/request-factory.ts RequestFactory}). * Some call sites only pass this property. * @param input.requestBuilder - The same builder when exposed under this name; **prefer** mutating this when your integration provides it. * @returns void or a promise that resolves when the hook finishes * @example * ```ts * onBeforeRequest: ({ request: builder }) => { * builder.headers.set('Authorization', 'Bearer ') * } * ``` */ onBeforeRequest?: (input: { request: Request; requestBuilder: any; envVariables: Record; }) => void | Promise | undefined; /** * Fired before response processing. Return a Response to replace the body, status, or headers * used by the client, or return nothing to keep the current response. Receives a clone so * reading the body does not consume the client response. Avoid reading unbounded streams. */ onResponseReceived?: (input: { response: Response; request: Request; }) => Response | void | Promise; /** * Fired after the outbound fetch `Request` has been built, right before it is sent. The `request` is the exact * object handed to fetch: mutating its headers modifies the outgoing request, and hashing its body produces a * hash that matches what the server receives (useful for request signing — a rebuilt `multipart/form-data` body * would get a different boundary). * * Use `onBeforeRequest` instead when you need to mutate the request builder (method, path, query, body, * security); those mutations have no effect at this stage because the request is already built. * * **Experimental:** This API may change in minor releases. * * @param input - Hook argument from the integration layer. * @param input.request - The exact fetch API `Request` that will be sent. Mutate its headers to modify the outgoing request. * @param input.requestBuilder - The builder the request was built from, for inspection. Mutating it has no effect at this stage. * @param input.envVariables - Resolved environment variables for the active environment. * @returns void or a promise that resolves when the hook finishes * @example * ```ts * onRequestBuilt: async ({ request }) => { * const bodyHash = await hash(await request.clone().arrayBuffer()) * request.headers.set('X-Body-Hash', bodyHash) * } * ``` */ onRequestBuilt?: (input: { request: Request; requestBuilder: any; envVariables: Record; }) => void | Promise | undefined; }; export type ApiReferenceConfigurationWithSource = Omit & SourceConfiguration; /** * Configuration for a single config with multiple sources * The configuration will be shared between the documents */ export type ApiReferenceConfigurationWithMultipleSources = ApiReferenceConfigurationWithSource & { sources: SourceConfiguration[]; }; /** Configuration for multiple Api References */ export type AnyApiReferenceConfiguration = Partial | Partial | Partial[] | Partial[]; /** Typeguard to check to narrow the configs to the one with sources */ export declare const isConfigurationWithSources: (config: AnyApiReferenceConfiguration) => config is Partial; export type ApiClientConfiguration = BaseConfiguration & SourceConfiguration; //# sourceMappingURL=types.d.ts.map