### Basic HTTP request example with variables Source: https://github.com/anweber/httpyac/blob/main/README.md Shows a simple .http file using variables and an HTTP GET request with Basic authentication. ```http @user = doe @password = 12345678 GET https://httpbin.org/basic-auth/{{user}}/{{password}} Authorization: Basic {{user}} {{password}} ``` -------------------------------- ### httpyac help send output Source: https://github.com/anweber/httpyac/blob/main/README.md Displays detailed help for the 'send' command, including arguments and all available options. ```shell > httpyac help send Usage: httpyac send [options] send/ execute http files Arguments: fileName path to file or glob pattern Options: -a, --all execute all http requests in a http file --bail stops when a test case fails -e, --env list of environments --filter filter requests output (only-failed) --insecure allow insecure server connections when using ssl -i --interactive do not exit the program after request, go back to selection --json use json output --junit use junit xml output -l, --line line of the http requests -n, --name name of the http requests --no-color disable color support -o, --output output format of response (short, body, headers, response, exchange, none) --output-failed output format of failed response (short, body, headers, response, exchange, none) --raw prevent formatting of response body --quiet --repeat repeat count for requests --repeat-mode repeat mode: sequential, parallel (default) --parallel send parallel requests -s, --silent log only request -t, --tag list of tags to execute --timeout maximum time allowed for connections --var list of variables -v, --verbose make the operation more talkative -h, --help display help for command ``` -------------------------------- ### Install httpyac globally and check version Source: https://github.com/anweber/httpyac/blob/main/README.md Install the httpyac CLI globally via npm and verify the installation by checking the version. ```shell npm install -g httpyac httpyac --version ``` -------------------------------- ### httpyac --help output Source: https://github.com/anweber/httpyac/blob/main/README.md Displays the main help output for the httpyac CLI, listing available commands and options. ```shell > httpyac --help Usage: httpyac [options] [command] httpYac - Quickly and easily send REST, SOAP, GraphQL and gRPC requests Options: -V, --version output the version number -h, --help display help for command Commands: oauth2 [options] generate oauth2 token send [options] send/ execute http files help [command] display help for command ``` -------------------------------- ### Run httpyac using Docker Source: https://github.com/anweber/httpyac/blob/main/README.md Run httpyac in a Docker container, mounting the current directory to /data and checking the version. ```shell docker run -it -v ${PWD}:/data ghcr.io/anweber/httpyac:latest --version ``` -------------------------------- ### Example .httpyac.js configuration Source: https://github.com/anweber/httpyac/blob/main/_autodocs/configuration.md Example JavaScript configuration file exporting an EnvironmentConfig object. Sets log level, request timeout, rejectUnauthorized, envDirName, and environments with $shared and dev hosts. ```javascript module.exports = { log: { level: 'debug' }, request: { timeout: 3000, rejectUnauthorized: false }, envDirName: 'env', environments: { $shared: { host: 'https://example.com' }, dev: { host: 'https://dev.example.com' }, }, }; ``` -------------------------------- ### Example plugin with configureHooks Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-registration.md Shows a minimal plugin that adds a request hook to set a custom header. The hook is registered via api.hooks.onRequest.addHook. ```ts import type { HttpyacHooksApi } from 'httpyac'; export function configureHooks(api: HttpyacHooksApi) { api.hooks.onRequest.addHook('myHeader', async request => { request.headers = { ...request.headers, 'x-my-header': '1' }; }); } ``` -------------------------------- ### Import gotHttpClient, getClientOptions, toHttpResponse, HttpRequestClient from httpyac Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-http.md Import the HTTP client utilities and class from the httpyac package. The module import installs the default request client/exchange on httpClientProvider; registerHttpPlugin must run to add auth/cookie hooks. ```TypeScript import { gotHttpClient, getClientOptions, toHttpResponse, HttpRequestClient } from 'httpyac'; ``` -------------------------------- ### HttpRegion class implementation Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Concrete implementation of the models.HttpRegion interface. The constructor binds the region to an httpFile and optionally sets a start line for a placeholder symbol. ```TypeScript export class HttpRegion implements models.HttpRegion { public constructor(private readonly httpFile: models.HttpFile, start = 0) {} } ``` -------------------------------- ### Send a file using HttpFileStore Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/httpYacApi.md Creates an HttpFileStore, gets or creates an httpFile, and sends it. Logs success or failure based on the boolean result. ```ts import { send, HttpFileStore } from 'httpyac'; const httpFileStore = new HttpFileStore(); const httpFile = await httpFileStore.getOrCreate('demo.http', async () => fileText, 0, {}); const result = await send({ httpFile }); console.log(result ? 'all requests succeeded' : 'some request failed'); ``` -------------------------------- ### HTTP request file with test script Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/index.md Shows a .http file parsed into an HttpRegion per request block, using ### delimiters. Defines a baseUrl variable and a GET request with a test script that asserts the response status is 200. ```http @baseUrl = https://httpbin.org ### get a uuid GET {{baseUrl}}/uuid Accept: application/json > {% test("status is ok", () => { client.assert(response.status === 200) }); %} ``` -------------------------------- ### HttpFileStore.initHttpFile method Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Resolves the absolute file name, computes rootDir, builds an HttpFile, resolves EnvironmentConfig, merges plugin hooks, and runs each with an HttpyacHooksApi. Plugin errors are logged and swallowed. ```typescript public async initHttpFile(fileName: models.PathLike, options: models.HttpFileStoreOptions): Promise ``` -------------------------------- ### HttpFileStore.parse method Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Initializes a fresh HttpFile via initHttpFile and runs parseHttpFile with the given text. ```typescript parse(fileName: models.PathLike, text: string, options: models.HttpFileStoreOptions): Promise ``` -------------------------------- ### Import httpyac.store namespace Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Import the store classes and instances from the 'httpyac' package. ```typescript import { HttpFileStore, HttpFile, HttpRegion, UserSessionStore, userSessionStore, pluginStore } from 'httpyac'; ``` -------------------------------- ### assertConfiguration(config, keys) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Asserts that the given configuration contains all required keys. Throws an error listing missing keys if any are absent. ```APIDOC ## assertConfiguration(config, keys) ### Description Asserts that the given configuration contains all required keys. Throws an error listing missing keys if any are absent. ### Method Function ### Signature ```ts export function assertConfiguration(config: models.OpenIdConfiguration, keys: string[]): void ``` ### Parameters - **config** (models.OpenIdConfiguration) - Required - The configuration object to validate. - **keys** (string[]) - Required - List of required configuration keys. ### Throws - **Error** - Throws `missing configuration: _, …` if any required key is missing. ``` -------------------------------- ### ProcessedHttpRegionInterceptor class Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-core-internals.md Pushes a ProcessedHttpRegion with start: performance.now() into context.processedHttpRegions at beforeLoop, updates end/duration/metaData/testResults at afterLoop/onError. Its response-logging interceptor fills request/response when the response is logged. Drives CLI JSON/JUnit output. ```typescript export class ProcessedHttpRegionInterceptor implements HookInterceptor<[models.ProcessorContext], boolean | void> { id = 'processedHttpRegion'; public getResponseLoggingInterceptor(): HookInterceptor<[models.HttpResponse, models.ProcessorContext], boolean | void>; } ``` -------------------------------- ### getOpenIdConfiguration(variablePrefix, variables) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Builds an OpenIdConfiguration object from variables using the given prefix. Reads each key from variables named `_` (case-insensitive) or nested `.`, defaulting to the `oauth2` prefix. ```APIDOC ## getOpenIdConfiguration(variablePrefix, variables) ### Description Builds an OpenIdConfiguration object from variables using the given prefix. Reads each key from variables named `_` (case-insensitive) or nested `.`, defaulting to the `oauth2` prefix. ### Method Function ### Signature ```ts export function getOpenIdConfiguration(variablePrefix: string | undefined, variables: models.Variables): models.OpenIdConfiguration ``` ### Parameters - **variablePrefix** (string | undefined) - Optional - The prefix used to read configuration keys from variables. - **variables** (models.Variables) - Required - The variables object containing configuration values. ### Returns - **models.OpenIdConfiguration** - The constructed OpenID configuration object. ### Defaults - `redirectUri` → `http://localhost:3000/callback` - `keepAlive` → `true` - `useAuthorizationHeader` → `true` - `variablePrefix` → `'oauth2'` ``` -------------------------------- ### createProgram Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Returns a commander program with version and description, and includes the `oauth2` and `send` commands. This is used to build the CLI program. ```APIDOC ## createProgram ### Description Returns a commander program with version and description, and includes the `oauth2` and `send` commands. This is used to build the CLI program. ### Method CLI ### Signature ```ts export async function createProgram(): Promise ``` ### Returns - Promise - A commander program with the following commands: - `oauth2 [options]` - Generate OAuth2 token - `send [options] ` - Send/execute http files (default command) ``` -------------------------------- ### OpenIdConfiguration helper functions Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Functions to build, compare, and validate OpenID configuration. `getOpenIdConfiguration` reads variables with the given prefix (default `oauth2`), `isOpenIdConfigurationEqual` compares two configs, and `assertConfiguration` throws `missing configuration: _, …` for missing keys. ```ts export function getOpenIdConfiguration(variablePrefix: string | undefined, variables: models.Variables): models.OpenIdConfiguration export function isOpenIdConfigurationEqual(config1, config2): boolean export function assertConfiguration(config: models.OpenIdConfiguration, keys: string[]): void // throws `missing configuration: _, …` ``` -------------------------------- ### HttpFileStore class constructor Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Constructor for HttpFileStore. Accepts optional plugin configuration hooks that are merged on top of the global pluginStore. ```typescript export class HttpFileStore implements models.HttpFileStore { constructor(private readonly plugins: Record = {}) {} } ``` -------------------------------- ### UserSessionStore class and userSessionStore singleton Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Defines the UserSessionStore class implementing models.SessionStore and exports a global singleton instance. Session IDs used internally include last_response, keep_streaming_, global_cache_, intellij_global_cache, input_, cookie sessions "_", OAuth2 cache keys, and stream connections from RequestClient.getSessionId(). ```TypeScript export class UserSessionStore implements SessionStore { readonly userSessions: Array = []; onSessionChanged(listener: () => void): Dispose; async reset(): Promise; // calls delete() on all, empties, notifies getUserSession(id: string): T | undefined; setUserSession(userSession: T): void; // replaces existing id, notifies removeUserSession(id: string): void; // calls delete() if present isUserSession(obj: unknown): obj is UserSession; } export const userSessionStore = new UserSessionStore(); ``` -------------------------------- ### Using the global log instance Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/io.md Shows how to use the global log instance. At default warn level, debug messages are suppressed; raising the level to trace increases verbosity. ```typescript import { log } from 'httpyac'; log.debug('parsing file'); // suppressed at default warn level log.options.level = LogLevel.trace; // raise verbosity ``` -------------------------------- ### execute Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Initializes IO providers, builds the program, and parses raw arguments. This function always terminates the process, so it is intended for CLI entry points, not embedding. ```APIDOC ## execute ### Description Initializes IO providers, builds the program, and parses raw arguments. This function always terminates the process, so it is intended for CLI entry points, not embedding. ### Method CLI ### Signature ```ts export async function execute(rawArgs: string[]): Promise ``` ### Parameters - **rawArgs** (string[]) - Required - The raw command-line arguments to parse. ### Returns - Promise - Resolves when the CLI finishes; the process is terminated in a finally block. ### Behavior - On error, sets `process.exitCode = 1` and rethrows. - Always calls `process.exit()` in a finally block. ``` -------------------------------- ### createEmptyProcessorContext Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/httpYacApi.md Creates a minimal ProcessorContext from a VariableProviderContext by resolving variables and initializing the options bag. ```APIDOC ## createEmptyProcessorContext ### Description Creates a minimal `ProcessorContext` from a `VariableProviderContext` by resolving `variables` (via `getVariables`) and initializing the per-execution `options` bag. ### Method `createEmptyProcessorContext` (async function) ### Signature ```ts export async function createEmptyProcessorContext( context: T ): Promise< T & { variables: models.Variables; options: Record; } > ``` ### Parameters - **context** (`T extends VariableProviderContext`) - Required - Must contain at least `httpFile`; may contain `activeEnvironment`, `config`, `variables`. ### Returns - **T & { variables: models.Variables; options: Record }** - The input context with `variables` and `options` filled in. ### Example ```ts const context = await createEmptyProcessorContext({ httpFile, activeEnvironment: ['dev'], }); ``` ``` -------------------------------- ### HttpFileStore.getAll method Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Returns all cached files that have finished parsing. ```typescript getAll(): Array ``` -------------------------------- ### Import httpyac.io providers Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/io.md Import the mutable singleton providers from the httpyac.io namespace. These default to inert stubs and are replaced by the CLI or embedding host. ```typescript import { fileProvider, httpClientProvider, javascriptProvider, log, Logger, userInteractionProvider, completionItemProvider } from 'httpyac'; ``` -------------------------------- ### Default config file names Source: https://github.com/anweber/httpyac/blob/main/_autodocs/configuration.md List of default configuration file names searched in order by getHttpyacConfig. First match wins, then package.json's httpyac key is merged. ```typescript export const defaultConfigFiles = [ '.httpyac.js', '.httpyac.cjs', '.httpyac.config.js', '.httpyac.config.cjs', 'httpyac.config.js', 'httpyac.config.cjs', '.httpyac.json', 'httpyac.config.json', ]; ``` -------------------------------- ### HttpFile class implementation Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Concrete implementation of the models.HttpFile interface. The constructor takes a mutable fileName and an optional rootDir used as the config base. ```TypeScript export class HttpFile implements models.HttpFile { constructor(public fileName: models.PathLike, public readonly rootDir?: models.PathLike) {} } ``` -------------------------------- ### parseUrlLineFactory / parseQueryLineFactory Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Parse URL part / query continuation lines. ```APIDOC ## parseUrlLineFactory / parseQueryLineFactory ### Description URL part / query continuation lines. ### Signature `(attachUrl) => ParseLineMethod` ### Parameters - **attachUrl** - Required - The function to attach the URL. ### Returns - **ParseLineMethod** - The line parser. ``` -------------------------------- ### IntellijHttpClient class stub Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-intellij.md Implements the HttpClient stub with methods test, assert, log, exit, and a global property. The constructor takes a ProcessorContext and initializes the global variables. ```typescript export class IntellijHttpClient implements HttpClient { global: Variables; constructor(private readonly context: models.ProcessorContext) {} } ``` -------------------------------- ### Logger constructor Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/io.md Creates a new Logger instance with configurable options for log level, output method, and parent logger forwarding. ```APIDOC ## Logger constructor ### Description Creates a new Logger instance with configurable options for log level, output method, and parent logger forwarding. ### Method Constructor ### Endpoint `new Logger(options, parentLogger?)` ### Parameters #### Constructor Options - **level** (`LogLevel | undefined`) - Optional - Minimum log level; messages below this level are dropped. - **logMethod** (`((level: LogLevel, ...params: unknown[]) => void) | undefined`) - Optional - Overrides the console target for every write. - **onlyFailedTests** (`boolean | undefined`) - Optional - Passed through; used by CLI filtering, not consulted in Logger itself. - **noTrace** (`boolean | undefined`) - Optional - When set, `trace()` writes to `console.debug` instead of `console.trace`. - **parentLogger** (`ConsoleLogHandler | undefined`) - Optional - Upstream logger to forward to. ### Request Example ```ts const logger = new Logger({ level: LogLevel.warn, noTrace: true }); ``` ### Response #### Success Response Returns a `Logger` instance implementing `ConsoleLogHandler`. #### Response Example ```ts const logger = new Logger({ level: LogLevel.warn, noTrace: true }); ``` ``` -------------------------------- ### knownMetaData Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Registry of documented # @ metadata. ```APIDOC ## knownMetaData ### Description Registry of documented `# @` metadata. ### Type `Array<{ name, description, completions? }>` ``` -------------------------------- ### isOpenIdConfigurationEqual(config1, config2) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Compares two OpenIdConfiguration objects for equality. Useful for detecting configuration changes. ```APIDOC ## isOpenIdConfigurationEqual(config1, config2) ### Description Compares two OpenIdConfiguration objects for equality. Useful for detecting configuration changes. ### Method Function ### Signature ```ts export function isOpenIdConfigurationEqual(config1, config2): boolean ``` ### Parameters - **config1** - Required - First configuration object to compare. - **config2** - Required - Second configuration object to compare. ### Returns - **boolean** - `true` if the configurations are equal, otherwise `false`. ``` -------------------------------- ### GrpcRequestClient class Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-protocols.md Extends AbstractRequestClient to handle gRPC requests. Reuses connections per URL, supports streaming, and throws 'Missing Protodefinitions' when protoDefinitions are absent. ```TypeScript export class GrpcRequestClient extends models.AbstractRequestClient { constructor(private readonly request: models.Request, private readonly context: models.ProtoProcessorContext) { super(); } } ``` -------------------------------- ### parseSubsequentLines Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Runs line parsers until one fails. ```APIDOC ## parseSubsequentLines ### Description Runs line parsers until one fails. ### Signature `(lineReader, parsers, context) => Promise` ### Parameters - **lineReader** - Required - The line reader. - **parsers** - Required - The parsers to run. - **context** - Required - The context. ### Returns - **Promise** - The result of parsing. ``` -------------------------------- ### log methods Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/io.md The global `log` instance provides methods for logging at various levels, with configurable verbosity and deferred output via `collectMessages()`. ```APIDOC ## log methods ### Description The global `log` instance provides methods for logging at various levels, with configurable verbosity and deferred output via `collectMessages()`. ### Methods - `info(...params: unknown[])` - Logs an info message. - `log(...params: unknown[])` - Logs a general message. - `trace(...params: unknown[])` - Logs a trace message (uses `console.debug` if `noTrace` is set). - `debug(...params: unknown[])` - Logs a debug message. - `error(...params: unknown[])` - Logs an error message. - `warn(...params: unknown[])` - Logs a warning message. - `logPriority(...msg: Array)` - Logs messages with priority. - `collectMessages()` - Starts collecting log messages as closures instead of writing immediately. - `flush()` - Executes all collected log messages. - `clear()` - Clears any collected messages. ### Usage Example ```ts import { log } from 'httpyac'; log.debug('parsing file'); // suppressed at default warn level log.options.level = LogLevel.trace; // raise verbosity ``` ``` -------------------------------- ### parseFileImport Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Parses < @file, < @encoding file, < file body imports. ```APIDOC ## parseFileImport ### Description Parses `< @file`, `< @encoding file`, `< file` body imports. ### Signature `(text) => RequestBodyImport | undefined` ### Parameters - **text** - Required - The text to parse. ### Returns - **RequestBodyImport | undefined** - The parsed import or undefined. ``` -------------------------------- ### Script globals (initIntellijVariables) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-intellij.md Defines the global variables available in IntelliJ plugin scripts, including client, crypto, $random, $env, Window, request, and response. The request object is conditionally created based on whether the region has a response. ```typescript { client: new IntellijHttpClient(context), crypto: new IntellijCryptoSupport(), $random: new IntellijRandom(), $env: process.env, Window: new IntellijWindow(), request: context.request ? (region has response ? new IntellijHttpClientRequest(context) : new IntellijPreRequestHttpClientRequest(context)) : undefined, response: /* set for response scripts: IntellijHttpResponse or IntellijTextStreamResponse */ } ``` -------------------------------- ### OAuth2Regex Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Regular expression for OAuth2/openid header matching. ```APIDOC ## OAuth2Regex ### Description OAuth2/openid header matcher. ### Value Regular expression (not specified). ``` -------------------------------- ### CLI executable entry point (bin/httpyac.js) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Entry point for the httpyac CLI. Requires the compiled CLI module and calls execute with process arguments. ```javascript #!/usr/bin/env node const { cli } = require('../dist/index'); cli.execute(process.argv); ``` -------------------------------- ### Import httpyac utils namespace Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Import the utils namespace from the httpyac package root. All helper functions are named exports, e.g. replaceVariables, parseHandlebarsString, testFactory. ```typescript import * as utils from 'httpyac'; // e.g. utils.replaceVariables, utils.parseHandlebarsString, utils.testFactory ``` -------------------------------- ### gotHttpClient function signature Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-http.md Direct got execution used by httpClientProvider.exchange for OAuth2 token requests, tests, and CLI. Resolves the request with getClientOptions, awaits got(request.url, options), converts with toHttpResponse. Returns false on got.CancelError; other errors rethrow. ```TypeScript export async function gotHttpClient( request: models.HttpClientRequest, context: models.HttpClientContext ): Promise ``` -------------------------------- ### Import parseIntellijScript and related types from 'httpyac' Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-intellij.md Import the IntelliJ compatibility module's public API. Use this to access parseIntellijScript, IntellijAction, and the script globals types. ```typescript import { parseIntellijScript, IntellijAction, IntellijScriptData, IntellijHttpClient, IntellijHttpClientRequest, IntellijPreRequestHttpClientRequest, IntellijHttpResponse, IntellijTextStreamResponse, IntellijVariables, IntellijRandom, IntellijCryptoSupport, IntellijWindow, } from 'httpyac'; ``` -------------------------------- ### Create empty processor context Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/httpYacApi.md Creates a processor context with variables and options filled in, given an httpFile and optional activeEnvironment. ```ts const context = await createEmptyProcessorContext({ httpFile, activeEnvironment: ['dev'], }); ``` -------------------------------- ### parseRequestHeaderFactory Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Parses Key: value lines, with arrays for duplicate keys. ```APIDOC ## parseRequestHeaderFactory ### Description Parses `Key: value` lines (arrays for duplicates). ### Signature `(headers) => ParseLineMethod` ### Parameters - **headers** - Required - The headers object to populate. ### Returns - **ParseLineMethod** - The line parser. ``` -------------------------------- ### createEmptyProcessorContext signature Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/httpYacApi.md Creates a minimal ProcessorContext from a VariableProviderContext by resolving variables and initializing the per-execution options bag. ```ts export async function createEmptyProcessorContext( context: T ): Promise< T & { variables: models.Variables; options: Record; } > ``` -------------------------------- ### pluginStore global plugin registry Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Declares the global plugin registry object that maps plugin names to registration functions. It is populated by src/registerPlugins.ts on package import. ```TypeScript export const pluginStore: Record = {}; ``` -------------------------------- ### Package root exports from src/index.ts Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/index.md Shows the public API surface of the httpyac package, re-exporting modules from the root. This is the entry point for all public types and functions. ```typescript export * as cli from './cli'; export * from './httpYacApi'; export * as io from './io'; export * from './models'; export * as store from './store'; export * as utils from './utils'; ``` -------------------------------- ### GrpcUrlRegex and getSerivceData Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-protocols.md Parses gRPC request URLs and resolves service data from proto definitions. Throws when the service does not exist. ```TypeScript export const GrpcUrlRegex = /^\s*((?grpc|https?):\/\/)?(?[^/]+?)(\/(?.+))?\/(?[^/]+?)\/(?[^/]+?)$/iu; export function getSerivceData(url: string, protoDefinitions: Record): ServiceData ``` -------------------------------- ### HttpFileStore cache mutation helpers Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Cache mutation helpers. remove returns whether an entry was deleted. ```typescript remove(fileName: models.PathLike): boolean rename(oldFileName: models.PathLike, newFileName: models.PathLike): void clear(): void ``` -------------------------------- ### TokenExchangeFlow.perform(config, openIdInformation, context) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Performs RFC 8693 token exchange. Posts `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with subject and requested token types. ```APIDOC ## TokenExchangeFlow.perform(config, openIdInformation, context) ### Description Performs RFC 8693 token exchange. Posts `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` with subject and requested token types. ### Method Static Function ### Signature ```ts static perform(config, openIdInformation, context) ``` ### Parameters - **config** - Required - The configuration for the token exchange. - **openIdInformation** - Required - The current OpenID information. - **context** - Required - The context for the flow. ### Behavior - Uses `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` - Sets `subject_token_type`/`requested_token_type` to access-token - Sets `subject_issuer` from config or decoded JWT `iss` ``` -------------------------------- ### parseRequestLineFactory Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Builds a request-line parser used by all protocols. Creates the region's request, parses headers/comments/query lines, sets contentType, and registers hooks. ```APIDOC ## parseRequestLineFactory ### Description Builds a request-line parser (used by all protocols). Creates the region's request, parses headers/comments/query lines, sets `contentType` from the `content-type` header, and registers `hooks.execute.addHook(protocol.toLowerCase(), executeRequestClientFactory(requestClientFactory, sessionStore))`. ### Signature `(requestContext: RequestParserContext) => ParseLineMethod` ### Parameters - **requestContext** (RequestParserContext) - Required - The request parser context. ### RequestParserContext - **protocol** (string) - Required - The protocol. - **method** (string) - Optional - The HTTP method. - **requestClientFactory** ((request: models.Request, context: models.ProcessorContext) => models.RequestClient) - Required - Factory to create a request client. - **modifyRequest** ((request: models.Request) => void) - Optional - Function to modify the request. - **methodRegex** (RegExp) - Required - Regex for method parsing. - **protocolRegex** (RegExp) - Optional - Regex for protocol parsing. - **sessionStore** (models.SessionStore) - Required - The session store. ### Returns - **ParseLineMethod** - The line parser. ``` -------------------------------- ### HandlebarsSingleLine Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Regular expression for single-line Handlebars expressions. ```APIDOC ## HandlebarsSingleLine ### Description Regular expression for single-line Handlebars expressions. ### Value `/\{{2}\s*(.+?)\s*\}{2}/u` ``` -------------------------------- ### pluginStore registration assignments Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Assigns each plugin's registration function to the corresponding key in pluginStore. This is executed on package import by src/registerPlugins.ts. ```TypeScript pluginStore.core = plugins.registerCorePlugins; pluginStore.dotenv = plugins.registerDotenvPlugin; pluginStore.eventSource = plugins.registerEventSourcePlugin; pluginStore.graphql = plugins.registerGraphQL; pluginStore.grpc = plugins.registerGrpcPlugin; pluginStore.http = plugins.registerHttpPlugin; pluginStore.intellij = plugins.registerIntellijPlugin; pluginStore.injection = plugins.registerInjectionPlugin; pluginStore.javascript = plugins.registerJavascriptPlugin; pluginStore.mqtt = plugins.registerMqttPlugin; pluginStore.oauth2 = plugins.registerOAuth2Plugin; pluginStore.rabbitMQ = plugins.registerAmqpPlugin; pluginStore.assert = plugins.registerAssertPlugin; pluginStore.websocket = plugins.registerWebsocketPlugin; pluginStore.xml = plugins.registerXmlPuglin; ``` -------------------------------- ### Import hooks and RequestClient classes from 'httpyac' Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/models-hooks.md Imports the hook types and AbstractRequestClient from the httpyac package root. Required before using any hook or client classes. ```typescript import { ParseHook, ParseMetaDataHook, ProvideAssertValue, ParseEndRegionHook, ProvideVariablesHook, ProvideEnvironmentsHook, ReplaceVariableHook, OnRequestHook, OnResponseHook, OnStreaming, ResponseLoggingHook, ExecuteHook, HttpFileHooks, RequestClientHooks, AbstractRequestClient, } from 'httpyac'; ``` -------------------------------- ### Batch usage import from httpyac/cli Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Import the CLI functions for programmatic batch usage. ```typescript import { execute, createProgram, sendCommand, oauth2Command } from 'httpyac/cli'; ``` -------------------------------- ### parseIntellijScript Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-intellij.md Parses IntelliJ HTTP Client-style pre-request and response scripts from the HTTP region. Supports external script files, single-line inline scripts, and multi-line inline scripts. ```APIDOC ## parseIntellijScript ### Description Parses IntelliJ HTTP Client-style pre-request and response scripts from the HTTP region. Supports external script files, single-line inline scripts, and multi-line inline scripts. ### Method async function ### Endpoint parseIntellijScript(getLineReader, { httpRegion }) ### Parameters #### Function Parameters - **getLineReader** (models.getHttpLineGenerator) - Required - Line reader generator for the HTTP region. - **httpRegion** (models.ParserContext) - Required - Parser context containing the HTTP region. ### Returns - **Promise** - Parsing result with start/end lines, offsets, script data, and whether it is a pre-request script. ### Script Forms - `< file.js` / `> file.js` - External script file (loaded at execution via `fileProvider.readFile`). - `< {% script %}` / `> {% script %}` - Single-line inline script. - `< {%` … `%}` / `> {%` … `%}` - Multi-line inline script. ### Behavior - `<` = pre-request (executes in `onRequest`, before variable replacement). - `>` = response/streaming handler (registers `onStreaming` + `onResponse`). ``` -------------------------------- ### parseHandlebarsSymbols Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Produces variable symbols for a line. ```APIDOC ## parseHandlebarsSymbols ### Description Produces variable symbols for a line. ### Signature `(line, startLine, offset = 0) => Array` ### Parameters - **line** - Required - The line to parse. - **startLine** - Required - The starting line number. - **offset** (number) - Optional - The offset (default 0). ### Returns - **Array** - The parsed symbols. ``` -------------------------------- ### oauth2Command Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Builds the `oauth2` command for the CLI program. This command generates an OAuth2 token. ```APIDOC ## oauth2Command ### Description Builds the `oauth2` command for the CLI program. This command generates an OAuth2 token. ### Method CLI ### Signature ```ts export function oauth2Command(): Command ``` ### Returns - Command - A commander command with the following usage: - `oauth2 [options]` - Generate OAuth2 token ``` -------------------------------- ### parseInlineResponse Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Parses inline HTTP/1.1 200-style responses. ```APIDOC ## parseInlineResponse ### Description Parses inline `HTTP/1.1 200`-style responses. ### Signature `(getLineReader, context, regex) => Promise` ### Parameters - **getLineReader** - Required - The line reader getter. - **context** - Required - The context. - **regex** (RegExp) - Required - The regex to match the response. ### Returns - **Promise** - The parse result. ``` -------------------------------- ### HttpFileStore.get method Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/store.md Returns the cached HttpFile for the given path, if any. ```typescript get(fileName: models.PathLike): models.HttpFile | undefined ``` -------------------------------- ### JUnit output transformation (src/cli/send/junitUtils.ts) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Transforms the JSON output into a JUnit XML document (Jenkins junit.xsd flavor) using `@xmldom/xmldom` and `xmldom-format`. ```TypeScript export function transformToJunit(output: SendJsonOutput): string ``` -------------------------------- ### convertCliOptionsToContext function Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Builds the send context from CLI options, mapping environment, repeat mode, log level, timeout, HTTPS settings, and variables. Variables are parsed by splitting on the first '='. ```typescript export function convertCliOptionsToContext(cliOptions: SendOptions) { const context: Omit = { activeEnvironment: cliOptions.env, repeat: cliOptions.repeat ? { count: cliOptions.repeat, type: cliOptions.repeatMode === 'sequential' ? models.RepeatOrder.sequential : models.RepeatOrder.parallel } : undefined, config: { log: { level: getLogLevel(cliOptions) }, request: { timeout: cliOptions.timeout, https: cliOptions.insecure ? { rejectUnauthorized: false } : undefined } }, variables: cliOptions.var ? Object.fromEntries(cliOptions.var.map(obj => { const split = obj.split('='); return [split[0], split.slice(1).join('=')]; })) : undefined, }; return context; } ``` -------------------------------- ### LogResponseInterceptor class Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-core-internals.md After the loop, clones the region response, tags it (httpRegion, mainResponse/refResponse), removes it from the region, and calls utils.logResponse(clone, context). Runs responseLogging hooks and then context.logResponse unless # @noLog. ```typescript export class LogResponseInterceptor implements HookInterceptor<[models.ProcessorContext], boolean | void> { id = 'logResponse'; } ``` -------------------------------- ### getEnvironments Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/httpYacApi.md Resolves config and triggers the provideEnvironments hook; flattens and deduplicates all returned environment name arrays, sorted ascending. ```APIDOC ## getEnvironments ### Description Resolves config and triggers the `provideEnvironments` hook; flattens and deduplicates all returned environment name arrays, sorted ascending. Returns `[]` when the hook returns `HookCancel` or no environments. ### Method `getEnvironments` (async function) ### Signature ```ts export async function getEnvironments(context: models.VariableProviderContext): Promise> ``` ### Parameters - **context** (`VariableProviderContext`) - Required - Config resolution source. ### Returns - **Array** - Sorted, deduplicated environment names, or `[]` if none. ``` -------------------------------- ### sendCommand Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/cli.md Builds the `send` command for the CLI program. This command sends or executes http files. ```APIDOC ## sendCommand ### Description Builds the `send` command for the CLI program. This command sends or executes http files. ### Method CLI ### Signature ```ts export function sendCommand(): Command ``` ### Returns - Command - A commander command with the following usage: - `send [options] ` - Send/execute http files ``` -------------------------------- ### javascriptProvider implementation (src/io/javascriptProvider.ts) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/io.md Default implementation of models.JavascriptProvider. evalExpression returns the raw context variable for {{ expr }}. The require registry is shared; protocol plugins register ws, mqtt, @cloudamqp/amqp-client, eventsource, xpath, @xmldom/xmldom, @grpc/grpc-js, plus httpyac, dayjs, open, uuid via the javascript plugin. runScript and loadModule are overridden by the javascript plugin (moduleUtils.runScript and moduleUtils.loadModule). ```TypeScript export const javascriptProvider: models.JavascriptProvider = { require: {}, evalExpression: async function evalExpression(expression, context) { return context.variables[expression]; }, }; ``` -------------------------------- ### getOAuth2Response Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Resolves an OpenIdFlow by name, builds OpenIdConfiguration from context variables, performs the flow (or reuses/refreshes a session), optionally wraps with token exchange, and stores the result in the user session store. ```APIDOC ## getOAuth2Response ### Description Resolves an `OpenIdFlow` by name, builds `OpenIdConfiguration` from context variables (prefix-aware, case-insensitive), performs the flow (or reuses/refreshes a session), optionally wraps with token exchange, and stores the result in the user session store. ### Method Function ### Signature ```ts export async function getOAuth2Response( flow: string, prefix: string | undefined, context: models.OpenIdContext, tokenExchangePrefix?: string ): Promise ``` ### Parameters - **flow** (string) - Required - The name of the OpenIdFlow to resolve. - **prefix** (string | undefined) - Required - Variable prefix for configuration. - **context** (models.OpenIdContext) - Required - `{ progress?, logResponse?, variables }`; may be a full `ProcessorContext`. - **tokenExchangePrefix** (string | undefined) - Optional - Prefix for token exchange configuration. ### Behavior 1. Reuses the session for the flow's cache key and refreshes it if expired (`refreshTokenFlow.perform`). 2. Otherwise performs the flow and, when `tokenExchangePrefix` is given, wraps the result with `TokenExchangeFlow.perform(tokenExchangeConfig, token, context)`. 3. Stores the result as a `userSessionStore` session (`type: 'OAuth2'`, properties of `OpenIdInformation`), sets the `oauth2Session` variable, and schedules `keepAlive` refresh when `config.keepAlive` and a refresh token exist. ### Return Value - `Promise` - The OAuth2 response information, or `undefined` if not available. ``` -------------------------------- ### implicitFlow Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Flow for implicit and hybrid grants. Supports `implicit` and `hybrid` flow types. Browser flow returning access token or exchanging code. ```APIDOC ## implicitFlow ### Description Flow for implicit and hybrid grants. Supports `implicit` and `hybrid` flow types. Browser flow returning access token or exchanging code. ### Supported Flows - `implicit` - `hybrid` ### Cache Key `implicit_…` ### Required Configuration - tokenEndpoint - authorizationEndpoint - clientId ### Behavior - Browser flow returning `access_token` (fragment) or exchanging `code` - Supports `responseType`/`responseMode` ``` -------------------------------- ### replaceFilePath Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Variable-replaces a path, resolves it absolute against the file directory, and warns and returns undefined on failure. The action is called with the resolved path. ```APIDOC ## replaceFilePath ### Description Variable-replaces a path, resolves it absolute against the file dir; warns and returns `undefined` on failure. ### Signature `(fileName: string, context: ProcessorContext, action: (path: PathLike) => Promise) => Promise` ### Parameters - **fileName** (string) - Required - The file name to replace variables in. - **context** (ProcessorContext) - Required - The processor context. - **action** ((path: PathLike) => Promise) - Required - The action to perform with the resolved path. ### Returns - **Promise** - The result of the action, or `undefined` on failure. ``` -------------------------------- ### ConfigRequest interface Source: https://github.com/anweber/httpyac/blob/main/_autodocs/configuration.md Merged into got options and read by protocol clients. timeout/rejectUnauthorized/followRedirects also used by WebSocket/MQTT clients, timeout by gRPC and CLI. ```typescript export interface ConfigRequest { timeout?: number; followRedirects?: boolean; rejectUnauthorized?: boolean; [key: string]: unknown; } ``` -------------------------------- ### TokenExchangeFlow.getCacheKey(config) Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/plugins-oauth2.md Generates a cache key for token exchange flow. ```APIDOC ## TokenExchangeFlow.getCacheKey(config) ### Description Generates a cache key for token exchange flow. ### Method Static Function ### Signature ```ts static getCacheKey(config) ``` ### Parameters - **config** - Required - The configuration for the token exchange. ### Returns - **string** - The cache key. ``` -------------------------------- ### ClientCertificateOptions interface Source: https://github.com/anweber/httpyac/blob/main/_autodocs/configuration.md Per-host client certificate options. Applied to HTTPS requests; paths resolved relative to rootDir at config load. ```typescript export interface ClientCertificateOptions { cert?: PathLike; key?: PathLike; pfx?: PathLike; passphrase?: string; } ``` -------------------------------- ### EnvironmentConfig interface Source: https://github.com/anweber/httpyac/blob/main/_autodocs/configuration.md Defines the main configuration object for httpyac. Passed to send()/HttpFileStore, merged with project config files, environment variables, and request-file metadata. Defaults applied by getEnvironmentConfig. ```typescript export interface EnvironmentConfig { cookieJarEnabled?: | boolean | { allowSpecialUseDomain?: boolean | undefined; looseMode?: boolean | undefined; rejectPublicSuffixes?: boolean | undefined; prefixSecurity?: string | undefined; }; log?: { level?: LogLevel; supportAnsiColors?: boolean; options?: RequestLoggerFactoryOptions; }; request?: ConfigRequest; proxy?: string; proxyExcludeList?: Array; requestPrettyPrintBodyMaxSize?: number; requestBodyInjectVariablesExtensions?: Array; clientCertificates?: Record; defaultHeaders?: Record; environments?: Record; envDirName?: string; useRegionScopedVariables?: boolean; configureHooks?: ConfigureHooks; plugins?: Record; } ``` -------------------------------- ### parseComments Source: https://github.com/anweber/httpyac/blob/main/_autodocs/api-reference/utils.md Parses # and // comments and @meta keys; triggers parseMetaData; updates knownMetaData completions. ```APIDOC ## parseComments ### Description Parses `#`/`//` comments and `@meta` keys; triggers `parseMetaData`; updates `knownMetaData` completions. ### Signature `(httpLine, context, metaRegex?) => Promise` ### Parameters - **httpLine** - Required - The HTTP line. - **context** - Required - The context. - **metaRegex** (RegExp) - Optional - The regex for metadata. ### Returns - **Promise** - The parse result or false. ```