import type { AnyEventListener, ApiReferenceEvents, WorkspaceEventBus } from '@scalar/workspace-store/events'; import type { RequestFactory, VariablesStore } from '@scalar/workspace-store/request-example'; import type { OpenApiDocument, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'; import type { OperationObject } from '@scalar/workspace-store/schemas/v3.2/strict/operation'; import type { Component, DefineComponent } from 'vue'; /** Shared fields present on every response body handler variant */ type ResponseBodyHandlerBase = { /** MIME type patterns this handler matches (exact or glob like "application/vnd.*+json") */ mimeTypes: string[]; /** Custom decoder: transform raw bytes into displayable data */ decode?: (buffer: ArrayBuffer, contentType: string) => string | Blob | Promise; /** Custom component for the preview view */ previewComponent?: Component; }; /** * Describes how a plugin handles a specific content type in the response body. * * The raw view is configured with either: * - `rawComponent`: A custom Vue component (receives `content` and `contentType` props). * - `language`: A CodeMirror language hint for the built-in raw renderer. * * These two options are mutually exclusive — providing `rawComponent` means the * built-in renderer is not used, so `language` would have no effect. */ export type ResponseBodyHandler = ResponseBodyHandlerBase & ({ rawComponent: Component; language?: never; } | { rawComponent?: never; language?: string; }); /** A type representing the hooks that a client plugin can define */ type ClientPluginHooks = { /** * Runs when an operation view mounts, before any request is sent. Useful for warming up * resources that would otherwise add latency to the first request (for example, lazily * created sandboxes). Receives the current document and operation so plugins can decide * whether the work is needed at all. */ onRequestMount: (payload: { document: OpenApiDocument; operation: OperationObject; }) => void | Promise; /** * Runs before a request is sent. Receives the current document and operation so plugins can * modify the request before it is sent (for example, adding headers or modifying the body). * * Mutations here happen on the request builder, before the fetch `Request` exists. Outside * Electron, use the `requestBuilt` hook when you need the exact outgoing request (for example, * to hash a multipart body for request signing). Electron sends the request payload instead. */ beforeRequest: (payload: { /** Workspace-store request spec; mutable by pre-request scripts (headers, method). */ requestBuilder: RequestFactory; document: OpenApiDocument; operation: OperationObject; variablesStore?: VariablesStore; /** Active server, so plugins can resolve relative URLs (e.g. a token endpoint). */ server?: ServerObject | null; /** Host fetch, so plugins can run network calls (e.g. a token refresh) through the same channel as the request. */ customFetch?: typeof fetch; }) => void | Promise; /** * Runs after the fetch `Request` has been built, right before it is sent. Outside Electron, the * request passed here is handed to fetch, so header mutations apply to the outgoing request and * the body bytes match what goes over the wire. Electron sends the request payload instead. * Mutations to the request builder have no effect at this stage; use `beforeRequest` for those. */ requestBuilt: (payload: { /** The fetch Request built before sending. Electron sends the request payload instead. */ request: Request; /** Request builder the request was built from. Mutating it has no effect at this stage. */ requestBuilder: RequestFactory; document: OpenApiDocument; operation: OperationObject; variablesStore?: VariablesStore; }) => void | Promise; /** * Runs before response metadata and body processing. Return a Response to replace the response * used by subsequent plugins and the client. Return nothing to keep the current response. * Each hook receives a clone, so reading its body does not consume the client response. * For streaming responses, avoid reading the entire body unless the stream is finite. */ responseReceived: (payload: { response: Response; /** Request duration in milliseconds, when supplied by the client. */ responseDuration?: number; /** Request builder object that was used to build the request. Mutating this object will not affect the request object. */ requestBuilder: RequestFactory; /** Request rebuilt from the sent request payload, not the same instance sent to the server. */ request: Request; document: OpenApiDocument; operation: OperationObject; variablesStore?: VariablesStore; }) => Response | void | Promise; }; /** Direction of a WebSocket message frame */ export type WebSocketFrameDirection = 'incoming' | 'outgoing'; /** Opcode classification for a WebSocket frame */ export type WebSocketFrameType = 'text' | 'binary' | 'close'; /** A single WebSocket message frame (sent or received) */ export type WebSocketPluginFrame = { direction: WebSocketFrameDirection; timestamp: number; data: string | ArrayBuffer; opcode: WebSocketFrameType; }; /** Close event metadata for WebSocket plugin hooks */ export type WebSocketPluginCloseInfo = { code: number; reason: string; wasClean: boolean; }; /** * WebSocket-specific plugin hooks for AsyncAPI channel operations. * * These are intentionally separate from the HTTP `ClientPluginHooks` because * the WebSocket lifecycle (long-lived connection, bidirectional frames) does * not map onto request/response semantics. */ export type ClientPluginWebSocketHooks = { /** Runs before the WebSocket handshake. Return a modified URL to override. */ beforeConnect: (payload: { url: string; }) => string | void | Promise; /** Runs for every incoming or outgoing frame on an open connection. */ onWebSocketMessage: (payload: { frame: WebSocketPluginFrame; }) => void | Promise; /** Runs when the connection closes (cleanly or due to error). */ onWebSocketClose: (payload: { info: WebSocketPluginCloseInfo; }) => void | Promise; }; /** A vue component which accepts the specified props */ type ClientPluginComponent, Emits extends Record void> = {}> = { component: DefineComponent; additionalProps?: Record; }; type ClientPluginComponents = { request: ClientPluginComponent<{ operation?: OperationObject; }, { 'operation:update:extension': (payload: ApiReferenceEvents['operation:update:extension']['payload']) => void; }>; response: ClientPluginComponent<{ operation?: OperationObject; }>; }; /** * ClientPlugin is used to extend the API Client with custom hooks and UI components. * * Example usage: * * const myPlugin: ClientPlugin = { * hooks: { * beforeRequest: async ({ requestBuilder, server, customFetch }) => { * console.log('Active server configuration:', server?.url); * * if (customFetch) { * await customFetch('https://auth.example.com/session/refresh', { method: 'POST' }); * } * * requestBuilder.headers.set('X-Custom-Header', 'foo'); * }, * responseReceived: ({ response, operation }) => { * // Handle post-response logic * console.log('Received status:', response.status, 'for operation:', operation.operationId); * } * }, * components: { * request: MyRequestComponent, // Custom Vue component for rendering the request section * response: MyResponseComponent // Custom Vue component for rendering the response section * }, * responseBody: [{ * mimeTypes: ['application/msgpack', 'application/x-msgpack'], * decode: (buffer) => { * const decoded = msgpack.decode(new Uint8Array(buffer)); * return JSON.stringify(decoded, null, 2); * }, * language: 'json', * }] * } */ /** Lifecycle hooks for app-level plugin concerns (analytics, logging, etc.) */ type ClientPluginLifecycle = { /** Called when the API client is initialized */ onInit?: (context?: { config: Record; }) => void; /** Called when the API client configuration changes */ onConfigChange?: (context: { config: Record; }) => void; /** Called when the API client is destroyed */ onDestroy?: () => void; }; export type ClientPlugin = { hooks?: Partial; /** WebSocket-specific hooks for AsyncAPI channel operations */ webSocketHooks?: Partial; components?: Partial; /** Lifecycle hooks for app-level concerns */ lifecycle?: ClientPluginLifecycle; /** * Subscribe to every event on the bus. The framework wires this up to * `bus.onAny` and handles subscribe/unsubscribe automatically. * * The listener receives a single tagged-union argument `{ event, payload }` * where `event` is the discriminant. Narrowing on `event` automatically * narrows `payload` to the exact type for that event — no casts, no `as` * assertions, and no manual runtime type checks just to satisfy the * compiler. Destructuring in the parameter list works too. * * @example * on: ({ event, payload }) => { * if (event === 'log:user-login') { * // payload is narrowed to { uid: string; email?: string; teamUid: string } * posthog.identify(payload.uid, { email: payload.email }) * } * * if (event === 'operation:create:operation') { * // payload is narrowed to the operation-create payload * analytics.track('operation_created', payload) * } * } */ on?: AnyEventListener; /** Custom response body handlers for specific content types */ responseBody?: ResponseBodyHandler[]; }; /** * Subscribes a single plugin's `on` listener to the given event bus via `onAny`. * * The plugin's `on` is passed straight through to `bus.onAny`, so it will * receive every event emitted on the bus as a `{ event, payload }` object. * Plugins without an `on` listener get a no-op unsubscribe. * * Returns an unsubscribe function. Call it when the plugin is torn down or * the bus is destroyed to remove the wildcard listener. * * @example * const unsubscribe = subscribePluginEvents(eventBus, plugin) * // later... * unsubscribe() */ export declare const subscribePluginEvents: (eventBus: WorkspaceEventBus, plugin: ClientPlugin) => (() => void); /** * Maps hook names to their expected payload types. * This ensures type safety when executing hooks with their corresponding payloads. * Derived from the ClientPlugin hooks definition. */ type HookPayloadMap = { [K in keyof ClientPluginHooks]: Parameters[0]; }; /** * Execute a request hook with type-safe payload handling. * The payload type is inferred from the hook name to ensure correct usage. */ export declare const executeHook: >(payload: HookPayloadMap[K], hookName: K, plugins: ClientPlugin[]) => Promise; /** Execute response hooks in order, releasing discarded stream branches after each hook. */ export declare const executeResponseHook: (payload: HookPayloadMap["responseReceived"], plugins: ClientPlugin[]) => Promise; type WebSocketHookPayloadMap = { [K in keyof ClientPluginWebSocketHooks]: Parameters[0]; }; /** * Execute a WebSocket plugin hook across all plugins. * * For `beforeConnect`, the returned URL string (if any) is threaded through * sequentially so each plugin can transform the URL. For fire-and-forget hooks * (`onWebSocketMessage`, `onWebSocketClose`) the return value is ignored. */ export declare const executeWebSocketHook: (payload: WebSocketHookPayloadMap[K], hookName: K, plugins: ClientPlugin[]) => Promise; export {}; //# sourceMappingURL=client-plugins.d.ts.map