API Reference
Complete reference for @powerduck/x-to-openapi v0.2.2. Every public export from the package entry point is documented with its exact signature and defaults.
Zero-config helpers
curlToOpenApi
One-shot conversion: registers a CurlAdapter and calls convert on it.
function curlToOpenApi(
input: string | readonly string[],
options?: ConvertOptions,
): Promise<ConvertResult>;
| Parameter | Type | Description |
|---|---|---|
input | string | readonly string[] | A curl command, an array of commands, or browser "Copy all as cURL" output (multi-command text is split automatically). |
options | ConvertOptions | Optional conversion settings. |
Returns: ConvertResult.
import { curlToOpenApi } from "@powerduck/x-to-openapi";
const result = await curlToOpenApi(
"curl -X POST https://api.example.com/users -H 'Content-Type: application/json' --data '{\"name\":\"Ada\"}'",
);
postmanToOpenApi
One-shot conversion: registers a PostmanAdapter and converts. Accepts a parsed collection object or a JSON string. Test scripts are preserved as x-postman-scripts.
function postmanToOpenApi(
input: unknown,
options?: ConvertOptions,
): Promise<ConvertResult>;
| Parameter | Type | Description |
|---|---|---|
input | unknown | A Postman Collection v2.0/v2.1.0 object, or a JSON string of one. |
options | ConvertOptions | Optional conversion settings. |
Returns: ConvertResult.
Core framework
XToOpenApi
The converter class. Holds an AdapterRegistry and runs the parse → build → validate pipeline.
class XToOpenApi {
register<I>(adapter: SourceAdapter<I>): this;
adapters(): string[];
convert(
source: string,
input: unknown,
options?: ConvertOptions,
): Promise<ConvertResult>;
}
register(adapter)
Registers an adapter. Returns this for chaining. Validates the adapter id against /^[a-z][a-z0-9-]*$/, requires a parse() method, and rejects duplicate ids.
adapters()
Returns the registered adapter ids as string[].
convert(source, input, options?)
The single entry point.
| Parameter | Type | Description |
|---|---|---|
source | string | An adapter id ("curl", "postman", …) or "auto" to select via canHandle(). |
input | unknown | The source data (shape depends on the adapter). |
options | ConvertOptions | Optional conversion settings. |
Behavior:
- Resolves options against
DEFAULT_OPTIONSand validates them. - Rejects inputs larger than 10 MB with a
ConversionError. - Selects the adapter (explicit id, or
"auto"detection). - Parses the input into
NormalizedRequest[](parse failures become diagnostics). - Builds the OpenAPI 3.2 document via
buildOpenApi32. - If
validateistrue, validates viavalidateOpenApi32and folds result diagnostics in. - Returns a
ConvertResult.
import { XToOpenApi, CurlAdapter } from "@powerduck/x-to-openapi";
const converter = new XToOpenApi().register(new CurlAdapter());
const result = await converter.convert("curl", curlText, { title: "My API" });
DEFAULT_OPTIONS
The resolved default every ConvertOptions is merged onto. Exported as a ResolvedConvertOptions.
const DEFAULT_OPTIONS: ResolvedConvertOptions = {
openapiVersion: "3.2.0",
title: "Generated API",
version: "1.0.0",
description: "",
inferPathParameters: true,
pathParameterMinSamples: 2,
inferSecurity: true,
includeCommonHeaders: false,
includeCookies: false,
includeExamples: false,
useServerBasePath: false,
validate: true,
strict: false,
};
AdapterRegistry
Holds registered adapters by id.
class AdapterRegistry {
register<I>(adapter: SourceAdapter<I>): this;
has(id: string): boolean;
get(id: string): SourceAdapter<unknown>;
detect(input: unknown): SourceAdapter<unknown> | undefined;
ids(): string[];
}
| Method | Description |
|---|---|
register(adapter) | Validates the id (/^[a-z][a-z0-9-]*$/), checks for parse(), and rejects duplicates. Returns this. |
has(id) | Membership test. |
get(id) | Returns the adapter, or throws listing the registered ids. |
detect(input) | Returns the first adapter whose canHandle() accepts the input. Throwing predicates are caught and skipped. |
ids() | Lists registered ids. |
ConversionError
Thrown in strict mode (or on oversized input). Carries the diagnostics that caused the failure.
class ConversionError extends Error {
readonly diagnostics: readonly Diagnostic[];
constructor(
message: string,
diagnostics: readonly Diagnostic[],
options?: { cause?: unknown },
);
}
DiagnosticBag
Internal collector used by XToOpenApi.convert. Dedupes diagnostics and throws a ConversionError on error-severity entries when strict is true.
class DiagnosticBag {
constructor(strict?: boolean); // default false
report(diagnostic: Diagnostic): void;
get items(): Diagnostic[];
hasErrors(): boolean;
}
Adapters
CurlAdapter
Converts curl commands (single, batch, or browser export) into NormalizedRequest[]. Wraps curlconverter and normalizes its output.
class CurlAdapter implements SourceAdapter<string | readonly string[]> {
readonly id = "curl";
canHandle(input: unknown): boolean;
parse(
input: string | readonly string[],
context: AdapterContext,
): Promise<NormalizedRequest[]>;
}
canHandleaccepts a string (or first array element) that begins with an optional shell prompt ($,#,>) followed bycurlorcurl.exe.parsesplits multi-command input viasplitCurlCommands, skips non-HTTP(S) URLs, drops HTTP/2 pseudo-headers, parses bodies and cookies, and infers auth.
The adapter module also exposes
resolveBackend,availableExports, andresetBackendfor its internal curlconverter integration; these are not re-exported from the package entry point.
splitCurlCommands
Splits browser "Copy all as cURL" output into individual commands. Handles single/double quotes, backslash and caret (^) continuations, CRLF, shell prompts ($, #, >, PS C:\>), and curl.exe.
function splitCurlCommands(input: string): string[];
import { splitCurlCommands } from "@powerduck/x-to-openapi";
const commands = splitCurlCommands(`
$ curl https://api.example.com/users
> curl https://api.example.com/users/123
`);
// ["curl https://api.example.com/users", "curl https://api.example.com/users/123"]
PostmanAdapter
Converts Postman Collections v2.0/v2.1.0 into NormalizedRequest[]. Walks nested folders, resolves auth with item > folder > collection inheritance, maps body modes, and preserves test scripts.
class PostmanAdapter implements SourceAdapter<PostmanCollection | string> {
readonly id = "postman";
canHandle(input: unknown): boolean;
parse(
input: PostmanCollection | string,
context: AdapterContext,
): Promise<NormalizedRequest[]>;
}
canHandleaccepts an object (or parsed JSON string) with aninfoobject and anitemarray. The v2.1.0 and v2.0 schema URLs are both accepted, as are shape-valid collections that omit the schema URL.- Test/prerequest events are emitted on the operation as
x-postman-scripts.
PostmanTypes
A namespace holding every Postman collection type used by the adapter:
import { PostmanTypes } from "@powerduck/x-to-openapi";
PostmanTypes.PostmanCollection;
PostmanTypes.PostmanItem;
PostmanTypes.PostmanFolder;
PostmanTypes.PostmanRequestItem;
PostmanTypes.PostmanRequest;
PostmanTypes.PostmanBody;
PostmanTypes.PostmanBodyMode;
PostmanTypes.PostmanAuth;
PostmanTypes.PostmanEvent;
PostmanTypes.PostmanScript;
// ... plus isFolder and isRequestItem type guards
Key members: PostmanCollection, PostmanInfo, PostmanVersion, PostmanItem, PostmanFolder, PostmanRequestItem, PostmanRequest, PostmanHeader, PostmanUrl, PostmanQueryParam, PostmanBodyMode, PostmanBody, PostmanUrlEncodedParam, PostmanFormDataParam, PostmanFileParam, PostmanGraphQLBody, PostmanAuthType, PostmanAuth, PostmanAuthParam, PostmanEvent, PostmanScript, PostmanVariable, PostmanDescription, isFolder, isRequestItem.
OpenAPI building blocks
buildOpenApi32
Low-level builder. Assembles an OpenAPI 3.2 document from an array of already-normalized requests. You normally call it indirectly through XToOpenApi.convert.
function buildOpenApi32(
requests: readonly NormalizedRequest[],
options: ResolvedConvertOptions,
report: (diagnostic: Diagnostic) => void,
): OpenApiDocument;
It groups operations by path + method, collects query/header/cookie/path parameters, merges body schemas, emits securitySchemes, routes non-standard methods to additionalOperations, and assigns operationId/tags.
buildPathTemplates
Groups same-shaped requests and templates segments that vary across at least minSamples samples and look like identifiers in every sample.
function buildPathTemplates(
requests: readonly NormalizedRequest[],
minSamples: number,
enabled: boolean,
): Map<number, PathTemplate>;
Returns a map keyed by sourceIndex. Each PathTemplate has:
interface PathTemplate {
readonly path: string; // e.g. "/users/{userId}"
readonly parameters: ReadonlyMap<number, string>; // segment index → name
}
When enabled is false, every request gets a static template equal to its raw pathname.
looksLikeIdentifier
Single source of truth for what counts as a templatable segment.
function looksLikeIdentifier(segment: string): boolean;
Returns true when the segment is pure numeric, a UUID, a ULID, or a hex string of at least 8 characters.