import "dotenv/config"; //#region src/ir/sdk-behavior.d.ts /** * SDK Behavior IR — language-agnostic runtime policies for generated SDKs. * * These types capture the "what" of SDK behavior (retry, telemetry, errors, etc.) * while emitters provide the "how" (language-specific mechanism). * * Emitters access these via `ctx.spec.sdk` — always populated, never undefined. */ /** Retry policy — when and how to retry failed requests. */ interface RetryPolicy { /** HTTP status codes that trigger a retry. */ retryableStatusCodes: number[]; /** Maximum number of retry attempts (0 = no retries). */ maxRetries: number; /** Whether to retry on connection errors (DNS failure, TCP reset). */ retryOnConnectionError: boolean; /** Whether to retry on timeout errors. */ retryOnTimeout: boolean; /** Backoff strategy between retries. */ backoff: BackoffStrategy; } /** Exponential backoff configuration. * * Formula: `delay = min(initialDelay * multiplier^attempt, maxDelay)` * With jitter: `delay += delay * jitterFactor * random(0, 1)` */ interface BackoffStrategy { /** Initial delay in seconds before the first retry. */ initialDelay: number; /** Multiplier applied to the delay on each subsequent retry. */ multiplier: number; /** Maximum delay in seconds (cap). */ maxDelay: number; /** Jitter factor (0..1). 0.5 means up to 50% random jitter added. */ jitterFactor: number; } /** Error mapping — status codes to named exception kinds. */ interface ErrorPolicy { /** Map from HTTP status code to a logical error kind name (e.g. 400 → 'BadRequest'). * Emitters append language-specific suffixes (e.g. 'BadRequestException'). */ statusCodeMap: Record; /** Catch-all error kind for 5xx status codes not in the map. */ serverErrorKind: string; /** Catch-all error kind for unrecognized status codes. */ clientErrorKind: string; /** URL template for error documentation. Use {code} as placeholder for the API error code. */ errorDocUrlTemplate?: string; } /** Telemetry — what request metrics to track and send. */ interface TelemetryPolicy { /** Whether telemetry is enabled by default. Users can opt out via constructor param. */ enabledByDefault: boolean; /** Header name for client telemetry data (previous request's ID + latency). */ headerName: string; /** Response header name for the request ID. */ requestIdHeader: string; } /** Pagination behavior defaults. */ interface PaginationPolicy { /** Delay in milliseconds between pages during auto-pagination. 0 = no delay. */ autoPageDelayMs: number; } /** Idempotency auto-generation rules. */ interface IdempotencyPolicy { /** Header name for the idempotency key. */ headerName: string; /** Whether to auto-generate a UUID v4 idempotency key for POST requests when retries > 0. */ autoGenerateForPost: boolean; } /** Logging contract — what to log at which level. */ interface LoggingPolicy { /** Whether structured logging hooks are generated. */ enabled: boolean; /** Log events that the generated client emits. */ events: LogEvent[]; } /** A discrete loggable event in the request lifecycle. */ type LogEvent = 'request.start' | 'request.success' | 'request.retry' | 'request.rate_limited' | 'request.error' | 'request.connection_error'; /** User-Agent construction rules. */ interface UserAgentPolicy { /** Template for the SDK identifier string. * Placeholders: {name} = spec name, {lang} = emitter language, {version} = SDK version. * Each emitter interpolates with its own language string and casing conventions. * Example: '{name} {lang}/{version}' → 'Acme PHP/4.32.0' */ sdkIdentifierTemplate: string; /** Whether to append the runtime/language version (e.g. PHP 8.2, Python 3.12). */ includeRuntimeVersion: boolean; /** Whether to allow app info enrichment via setAppInfo(name, version, url). */ allowAppInfo: boolean; /** AI agent environment variable detection entries. */ aiAgentEnvVars: AiAgentEnvVar[]; } /** Maps an environment variable to an AI agent slug for User-Agent enrichment. */ interface AiAgentEnvVar { /** Environment variable to check (e.g. 'CLAUDE_CODE'). */ envVar: string; /** Agent name to append to User-Agent (e.g. 'ClaudeCode'). */ agentName: string; } /** Guards that validate request params before sending. */ interface RequestGuardPolicy { /** Keys that should be in RequestOptions, not in params. * If detected in the body or query params, the SDK throws an error. */ optionKeys: string[]; } /** Timeout configuration. */ interface TimeoutPolicy { /** Default HTTP request timeout in seconds. */ defaultTimeoutSeconds: number; /** Environment variable name to override the timeout (e.g. 'SDK_REQUEST_TIMEOUT'). */ timeoutEnvVar?: string; } /** Language-agnostic runtime policies for generated SDKs. * Attached to `ApiSpec.sdk` and consumed by emitters via `ctx.spec.sdk`. */ interface SdkBehavior { retry: RetryPolicy; errors: ErrorPolicy; telemetry: TelemetryPolicy; pagination: PaginationPolicy; idempotency: IdempotencyPolicy; logging: LoggingPolicy; userAgent: UserAgentPolicy; requestGuard: RequestGuardPolicy; timeout: TimeoutPolicy; } //#endregion //#region src/ir/types.d.ts /** * Authentication scheme extracted from OpenAPI `components.securitySchemes`. * * `schemeName` is the key under `components.securitySchemes`, spelled exactly as * in the document. The requirements under `ApiSpec.security` and * `Operation.security` refer to the same key, so emitters join a requirement to * its scheme on that field. `description` is present only when the document * declares one. */ type AuthScheme = { description?: string; schemeName: string; } & ({ kind: 'basic'; } | { kind: 'bearer'; } | { kind: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string; } | { kind: 'oauth2'; flows: Record; }); /** * A variable in a templated server URL (`https://{region}.api.example.com`), * from the server's `variables` map. */ interface ServerVariable { /** Substituted for the placeholder when the caller picks no value; OpenAPI requires one. */ default: string; /** The values the variable may take. Present only when the document declares a non-empty list. */ enum?: string[]; description?: string; } /** A server entry from the OpenAPI servers array */ interface ServerEntry { /** * As written in the document, placeholders included. `ApiSpec.baseUrl` is * the first server's URL with its variables' defaults filled in; resolve any * other entry the same way with `resolveServerUrl` from `ir/server-url.ts`. */ url: string; description?: string; /** The template's variables, keyed by placeholder name. Present only when the document declares them. */ variables?: Record; } /** * A link to documentation outside the OpenAPI document (an External * Documentation Object). Present on a node only when the document declares * one with a non-blank `url`; an emitter can surface it in a doc comment (a * JSDoc `@see`, say). `url` is exactly as written — OpenAPI allows a value * relative to the document's own location, which the parser does not know, so * it neither resolves nor rewrites it. `description` is present only when it * has non-whitespace content. */ interface ExternalDocs { url: string; description?: string; } /** * The specification extensions (`x-*` keys) an OpenAPI object declares, * each under the key as written with its value verbatim — a string, a * boolean, a number, `null`, an array or an object, nested values * included — in document order. Carried on `Operation`, `Model`, `Field` * and `Enum` as `extensions`, present only when the object declares at * least one key the parser does not already read into a typed field (an * Operation Object's `x-pagination`, `x-oagen-async`, * `x-mutually-exclusive-parameter-groups` and * `x-mutually-exclusive-body-groups`; a Schema Object's * `x-enum-descriptions` and `x-enumDescriptions`), so an emitter can read * the keys it knows (`x-idempotent`, `x-since`) without the parser knowing * each one. Not shape: two schemas that differ only in their extensions * are one model or one enum wherever the parser decides that, and the * differ reports a change to them as additive (`extensionsChanged`, * `field-extensions-changed`), never as a type change. Values come from * the document unvalidated, so an emitter that writes one into generated * source must escape it as it escapes a `description`. */ type Extensions = Record; /** Root IR node representing the full API surface */ interface ApiSpec { name: string; version: string; description?: string; /** The document's top-level `externalDocs`, when it declares a usable one. */ externalDocs?: ExternalDocs; baseUrl: string; servers?: ServerEntry[]; services: Service[]; /** * The requests the API sends to its users, from the document's top-level * `webhooks` map (OpenAPI 3.1), in document order. Absent — not an empty * list — when the document declares none, so the IR of a document without * webhooks is unchanged. A webhook is not an SDK method: it belongs to no * service, gets no resolved operation name, and is untouched by operation * hints and mount rules. See `Webhook`. */ webhooks?: Webhook[]; models: Model[]; enums: Enum[]; auth?: AuthScheme[]; /** * Document-level security requirements: the default every operation uses * unless it declares its own `Operation.security`. Same shape and semantics * as that field. `undefined` when the document declares none. */ security?: SecurityRequirementSet[]; /** Language-agnostic runtime policies (retry, errors, telemetry, etc.). */ sdk: SdkBehavior; } /** * A request the API sends to its users: one HTTP method of one entry in the * document's top-level `webhooks` map (OpenAPI 3.1). An entry whose path item * declares several methods yields one `Webhook` per method, so `name` alone * does not identify a webhook; `name` + `httpMethod` does. * * Everything here is read from the receiver's side of the wire: the request * body is the payload the receiver is handed, the parameters are the headers * (signatures, event types) and query values the request carries, and * `responses` are the status codes the sender expects back. An emitter uses * this to generate a payload type or a typed handler per event. A webhook is * never an SDK method: it has no path, belongs to no `Service`, and gets no * resolved operation name. * * An operation's `callbacks` (OpenAPI 3.x), whose path items have this * shape, are not read into `Webhook` or anywhere else; the parser warns at * every site that declares any (see `warnOnIgnoredCallbacks`). */ interface Webhook { /** The key under `webhooks`, verbatim (`petAdopted`, `user.created`). */ name: string; /** The operation's `operationId`, when the document declares one. */ operationId?: string; httpMethod: HttpMethod; /** * The `summary` alone, read as `Operation.summary` is: the operation's own, * else the path item's. Absent when neither has content. */ summary?: string; /** * Combined doc text, built as `Operation.description` is from the same * two-level read. Absent when neither level gives any text. */ description?: string; /** * The operation's own `externalDocs`, when it declares a usable one, as on * `Operation.externalDocs`. A Path Item Object has no `externalDocs`, so * there is nothing to fall back to. */ externalDocs?: ExternalDocs; /** Present, and `true`, only when the document marks the webhook deprecated. */ deprecated?: boolean; /** The operation's `tags`, read exactly as `Operation.tags` is. */ tags?: string[]; /** Header parameters the request carries, typed like `Operation.headerParams`. */ headerParams: Parameter[]; /** Query parameters the request carries, typed like `Operation.queryParams`. */ queryParams: Parameter[]; /** Cookie parameters; present only when the document declares at least one. */ cookieParams?: Parameter[]; /** * The payload the receiver is handed. An inline object schema is * materialized as a model named `Payload`, where the stem is the * `operationId` when there is one and the webhook's name otherwise (see the * parser's `resolveWebhookModelStems` for how the stem is kept unique). * Read from the content entry the same pick as `Operation.requestBody` * chooses, by media type essence. Absent when the operation declares no * `requestBody`, or one none of whose media types is read — which the * parser warns about. */ requestBody?: TypeRef; /** How the payload is encoded, read like `Operation.requestBodyEncoding`. */ requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text'; /** * The media type the payload was read from, by essence, read like * `Operation.requestBodyContentType` (`application/merge-patch+json`; * `application/json` for `application/json; charset=utf-8`): what the * sender labels the request with, so a handler can check it. Present * exactly when `requestBody` is. */ requestBodyContentType?: string; /** Present, and `true`, only when the document marks the request body `required`. */ requestBodyRequired?: boolean; /** * Doc text for the payload, read as `Operation.requestBodyDescription` * is: the Request Body Object's own `description`, else the `description` * written on the schema of the content entry `requestBody` is read from (a * `$ref` is not followed). Present only when one of the two has * non-whitespace content, kept verbatim. */ requestBodyDescription?: string; /** * Media types the payload declares under `content`, in document order and * exactly as written, read as `Operation.requestBodyContentTypes` is. * Present only when at least one is declared. */ requestBodyContentTypes?: string[]; /** * One entry per `requestBodyContentTypes` entry, in the same order, typed * as `Operation.requestBodyContents` is: the entry for the media type * `requestBody` was read from carries that same TypeRef; an inline object * under another media type is materialized as `Payload` * (`PetAdoptedTextCsvPayload`). Present only when `requestBodyContentTypes` * is. */ requestBodyContents?: RequestBodyContent[]; /** * The responses the sender expects from the receiver, in document order: * one entry per status code key (three digits, 100–599) the operation * declares. `default`, range (`2XX`) and `x-` keys are not carried; a key * that is none of those (`error`, `6XX`, `600`) is ignored with a warning. * Body schemas on these responses are not carried either: a webhook * response is an acknowledgement, and typing it would mint models no * handler needs. */ responses: WebhookResponse[]; /** * The security the request carries, mirroring the OpenAPI document exactly * as `Operation.security` does: `undefined` inherits `ApiSpec.security`, * `[]` means none, otherwise one alternative per requirement object. */ security?: SecurityRequirementSet[]; } /** One status code a webhook's sender expects back, with the document's description of it. */ interface WebhookResponse { statusCode: number; description?: string; } /** A service groups related operations (maps to an SDK resource class) */ interface Service { name: string; description?: string; /** * A document tag's `externalDocs`, resolved by the same rule as * `description`: a service named after a declared tag takes that tag's; a * split-off service inherits it from the first linked tag its operations * carry, chosen independently of the tag its description comes from. * Absent when no tag gives one. */ externalDocs?: ExternalDocs; operations: Operation[]; } /** One scheme a request must satisfy, with the scopes it needs. */ interface SecurityRequirement { /** Key under `components.securitySchemes`; joins to `AuthScheme.schemeName`. */ schemeName: string; scopes: string[]; } /** * One alternative from an OpenAPI security requirement list: a request must * satisfy *every* scheme in the set together ("all of"). A list of sets is * satisfied by *any one* of them ("either of"). An empty set is an alternative * that needs no credentials at all, which is how a document makes * authentication optional (`security: [{ userToken: [] }, {}]`). */ type SecurityRequirementSet = SecurityRequirement[]; /** A single API operation (maps to an SDK method) */ interface Operation { name: string; /** * The `summary` alone: the OpenAPI operation's own, or — when the operation * declares none with non-whitespace content — the `summary` of the Path * Item it sits on (the `paths` entry, or the `components/pathItems` item a * `$ref` entry leads to), which OpenAPI applies to every operation on that * path. Present only when one of the two has content; a summary that is not * a string, or is empty or whitespace-only, is treated as absent at either * level. Read this to use the * summary as a one-line label; `description` below still carries the * combined form, so emitters that only print `description` are unchanged. */ summary?: string; /** * Doc text for the operation, combined from a `summary` and a `description` * each read as `summary` above is: the operation's own, else the Path * Item's, field by field. When both have content, this is * `summary + "\n\n" + description`; when only one has content (or both are * identical), this is that one. A value that is not a string, or is empty * or whitespace-only, is treated as absent, and text with content is kept * verbatim. The parts are * not separable from this field alone — use `summary` for that. */ description?: string; /** The operation's own `externalDocs`, when it declares a usable one. */ externalDocs?: ExternalDocs; httpMethod: HttpMethod; path: string; /** * The servers this operation is served from, when they differ from the * document's: the operation's own `servers`, else its Path Item's (OpenAPI * precedence). Absent when the operation inherits `ApiSpec.servers` — it * declares none at either level, or what it declares is the document's list * again (same URLs, descriptions and variables, in the same order), or both * it and the document mean OpenAPI's default server (no servers, * `servers: []`, or nothing but `/`, whatever its description or * variables — `/` references none; `isDefaultServerList` in * `ir/server-url.ts`). Same * shape as `ApiSpec.servers`, variables included, so `resolveServerUrl` * from `ir/server-url.ts` fills a template's defaults the way `baseUrl` was * produced. To find where a request goes, take `op.servers ?? spec.servers`. */ servers?: ServerEntry[]; pathParams: Parameter[]; queryParams: Parameter[]; /** * Query parameters the spec also declares as request-body properties on a * body-carrying method (POST/PUT/PATCH). They travel in the body only, so * they are excluded from `queryParams`; they are kept here so inline enums * they declare stay reachable and the compat surface still sees them. * Emitters never serialize these to the URL. */ bodyOwnedQueryParams?: Parameter[]; headerParams: Parameter[]; cookieParams?: Parameter[]; /** * The request body's type, read from one content entry of the Request Body * Object (after a `components/requestBodies` `$ref` is resolved). Media * types are matched by essence — parameters and case aside, so * `application/json; charset=utf-8` and `APPLICATION/JSON` are * `application/json` — and tried in a fixed order: `application/json`, then * a `+json` media type (`application/vnd.api+json`), then * `multipart/form-data`, then `application/x-www-form-urlencoded`, each * only when it declares a schema; then `application/octet-stream`, then * `text/plain`, with or without one (a schema-less binary body is a binary * string, a schema-less text body a string). An inline object body is * materialized as `Request`; an inline enum body, or an array of one, * is promoted to `spec.enums` under that name, numbered on a clash with an * enum of other members. Absent when the operation declares no * body, or one none of whose media types is read — which the parser warns * about once, so a body is never dropped silently. */ requestBody?: TypeRef; /** * The wire encoding of the media type `requestBody` was read from: `json` * for `application/json` and any `+json` media type, `form-data` for * `multipart/form-data`, `form-urlencoded` for * `application/x-www-form-urlencoded`, `binary` for * `application/octet-stream`, `text` for `text/plain`. Set exactly when * `requestBody` is. */ requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text'; /** * The media type `requestBody` was read from, by essence — `type/subtype` * with parameters and case stripped: `application/merge-patch+json` for a * body declared under that key, `application/json` for one under * `application/json; charset=utf-8`, `multipart/form-data` for one under * `multipart/form-data; boundary=x`. This is what an emitter sends as the * request's `Content-Type`, so a server that requires its declared media * type accepts the request; parameters such as a multipart boundary are * the emitter's to produce. `requestBodyEncoding` says how to serialize * the body, this says how to label it. The key as written is the * `contentType` of the `requestBodyContents` entry that shares * `requestBody`'s type. Set exactly when `requestBody` is. */ requestBodyContentType?: string; /** * Whether a caller must send `requestBody`: the Request Body Object's * `required`, read after a `components/requestBodies` `$ref` is resolved. * OpenAPI defaults the flag to `false`, so a body the document does not * mark required comes through as `false`. Present exactly when * `requestBody` is; an operation without a body has no entry. */ requestBodyRequired?: boolean; /** * Doc text for the request body, e.g. "The pet to add to the shelter." — * what an emitter prints for the body argument, as `responseDescription` * is what it prints for the return. The Request Body Object's own * `description`, read after a `components/requestBodies` `$ref` is * resolved; when that has no non-whitespace content, the `description` * written on the schema of the content entry `requestBody` is read from, * as it stands there: a `$ref` is not followed, so a component's text * stays on its model, while a `description` written beside the `$ref` is * read. When both have content the body's own wins. The schema's text is * also the `description` of the model an inline object body is * materialized as (`Request`), and the `description` of the `Enum` * an inline enum body is lifted to (`Request` in `enums`); for a body * no model or enum carries — an inline `oneOf`, an array, a primitive — * this field is the only place that text reaches. Present only when one * of the two has non-whitespace content, kept verbatim. The body's own text is * carried whether or not a media type is read as `requestBody`; the * schema's is read only from the entry that is. */ requestBodyDescription?: string; /** * Media types the request body declares under `content`, in document * order and exactly as written (`application/json; charset=utf-8`, * `multipart/form-data; boundary=x`, `text/csv`), so an emitter can offer * each verbatim as a `Content-Type`. Present only when the body declares at * least one media type — whether or not one of them is read as * `requestBody` — as `responseContentTypes` is on the response side. */ requestBodyContentTypes?: string[]; /** * One entry per `requestBodyContentTypes` entry, in the same order, with * the type that media type resolves to. The entry for the media type * `requestBody` was read from carries that very TypeRef, so the two never * disagree. Every other entry is typed as it would be were it the only one * declared: from its schema when it has one (an inline object materialized * as `Request`, `ReplaceWidgetTextCsvRequest`), else a * binary string for `application/octet-stream`, a string for `text/plain`, * and `unknown` for any other media type. Present only when * `requestBodyContentTypes` is. */ requestBodyContents?: RequestBodyContent[]; /** * The primary success response's body type: the lowest declared status code * from 200 to 399 whose type is not `unknown` — the lowest 2xx with a typed * body, so a `200` left `unknown` by the media-type rules (a schema-less * `text/csv`) yields to a `201` typed from a schema, and a 3xx entry (always * `unknown`) never wins over a typed 2xx — falling back to the lowest * declared code (an untyped 2xx, or a 3xx when no 2xx is declared). * `responseHeaders` and `responseDescription` come from the same entry. * Never promoted from a `2XX` range or the `default` response: an * operation declaring no 2xx or 3xx response at all (only `default` or * `2XX`, only a `404`, an empty `responses` map, or no `responses` key) * has `{ kind: 'primitive', type: 'unknown' }` here — the type of a body * the document does not describe — with no `responseHeaders` or * `responseDescription`, and an emitter should take the success body * from `rangeResponses` (`2XX`), then `defaultResponse` — the same order * it resolves any status: the explicit entry, then the matching range, * then the default. A body that is itself an inline enum, or an array of * one, is promoted to `spec.enums` as `Response` (see * `SuccessResponse.type` for one of several success bodies). */ response: TypeRef; /** * The status code of the response `response` was read from — the primary * success response chosen as described there: `200`; `201` when an untyped * `200` yielded to a typed `201`; `302` for a lone redirect; a POST's lone * `200`. Present exactly when the operation declares at least one 2xx or * 3xx response, and absent when it declares none (only `default`, a range, * 4xx/5xx codes, an empty `responses` map or no `responses` key) — the * case where `response` is `unknown`. When `successResponses` is set, this * equals the `statusCode` of the entry `response` was taken from. Read it * to check or document the status an operation succeeds with instead of * guessing one from the HTTP method. The differ pairs a lone 2xx/3xx with * the other spec's entry of this code, so an entry added beside it is not * mistaken for it, and reports it moving while both specs carry one as * `responseStatusCodeChanged`. */ responseStatusCode?: number; /** * Headers the primary success response declares (the one `response` is the * body of). Present only when the spec declares at least one. Each entry of * `successResponses` carries its own `headers`, but that list is only set * when an operation declares more than one 2xx or 3xx response (counted * together), so the primary response's headers need a home of their own. */ responseHeaders?: ResponseHeader[]; /** * Media types the primary success response declares under `content`, in * document order and exactly as written (`application/json; charset=utf-8`, * `application/vnd.api+json`, a wildcard such as `application/*`). Present * only when it declares at least one. Like `responseHeaders`, this lifts * the primary entry's `contentTypes`, because `successResponses` only * exists when an operation declares more than one 2xx or 3xx response. */ responseContentTypes?: string[]; /** * One entry per `responseContentTypes` entry, in the same order, with the * type that media type's schema resolves to. The entry for the media type * `response` was read from carries that same TypeRef. Present only when * `responseContentTypes` is. */ responseContents?: ResponseContent[]; /** * The `description` of the primary success response (the one `response` is * the body of), e.g. "The pet, with its owner." — often the clearest * statement of what an operation gives back, so an emitter can print it as * a `@returns` tag. Present only when that response declares one with * non-whitespace content; the text is kept verbatim. Each entry of * `successResponses` carries its own `description`, but that list is only * set when an operation declares more than one 2xx or 3xx response (counted * together), so the primary response's description needs a home of its own. */ responseDescription?: string; /** * Every declared 2xx and 3xx response, one `SuccessResponse` per status * code, each with its own `type`, `headers` and `description`. A 2xx entry's * `type` is its body, read by media type compared by essence, parameters * and case aside (the JSON schema — `application/json`, else a `+json` * media type; else binary string for `application/octet-stream` / * `application/pdf`; else `string` for `text/plain`, `text/html`, * `text/xml`, `application/xml`; else the schema of the first media type * that declares one) and `unknown` when none applies, a schema-less * `text/csv` included; a 3xx entry's `type` is always * `unknown`, and the entry is kept so an emitter can * recognize a redirect endpoint. Set only when more than one such response * is declared, counting 2xx and 3xx together: `200` + `201`, `200` + `302` * and `301` + `302` all set it, while a lone `200` (or a lone `302`) leaves * it `undefined` and `response` / `responseHeaders` / `responseDescription` * describe that single response alone. 4xx and 5xx responses go to * `errors`; `default` and the ranges `1XX`–`5XX` to `defaultResponse` and * `rangeResponses`; an explicit 1xx code is not carried. A key is a status * code only when it is exactly three digits in 100–599: `6XX`, `4XXX`, * `20X`, `600` and `200 ` are no status code and no range, so they are * ignored with a warning, like `error`, never read from a numeric prefix. */ successResponses?: SuccessResponse[]; errors: ErrorResponse[]; /** * The document's `default` response: what the operation returns for every * status it does not list explicitly or by range. Present only when the * spec declares one. It is kept apart from `errors` because it carries no * status code (`ErrorResponse.statusCode` is a number emitters compare and * format as one) and is not always an error — a spec may use it for its * success body too. An emitter should treat its `type` as the fallback for * any status that neither `errors`/`successResponses` nor `rangeResponses` * covers. `response` is never promoted from it: when the operation declares * no explicit 2xx, the emitter takes the success body from the `2XX` entry * of `rangeResponses`, then from here. */ defaultResponse?: DefaultResponse; /** * The document's `1XX`–`5XX` range responses, in declaration order. Present * only when the spec declares at least one. A range covers every status in * its hundred that the operation does not list explicitly, so an emitter * resolves a status in the order OpenAPI does: the explicit entry, then * the range, then `defaultResponse`. Ranges never feed `response`, * `successResponses` or `errors`, whose numeric `statusCode` could not say * which codes an entry stands for. */ rangeResponses?: RangeResponse[]; pagination?: PaginationMeta; injectIdempotencyKey: boolean; deprecated?: boolean; async?: boolean; /** * The operation's `tags`, in document order, with every entry that is not * a non-empty string dropped and a repeated entry folded onto its first * occurrence. Present only when at least one remains. The parser names the * service from `tags[0]` — the first usable entry — so the two never * disagree; the list is kept so an emitter can group or document the * method by every tag. */ tags?: string[]; /** * Per-operation security requirements, mirroring the OpenAPI document: * - `undefined` — the operation declares nothing and inherits * `ApiSpec.security` (which may itself be `undefined`). * - `[]` — `security: []`: the operation needs no authentication. * - otherwise one `SecurityRequirementSet` per requirement object; the * request must satisfy any one set, and every scheme within it. */ security?: SecurityRequirementSet[]; /** * Mutually-exclusive parameter groups parsed from `x-mutually-exclusive-parameter-groups`. * Each group represents a logical choice the caller must (or may) make between * several subsets of query/path/header parameters. The grouped parameters remain * in their original arrays (queryParams, pathParams, etc.) for wire-format purposes; * this field adds the grouping metadata so emitters can render sum types. */ parameterGroups?: ParameterGroup[]; /** * The Operation Object's own `x-*` keys (see `Extensions`), less the ones * the parser reads into typed fields: `x-pagination` (`pagination`), * `x-oagen-async` (`async`), `x-mutually-exclusive-parameter-groups` and * `x-mutually-exclusive-body-groups` (`parameterGroups`). A Path Item * Object's extensions are not read. Present only when at least one key * remains. */ extensions?: Extensions; } /** * A mutually-exclusive parameter group. The caller must supply exactly one * variant (when `optional` is false) or may omit the group entirely (when true). */ interface ParameterGroup { /** Group name from the extension (e.g. "parent_resource"). */ name: string; /** True when the whole group may be omitted. */ optional: boolean; /** Ordered variants (insertion order matches the spec). */ variants: ParameterGroupVariant[]; /** * Base name emitters must use for this group's generated wrapper type, in * place of `name`. * * Two operations commonly share one group name — create and update both * declare `protocol_options` — and emitters name the wrapper from the group * name alone, so both operations collapse onto one type. That is correct * only while their members agree. When they disagree (create's * `saml_options` is a `CreateConnectionSAMLOptions`, update's is a * `PatchConnectionSAMLOptions`) one wrapper silently forces one operation to * use the other operation's type. * * The parser therefore fingerprints each group's members across every * operation declaring it and qualifies this with the operation name * (`update_connection_protocol_options`) only where they genuinely diverge. * Groups that agree — including ones differing only by nullability, or by * duplicate inline enums carrying identical values — keep the bare group * name, so already-published wrapper types are never renamed. */ wrapperName?: string; } /** * One variant within a mutually-exclusive parameter group. */ interface ParameterGroupVariant { /** Variant name from the extension (e.g. "by_id", "by_external_id"). */ name: string; /** * References to the actual parameter IR nodes. These are the same * objects that live in operation.queryParams / .pathParams / .headerParams -- * shared by identity, not duplicated. */ parameters: Parameter[]; /** * Names of parameters that may be omitted when this variant is used — * optional modifiers of the variant's required fields, from the * extension's `optionalFields`. Absent means every parameter in the * variant is required with it. */ optionalParameters?: string[]; } /** * How an operation's list is paged — what an auto-paging iterator sends to * reach the next page: * * - `cursor` — `param` carries an opaque cursor taken from the previous * response; iteration ends when the response yields no next cursor. * - `offset` — `param` is the number of items to skip; advance it by the * number of items received, with `limitParam` as the page size. * - `page` — `param` is a page *number*; start at `pageStart` (the * parameter's `default`, else its `minimum`, else 1) and advance it by * exactly one per request, with `limitParam` as the page size. * - `link-header` — follow the RFC 5988 `Link: <…>; rel="next"` response * header instead of building the next request from `param`. * * Under every strategy an empty page ends the iteration; `endOfIteration` * names a response field that ends it earlier. */ type PaginationStrategy = 'cursor' | 'offset' | 'page' | 'link-header'; /** * The response field that tells an iterator the last page has been reached. * `path` is a dotted property path from the response root, in the convention * `dataPath` uses: `has_more` at the top level, `pagination.totalPages` one * level down inside the pagination companion. * * - `hasMore` — a boolean; stop when it is `false`. * - `totalPages` — an integer count of pages; stop once the pages fetched so * far reach it. For the `page` strategy that is * `page - pageStart + 1 >= totalPages` — `page >= totalPages` when pages * start at 1, `page + 1 >= totalPages` when they start at 0 — and for * `offset` it is `floor(offset / limit) + 1 >= totalPages`. * - `totalCount` — an integer count of items; stop once the items received * so far reach it. * * An empty page ends the iteration under every kind and every strategy. */ interface PaginationEndOfIteration { kind: 'hasMore' | 'totalPages' | 'totalCount'; path: string; } /** * Structured pagination metadata for auto-paging iterator generation. * * Present only when a query parameter the operation declares drives the * iterator — the one detection recognized, or the one an override names — * so `param` is always a query parameter of the operation. A list envelope * returned by an operation that declares no such parameter (a `page` * without a page size, no paging parameter at all) is kept as a plain * response model and has no entry here. */ interface PaginationMeta { strategy: PaginationStrategy; /** Query parameter that selects the page: the cursor, the offset, or the page number. */ param: string; /** Query parameter that sets the page size (`offset` and `page` strategies). */ limitParam?: string; /** * First page number the API expects; set for the `page` strategy only. The * page parameter's integer `default`, else its `minimum`, else 1 — read * from the parameter's schema as written, through a `$ref`, `allOf` * members and nullable wrappers — or the value an override sets (an * override may set it under the `page` strategy only). An * iterator sends `pageStart` first and `pageStart + n` after `n` pages; * `PaginationEndOfIteration` shows how the base enters the `totalPages` * stop rule, so emitters never re-derive it. */ pageStart?: number; dataPath?: string; /** * The description the document gives the data array property itself — the * one `dataPath` names — so an emitter that documents what a list method * returns can read it here instead of from the document. Like a `Field`'s * `description` it is the property's own text, never the item schema's. * * Present only when the property declares one; absent whenever `dataPath` * is, since there is no property to take it from. */ dataDescription?: string; itemType: TypeRef; /** * Every property the list envelope carries besides the data array, in * document order: the pagination companion (`list_metadata`, `pagination`, * `has_more`, …, recognized in any spelling — `pageInfo` as much as * `page_info`) and any discriminant such as `object: "list"`. Together * with `dataPath` and `itemType` this is the envelope's full shape, so an * emitter can type what the endpoint returns and read the page details it * needs for the next request without parsing the document itself. * * An inline companion object is lifted to a model. Because the same envelope * recurs on every list endpoint of an API, copies that agree structurally * share one model named from the property alone (`list_metadata` → * `ListMetadata`, or the component schema of that name when one exists); a * copy whose shape differs keeps an operation-qualified name * (`ListUsersListMetadata`) so it can never change another type's shape. * * Absent when the response is a bare array, or when pagination was inferred * from query parameters alone and no envelope was detected. */ envelopeFields?: Field[]; /** * Where the response says the iteration is over (see * `PaginationEndOfIteration`). Detected from a recognized list envelope * when it carries an obvious field — a boolean `has_more`/`hasMore`, an * integer `total_pages`/`totalPages`, or an integer `total`/`total_count` — * beside the array a nested `dataPath` names (`result.total_pages`), at * the top level, or one level down inside a pagination companion object * (`pagination.totalPages`), in that order, and the same way from the body * an explicit `dataPath` keeps as a wrapper — a component the response is * a `$ref` to, or an inline body detection did not recognize; a `hasMore` * field is preferred over a * `totalPages` one, which is preferred over a count. The operation's * `x-pagination` extension or its `operationHints` entry can set it * explicitly, to a field of the primary response whose type fits the kind. * Absent when nothing recognizable is declared; an emitter then * stops on an empty page (and, for `cursor`, on a missing next cursor). */ endOfIteration?: PaginationEndOfIteration; } type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace'; /** * JSON Schema validation keywords declared directly on a schema, carried so an * emitter can document a value's limits ("at most 100"), check a value before * sending it, or keep a generated example within range. Every member is * optional and present only when the document declares it; a schema with no * validation keyword has no `constraints` at all. * * Numeric bounds use the OpenAPI 3.1 / JSON Schema 2020-12 shape, where * `exclusiveMinimum` / `exclusiveMaximum` are the bound itself. OpenAPI 3.0 * spells them as booleans that make `minimum` / `maximum` exclusive; the * parser normalizes that form, so `{ minimum: 0, exclusiveMinimum: true }` * arrives as `{ exclusiveMinimum: 0 }` with no `minimum`, and a `false` is * dropped. Emitters read one shape whichever version produced it. * * The keywords on the field, parameter or model schema itself are carried, * conjoined with those of its inline `allOf` members (a single-member * `allOf` is unwrapped by the parser, so its limit is the value's own; a * `$ref` member contributes the keywords written beside the reference while * the referenced model keeps its own). Limits nested inside array `items` or * map values are not carried. A nullable wrapper — `oneOf`/`anyOf` with a * single non-null, non-`$ref` branch — conjoins that branch's keywords with * its own; limits on a general multi-variant union are not carried. */ interface Constraints { /** Inclusive lower bound (`minimum`). */ minimum?: number; /** Inclusive upper bound (`maximum`). */ maximum?: number; /** Exclusive lower bound as a number; the OAS 3.0 boolean form is normalized to this. */ exclusiveMinimum?: number; /** Exclusive upper bound as a number; the OAS 3.0 boolean form is normalized to this. */ exclusiveMaximum?: number; /** The value must be an integer multiple of this (`multipleOf`). */ multipleOf?: number; /** Minimum string length in characters (`minLength`). */ minLength?: number; /** Maximum string length in characters (`maxLength`). */ maxLength?: number; /** ECMA-262 regular expression the string must match (`pattern`), verbatim from the document. */ pattern?: string; /** Minimum number of array items (`minItems`). */ minItems?: number; /** Maximum number of array items (`maxItems`). */ maxItems?: number; /** Present, and `true`, when array items must be unique; `uniqueItems: false` restates the default and is dropped. */ uniqueItems?: boolean; /** Minimum number of items matching the schema's `contains` (`minContains`). */ minContains?: number; /** Maximum number of items matching the schema's `contains` (`maxContains`). */ maxContains?: number; /** Minimum number of object properties (`minProperties`). */ minProperties?: number; /** Maximum number of object properties (`maxProperties`). */ maxProperties?: number; /** Property name → properties that must also be present when it is (`dependentRequired`). */ dependentRequired?: Record; } interface Parameter { /** * The name as the document wrote it (`X-Pet-Token`); emitters apply their * own casing. A parameter's identity is its location and name — * `parameterKey` in `ir/parameter-key.ts`, which compares a header's name * case-insensitively (RFC 9110 §5.1) and every other as written. The * parser merges a path item's parameters into its operations on that * identity, and the differ pairs parameters on it. */ name: string; /** * The parameter schema's type. The parameter's schema is its `schema` or, * for a parameter declared with a `content` map in its place, the schema * of the entry read from that map: `application/json` or a `+json` media * type when the entry declares a schema, else `text/plain` with or without * one, each matched by media type essence (parameters and case stripped). * A `text/plain` entry without a schema types the parameter as a string; * a map none of whose media types is read does too, with a parser warning * that names them; a `schema` beside a `content` map wins. Every field of * this interface that reads "the parameter's schema" reads this schema, * so a parameter declared either way is typed by one rule. * * An inline object schema (a `deepObject` query parameter, say), or an * array, map, union or nullable wrapper holding one, references a model * the parser creates for it, named from the service and parameter * (`PetsFilter`; a header's name lower-cased first, so `X-RateLimit-Meta` * and `x-ratelimit-meta` both reference `PetsXRatelimitMeta`) and * qualified by location or operation when that name already belongs to * another shape (see "Response Headers" in docs/architecture/ir-types.md); * a webhook's is named under the webhook's stem. A primitive, a `$ref`, an * inline enum (named the same way) or an array of either is typed as * written. */ type: TypeRef; required: boolean; description?: string; deprecated?: boolean; /** * The parameter schema's `externalDocs`, when it declares a usable one; * a schema that is a `$ref` falls back to the component it points at, * the way `description` and `deprecated` do. A Parameter Object has no * `externalDocs` of its own. Absent when neither level gives one. */ externalDocs?: ExternalDocs; default?: unknown; /** * A single illustrative value, resolved level by level: the parameter's own * `example` (else the first entry of its `examples` map), then — for a * parameter declared with `content` — the same on the Media Type Object * its schema was read from, then the parameter schema's `example` (else * the first of its `examples` list), then the same on the component schema * its `$ref` points at. A level with neither falls through; an explicit * `null` is kept. Absent when no level gives one. */ example?: unknown; /** * Every example value the document gives, in document order: the * parameter's `examples` map of Example Objects (each entry's `value`, with * `$ref`s resolved against `components.examples`), else — for a parameter * declared with `content` — the same map on the Media Type Object its * schema was read from, else the JSON Schema `examples` list on the * parameter's schema, else the list on the component schema its `$ref` * points at. Present only when at least one value exists. */ examples?: unknown[]; style?: 'form' | 'simple' | 'label' | 'matrix'; explode?: boolean; /** * The media type the parameter's value is serialized in: the `content` * key its schema was read from, as written (`application/json; * charset=utf-8`). Present exactly when the parameter is declared with * `content` and the map is read (see `type`) — a schema-less `text/plain` * entry included; absent for a `schema` parameter, and for a `content` * map none of whose media types is read, whose string value is sent as * written. An emitter that serializes parameters by `style` and `explode` * must instead serialize such a value in this media type: JSON-encode an * `application/json` or `+json` value, send a `text/plain` value as text. * `oagen diff` compares it by essence and reports a change as a breaking * `param-content-type-changed`. */ contentType?: string; /** * Validation keywords from the parameter's schema. When that schema is a * `$ref`, the target's keywords are merged underneath the parameter's own * — the per-value fallback `default` and `example` use — so a parameter * can be read on its own without chasing the target (a primitive * component becomes a fieldless model; an array component becomes no * model). Absent when neither declares any. */ constraints?: Constraints; } /** Type reference — the core type system of the IR */ type TypeRef = PrimitiveType | ArrayType | ModelRef | EnumRef | UnionType | NullableType | LiteralType | MapType; interface PrimitiveType { kind: 'primitive'; type: 'string' | 'integer' | 'number' | 'boolean' | 'unknown'; format?: string; } interface ArrayType { kind: 'array'; items: TypeRef; } interface ModelRef { kind: 'model'; name: string; } interface EnumRef { kind: 'enum'; name: string; values?: (string | number)[]; } interface LiteralType { kind: 'literal'; value: string | number | boolean | null; } interface UnionType { kind: 'union'; variants: TypeRef[]; discriminator?: { property: string; mapping: Record; }; /** Which OAS composition keyword produced this union. Emitters can use this to * distinguish inheritance (allOf) from exclusive union (oneOf) from open union (anyOf). */ compositionKind?: 'allOf' | 'oneOf' | 'anyOf'; } interface NullableType { kind: 'nullable'; inner: TypeRef; } interface MapType { kind: 'map'; valueType: TypeRef; keyType?: TypeRef; } /** * A generic type parameter on a model. * Example: `DirectoryUser>` * → `{ name: 'TCustomAttributes', default: { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } } }` */ interface TypeParam { name: string; /** Default type when the param is not specified. */ default?: TypeRef; } /** * Model definition (maps to an SDK model/data class). Every * `components/schemas` entry becomes one, except an enum (`Enum`) and an * array component — a schema that is an array and declares `items`, or an * alias of one (a bare `$ref`, or an `allOf` of a `$ref` and limits) — which * becomes no model at all: a `$ref` to it resolves to the array it declares * (`{ kind: 'array' }`, under `nullable` when the component admits null), * and what its items reference is extracted under `Item…`; the * component's own `description`, `deprecated` and `externalDocs` are read * by a field that names it with a bare `$ref` (`Field`). The inline schemas * the parser materializes — request bodies, responses, union variants, * nested objects, array items, map values — are models too. */ interface Model { name: string; description?: string; /** The schema's `externalDocs`, when it declares a usable one. */ externalDocs?: ExternalDocs; /** * Present, and `true`, when the schema this model was built from says * `deprecated: true` — a component, a discriminated-union variant, or an * inline request body, response or field object. Only that schema's own * top-level keyword counts, read as `Field.deprecated` is: an `allOf` * member's or a nullable branch's flag is not read (a `$ref` member's stays * on the referenced model), and a folded `Json` model's flag does not * deprecate the `` it collapses into. Absent otherwise. An inline * schema that shares the name of a model the document declares has no * model of its own: a deprecated schema identical to a live component * keeps its flag on the `Field`, `Parameter` or envelope field that wrote * it, and a site with no node of its own carries none — a request body or * response, an array's items, a `oneOf` variant, a webhook payload * variant, an error or secondary body — so deprecating only the items of * `Pet.owners` beside a live component of their shape leaves no trace in * the IR, as it leaves none when two inline copies fold. */ deprecated?: boolean; fields: Field[]; /** Generic type parameters. Empty/undefined for non-generic models. */ typeParams?: TypeParam[]; /** * Set when the model is a named union: a component schema that is itself a * `oneOf`/`anyOf` with no `properties` of its own. One TypeRef per non-null * variant, in document order, built exactly as an inline union's are: a * `$ref` variant is a `model`/`enum` ref, an inline object variant is a ref * to a model extracted for it (named from this model with the inline * variant rules, never this model's own name), a primitive stays a * primitive. A `type: 'null'` variant is dropped, as an inline union lifts * it into a `nullable` wrapper; a Model has no such wrapper. `fields` keeps * the optional merge of the inline variants' properties it always had, so * an emitter that does not read `variants` sees the same model as before. */ variants?: TypeRef[]; /** Which composition keyword produced `variants`. Present exactly when `variants` is. */ compositionKind?: 'oneOf' | 'anyOf'; /** * When set, this model is a discriminated union — over its `variants` (a * named `oneOf`/`anyOf` with a `discriminator:` keyword or a const-pinned * property shared by every variant) or over allOf+oneOf variants (where * `variants` is absent and the mapping alone names them). Emitters should * generate a dispatcher (factory) instead of a regular dataclass. The * `property` field is the discriminator key (e.g. "event"), and `mapping` * maps each discriminator value to the concrete variant model name (an IR * model name, after `schemaNameTransform`). */ discriminator?: { property: string; mapping: Record; }; /** * Validation keywords declared on the model's own schema — for an object * schema, `minProperties`, `maxProperties` and `dependentRequired`. Absent * when the schema declares none. */ constraints?: Constraints; /** * The `x-*` keys of the schema the model was built from (see * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`: a * component's own, or the inline schema's — a request body, a response, * a `oneOf` variant, an object nested in a field, array items, an * `allOf` wrapper's (a member's keys stay on that member, a `$ref` * member's on its component). A nullable `oneOf`/`anyOf` or single-member * `allOf` wrapper the parser collapses carries its keys onto the model * built from its branch, the wrapper's value winning for a key both * declare, as its link rides onto it. Present only when at least one key * remains. Not shape: an inline schema that differs from a model only * here shares that model, which keeps its own keys. */ extensions?: Extensions; } interface Field { name: string; /** * Optional domain-facing name override. When set, emitters derive the * domain-side identifier (in their own casing) from this instead of `name`, * while serialization still uses `name` for the wire key. Lets an SDK expose * a wire field under a friendlier name (e.g. `connection_type` → `type`) * without changing the API contract. Set via the `fieldHints` config and * honored by any emitter that reads it. */ domainName?: string; type: TypeRef; required: boolean; /** * The field schema's own `description`; for a bare `$ref` to an array * component — which names no model to carry the component's text — the * component's, as `example` falls back to it. A `$ref` to a model, named * union or enum leaves the text on it. */ description?: string; /** * The field schema's own `externalDocs`, when it declares a usable one — * read like `description`: for a `$ref` with an `externalDocs` sibling * (legal in OAS 3.1), the sibling's link, while the referenced model keeps * its own; a bare `$ref` yields none, unless it names an array component, * whose link the field then carries. Absent otherwise. Documentation, not * shape: two fields that differ only here are one shape. */ externalDocs?: ExternalDocs; readOnly?: boolean; writeOnly?: boolean; /** * Present, and `true`, when the field schema says `deprecated: true` — a * keyword written beside a `$ref` included — or when a bare `$ref` names * an array component that says so, since no model carries that * component's flag. The flag of a model, named union or enum a `$ref` * names stays on it. */ deprecated?: boolean; default?: unknown; /** * A single illustrative value. The field schema's `example` when present, * otherwise the first entry of its `examples`; when the schema is a `$ref` * with neither, the same taken from the component it points at. An * explicit `null` is kept. Absent when no level gives one. */ example?: unknown; /** * Every example value the schema gives, in document order, from the JSON * Schema `examples` list (OAS 3.1 deprecates `example` in its favour) — * on the field schema, else on the component its `$ref` points at. * Present only when the list has at least one entry. */ examples?: unknown[]; /** * Validation keywords declared on the field's schema, including any * written beside a `$ref` (OpenAPI 3.1 allows siblings). Absent when the * schema declares none; a bare `$ref` yields none, since the referenced * model carries its own limits. */ constraints?: Constraints; /** * The field schema's own `x-*` keys (see `Extensions`), less * `x-enum-descriptions` / `x-enumDescriptions`, read like `constraints`: * keys written beside a `$ref` (legal in OAS 3.1) are the field's, a bare * `$ref` yields none — the referenced model, union or enum carries its * own — unless it names an array component, whose keys the field then * carries as it carries that component's `description`. A property * several `allOf` members always declare is typed by the first typing * declaration, keys included (a typeless one fills in what it leaves * unset); a property only variants declare carries exactly the keys * every declaration as written agrees on, value for value, whether or * not the declarations share one shape — in an inline `allOf` and under * a component (a bare `oneOf` component, a union member of a component * `allOf`) alike. Present only when at least one * key remains. Not shape: two fields that differ only here are one shape. */ extensions?: Extensions; } /** Enum definition */ interface Enum { name: string; /** * The enum schema's own `description`: a component enum's, as * `Model.description` is a component model's, or — for an enum lifted * from an inline schema on a property, parameter, response header, * request or response body (primary, secondary-media-type, error or * fallback) or webhook parameter or payload, including array items, * `oneOf` variants and a `oneOf` of string consts collapsed into one enum * — the text of the schema that declares its members, read as its * `externalDocs` is: a nullable `oneOf`/`anyOf` or single-member `allOf` * wrapper the parser collapses gives its own text when it has content, * and the branch's own counts only when the wrapper has none. A * Parameter or Header Object's `description` is that parameter's or * header's, never the enum's. Present only when the text has * non-whitespace content, kept verbatim. When several inline schemas lift * to one name, the first lifted gives the text, as it gives the values and * the link, so the key is absent when that schema declared none even if a * later one does. Documentation, not shape: the differ does not report a * change to it, and two inline enums that differ only in it are one enum. */ description?: string; values: EnumValue[]; /** Spec-level default value (the value of `default:` on the schema). Optional. */ default?: string | number; /** * The enum schema's `externalDocs`, when it declares a usable one: a * component enum's own, or — for an enum lifted from an inline schema on a * property, parameter or response header — that schema's. A nullable * wrapper the parser collapses carries its link onto the enum, as it does * onto a model; when several inline schemas lift to one name, the first * lifted gives the link, as it gives the values. */ externalDocs?: ExternalDocs; /** Present, and `true`, when the component enum schema says `deprecated: true`; absent otherwise. */ deprecated?: boolean; /** * The `x-*` keys of the schema that declares the members (see * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`, which * the values' `description` is read from: a component enum's own, or — * for an enum lifted from an inline schema — that schema's, read as its * `description` and `externalDocs` are: a nullable `oneOf`/`anyOf` or * single-member `allOf` wrapper the parser collapses carries its keys * onto the branch, the wrapper's value winning for a key both declare. * The field, parameter or header the inline schema types carries the * same keys, since they are its schema's own. When several inline * schemas lift to one name, the first lifted gives the keys, as it gives * the values. Present only when at least one key remains. Not shape: two * inline enums that differ only here are one enum. */ extensions?: Extensions; } /** * One member of an enum. An enum schema is an `enum:` list or a * `oneOf`/`anyOf` whose every non-null variant is a string `const` schema * (the OAS 3.1 spelling that documents values one by one); both give one * `EnumValue` per member, in document order. */ interface EnumValue { /** UPPER_SNAKE_CASE form of `value`. */ name: string; /** The value as written; a number stays a number. */ value: string | number; /** * The value's own documentation: a `const` member's `description`, else * the entry for the value in the enum schema's `x-enum-descriptions` / * `x-enumDescriptions` extension. Present only when that text has * non-whitespace content; absent otherwise. */ description?: string; /** * Present, and `true`, when the value's `const` member says * `deprecated: true`; absent otherwise. An `enum:` list has no per-value * keyword, so its values never carry it. */ deprecated?: boolean; } /** * A header a response declares, typed like a parameter. `name` is kept exactly * as written in the spec (e.g. `Content-Disposition`); emitters apply their * own casing. Header names are case-insensitive (RFC 9110 §5.1), so one * response declares each header once: of two keys that differ in case * alone, the parser keeps the later (`foldHeaderName` in * `ir/parameter-key.ts` decides which keys are one header). */ interface ResponseHeader { name: string; /** * The header schema's type. The header's schema is resolved as a * parameter's is (see `Parameter.type`): the Header Object's `schema` * (resolved through `components/headers`) or, in its place, the schema of * the `content` entry read by the same media type rule. A header with * neither, a `text/plain` entry without a schema, or a map none of whose * media types is read — the last with a parser warning — is a string. */ type: TypeRef; required: boolean; description?: string; deprecated?: boolean; /** * The header schema's `externalDocs`, when it declares a usable one — the * schema `type` is read from, whether the Header Object's `schema` or the * `content` entry's. A Header Object has no `externalDocs` of its own. * Absent otherwise. */ externalDocs?: ExternalDocs; } interface ErrorResponse { statusCode: number; type?: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** * Media types declared under `content`, in document order and as written. * `type` is by definition the JSON body (`application/json`, else the first * `+json` media type), so the list is present only when it says something * `type` does not: the error declares another media type, a JSON media type * other than plain `application/json` (`application/problem+json` alone, * `application/json; charset=utf-8`), or a JSON body `type` could not be * read from. An error that declares only `application/json` with a schema * keeps its shape. */ contentTypes?: string[]; /** * One entry per `contentTypes` entry, in the same order. The entry for the * media type `type` was read from carries the same TypeRef as `type`. * Present only when `contentTypes` is. */ contents?: ResponseContent[]; /** * The response's `description` as written in the document (e.g. "Not * found"). Present only when it has non-whitespace content; kept verbatim. */ description?: string; } /** * One entry of `Operation.successResponses`: a declared 2xx or 3xx response. * A 3xx entry's `type` is always `unknown`. A 2xx body that is itself an * inline enum, or an array of one, is promoted to `spec.enums` as * `Response`; every entry derives that same name, so a second body with * other members is qualified with its status code (`CheckPetKindResponse202`), * while identical members share one enum. */ interface SuccessResponse { statusCode: number; type: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** * Media types declared under `content`, in document order and as written. * Present only when there is at least one. */ contentTypes?: string[]; /** * One entry per `contentTypes` entry, in the same order. The entry for the * media type `type` was read from carries that same TypeRef. Present only * when `contentTypes` is. */ contents?: ResponseContent[]; /** * The response's `description` as written in the document (e.g. "The pet, * with its owner."). Present only when it has non-whitespace content; kept * verbatim. */ description?: string; } /** * One media type a response declares under `content`, with the type its * schema resolves to. `contentType` is kept exactly as written in the spec, * parameters and all, so it can be sent back verbatim in an `Accept` header. */ interface ResponseContent { contentType: string; type: TypeRef; } /** * One media type a request body declares under `content`, with the type it * resolves to. `contentType` is kept exactly as written in the spec, * parameters and all, so it can be sent verbatim as a `Content-Type`. */ interface RequestBodyContent { contentType: string; type: TypeRef; } /** * The `default` response: the body and headers for every status the * operation does not list. See `Operation.defaultResponse`. */ interface DefaultResponse { /** * Response body type: the `application/json` body, else the first `+json` * one; absent when the response declares neither. */ type?: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** * Media types declared under `content`, in document order and as written, * exactly as on `SuccessResponse`. Present only when there is at least one. */ contentTypes?: string[]; /** * One entry per `contentTypes` entry, in the same order. The entry for the * media type `type` was read from carries that same TypeRef. Present only * when `contentTypes` is. */ contents?: ResponseContent[]; /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */ description?: string; } /** A Responses Object range key, uppercase as OpenAPI writes it (`4xx` is read as `4XX`). */ type StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX'; /** * A range response: the body and headers for every status in one hundred * (`4XX` → 400–499) that the operation does not list explicitly. See * `Operation.rangeResponses`. */ interface RangeResponse { range: StatusRange; /** * Response body type: the `application/json` body, else the first `+json` * one; absent when the response declares neither. */ type?: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** Media types declared under `content`, as on `DefaultResponse`. */ contentTypes?: string[]; /** One entry per `contentTypes` entry, as on `DefaultResponse`. */ contents?: ResponseContent[]; /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */ description?: string; } //#endregion //#region src/parser/schemas.d.ts /** * Signature of the `schemaNameTransform` hook. `name` is the cleaned * PascalCase name; `originalName` is the `components.schemas` key exactly * as spelled in the document, or `undefined` for names oagen synthesises. * See `SchemaExtractionOptions.schemaNameTransform`. */ type SchemaNameTransform = (name: string, originalName?: string) => string; //#endregion //#region src/ir/operation-hints.d.ts /** Per-operation override keyed by "METHOD /path" (e.g. "POST /auth/token"). */ interface OperationHint { /** Override the algorithm-derived method name. */ name?: string; /** Remount this operation to a different service/namespace (PascalCase). */ mountOn?: string; /** Split a union-body operation into N typed wrapper methods. */ split?: SplitHint[]; /** Inject constant body defaults (e.g. { grant_type: 'password' }). */ defaults?: Record; /** Fields the SDK reads from client config at runtime (e.g. ['client_id']). */ inferFromClient?: string[]; /** * Marks this operation as a URL builder rather than a real HTTP call. Emitters * should generate a method that returns the constructed URL (typically as a * string) without performing any I/O. Used for OAuth-style redirect endpoints * such as /auth/authorize and /accounts/sessions/logout. */ urlBuilder?: boolean; /** * Explicit pagination for this operation, applied by the parser (through * `ParseOptions.operationHints`) rather than by `resolveOperations`. Same * shape as the spec's `x-pagination` Operation Object extension; a field set * here wins over the extension, which wins over name-based detection. */ pagination?: PaginationHint; } /** * Explicit pagination for one operation — the object a spec can carry as * `x-pagination` on an Operation Object and that `OperationHint.pagination` * accepts from config. Every field is optional and layers over the * lower-precedence sources (config hint > `x-pagination` > detection), so * `{ strategy: 'page' }` alone keeps the detected `param` and `limitParam`. * * `strategy: 'none'` turns pagination off for the operation; a list envelope * is then kept as a plain response model rather than unwrapped. Any other * strategy needs a `param`, from some source, that names one of the * operation's query parameters. An override that fails validation — unknown * strategy, missing or undeclared parameter, one parameter as both `param` * and `limitParam`, a `pageStart` under a strategy other than `page`, a * `dataPath` that does not reach an array, an `endOfIteration` whose path * does not resolve in the primary response to a field of its kind's type, * malformed field — is reported with an `[oagen] Warning:` and ignored, * leaving the detected metadata as is. */ interface PaginationHint { strategy?: PaginationStrategy | 'none'; /** Query parameter that selects the page (cursor, offset, or page number). */ param?: string; /** Query parameter that sets the page size; not the one `param` names. */ limitParam?: string; /** * First page number the API expects (`page` strategy only; set under * another strategy, it makes the override unusable). Defaults to the page * parameter's integer `default`, else its `minimum`, else 1. */ pageStart?: number; /** * Dotted path to the data array inside the response. Resolved against the * response, so the array's element type — not the wrapper — becomes * `itemType`. */ dataPath?: string; /** * Response field that ends the iteration. Its `path` must resolve in the * primary response to a field whose type fits its `kind` — a boolean for * `hasMore`, an integer or number for `totalPages` and `totalCount` — or * the override is unusable. */ endOfIteration?: PaginationEndOfIteration; } interface SplitHint { /** Wrapper method name (snake_case). */ name: string; /** The discriminated union variant model name (e.g. 'PasswordSessionAuthenticateRequest'). */ targetVariant: string; /** Constant body fields injected by the wrapper. */ defaults?: Record; /** Fields the SDK reads from client config at runtime. */ inferFromClient?: string[]; /** Only these body fields are exposed as method params. If omitted, all non-default/non-inferred fields are exposed. */ exposedParams?: string[]; /** * Subset of exposedParams that should be emitted as optional even when the * variant model would otherwise mark them required (or when the variant has * no addressable model, as happens for inline oneOf branches). */ optionalParams?: string[]; } //#endregion //#region src/parser/parse.d.ts /** * A bundled OpenAPI document, post-`$ref` resolution but pre-IR extraction. * * This is the shape the spec author wrote, with external refs inlined and * internal refs left intact. It is intentionally loose (`Record`) so `transformSpec` can reach arbitrary spec extensions without * fighting types — narrow with `as` at use sites. */ type OpenApiDocument = Record; interface ParseOptions { operationIdTransform?: (id: string) => string; /** * Custom transform for schema (model/enum) names. Receives the cleaned * PascalCase name and, for component schemas, the original name as spelled * in the document. Returning `originalName` opts out of normalization. * See `SchemaExtractionOptions.schemaNameTransform`. */ schemaNameTransform?: SchemaNameTransform; /** * Domain-facing field-name overrides, keyed by IR model name then wire field * name: `{ Connection: { connection_type: 'type' } }`. Sets `Field.domainName` * so emitters expose the field under the friendlier name while keeping the * wire key. Language-agnostic — honored by any emitter that reads `domainName`. */ fieldHints?: Record>; /** * Per-operation overrides keyed by "METHOD /path" — the same map * `resolveOperations` reads. The parser applies only each hint's * `pagination`, which wins over the operation's `x-pagination` extension * and over name-based detection (see `PaginationHint`). */ operationHints?: Record; /** * Fold the models materialized for inline error bodies onto shared models * named by shape (`ErrorBody`, `ErrorBodyWithCode`, the enum `ErrorBodyCode`; * see `collapseErrorBodies`). On by default; `false` keeps one model per * operation and status code (`Error`). */ collapseErrorBodies?: boolean; /** * Pre-IR overlay applied to the bundled OpenAPI document before any IR * extraction runs. Use this when the upstream spec can't be changed but you * need to patch around a spec quirk that would otherwise emit a breaking SDK * change — e.g. rewriting a path's response `$ref` back to its prior schema, * merging the new fields onto the prior schema, and dropping the fork. * * The function may mutate the document in place and return it, or return a * new object; the returned value is what the rest of oagen sees. * * Runs once, after `$ref` bundling and before schema/operation extraction. * If you need to inspect the resulting IR instead, post-process the * `ApiSpec` returned by `parseSpec`. */ transformSpec?: (spec: OpenApiDocument) => OpenApiDocument; } export declare function parseSpec(specPath: string, options?: ParseOptions): Promise; //#endregion //#region src/utils/naming.d.ts export declare function toCamelCase(s: string, acronyms?: Set): string; export declare function toSnakeCase(s: string): string; //#endregion //#region scripts/smoke/shared.d.ts export interface ExchangeProvenance { resolutionTier: 'exact' | 'crud-prefix' | 'fuzzy' | 'manifest'; resolutionConfidence: number; sdkMethodName: string; captureIndex: number; totalCaptures: number; } export interface CapturedExchange { operationId: string; service: string; operationName: string; request: { method: string; path: string; queryParams: Record; body: unknown | null; }; response: { status: number; body: unknown | null; }; outcome: 'success' | 'api-error' | 'skipped'; error?: string; /** * True when the operation's declared responses do not cover the response * status: no explicit code, no `1XX`–`5XX` range containing it and no * `default` response. See `isUnexpectedStatus`. */ unexpectedStatus?: boolean; /** * The explicit status codes the operation declares (`ExpectedStatuses.codes`: * every declared 2xx/3xx code and every `errors` code; nothing is implied * from the HTTP method). A range or `default` response is not listed here; * `expectedStatuses` carries those. */ expectedStatusCodes?: number[]; /** * Everything the operation's declared responses cover — the explicit * codes, the `1XX`–`5XX` ranges and whether a `default` response exists — * as `unexpectedStatus` was decided against it. `expectedStatusCodes` is * its `codes` list. */ expectedStatuses?: ExpectedStatuses; durationMs: number; /** How the SDK method was resolved and which capture was selected */ provenance?: ExchangeProvenance; } export interface SmokeResults { source: 'raw' | 'spec-baseline' | `sdk-${string}`; timestamp: string; specVersion: string; exchanges: CapturedExchange[]; } export interface PlannedOperation { service: string; operation: Operation; } export interface PlannedGroup { service: string; operations: PlannedOperation[]; } /** Operations that require complex preconditions and can't be auto-tested */ export declare let SKIP_OPERATIONS: Set; /** Services to skip entirely */ export declare let SKIP_SERVICES: Set; /** * Map IR service names to SDK property names on the client object. * Empty = use toCamelCase(serviceName) as fallback. */ export declare let SERVICE_PROPERTY_MAP: Record; export interface SmokeConfig { skipOperations: string[]; skipServices: string[]; servicePriority: Record; servicePropertyMap: Record; } /** Load smoke test configuration from a JSON file */ export declare function loadSmokeConfig(configPath?: string): void; /** Return the current smoke config values (for diff.ts to consume) */ export declare function getSmokeConfig(): { skipOperations: Set; skipServices: Set; servicePriority: Record; servicePropertyMap: Record; }; export declare function planOperations(spec: ApiSpec): PlannedGroup[]; /** * A single wave of operations that can be planned and executed together. * Wave 0 contains parameterless operations. Subsequent waves contain * operations whose path params became resolvable after earlier waves ran. */ export interface OperationWave { /** Operations in this wave, with pre-resolved path params */ calls: Array<{ op: Operation; irService: string; pathParams: Record; }>; } /** * Plan operations in waves so that batched runners can execute each wave, * extract IDs from responses, then plan the next wave. * * Returns an iterator that yields one wave at a time. The caller must * execute each wave and populate the IdRegistry before calling next(). * * @param groups - service groups from planOperations() * @param ids - the IdRegistry (mutated by the caller between waves) * @param resolveMethod - optional filter; return null to skip an operation */ export declare function planWaves(groups: PlannedGroup[], ids: IdRegistry, resolveMethod?: (op: Operation, irService: string) => boolean): Generator; export declare function generateFixtureValue(typeRef: TypeRef, fieldName: string, spec: ApiSpec): unknown; /** Generate a snake_case request body payload from an operation's requestBody type */ export declare function generatePayload(op: Operation, spec: ApiSpec): Record | null; /** Generate a camelCase payload for SDK method calls */ export declare function generateCamelPayload(op: Operation, spec: ApiSpec): Record | null; /** Generate query params for an operation (required params only, plus limit=1 for lists) */ export declare function generateQueryParams(op: Operation, spec: ApiSpec): Record; /** Generate camelCase query params for SDK method calls */ export declare function generateCamelQueryParams(op: Operation, spec: ApiSpec): Record; export declare class IdRegistry { private ids; set(service: string, field: string, value: string): void; get(service: string, field: string): string | undefined; /** Resolve path parameters for an operation using stored IDs */ resolvePathParams(op: Operation, service: string): Record | null; /** Try to find a param value across all services */ private findAcrossServices; /** * Resolve a path param like "organizationId" by mapping it to the * service that stores that entity's ID (e.g. Organizations.id). * Also handles snake_case suffixed with _id by stripping the suffix * and looking up the pluralized service name. */ private resolveFromParamName; /** * Find a value by looking for any service name that ends with the given suffix. * e.g. suffix "Users" matches "UserManagementUsers.id" */ private findByServiceSuffix; /** * Last-resort fallback: use the spec's example or default value for a parameter. * Many path params (e.g. actionName, slug, type) have example values in the spec. */ private resolveFromExample; /** * Extract IDs from a response body and store them. * @param isTopLevel - true for operations without path params (their `id` belongs to this service). * false for sub-resource operations (their `id` is a child entity, don't overwrite). */ extractAndStore(service: string, responseBody: unknown, isTopLevel?: boolean): void; /** Extract fields ending in _id or Id and store them for cross-service resolution */ private extractNestedIds; } /** * The statuses an operation's declared responses cover, read from every * response kind the IR carries: the explicit success and error codes, the * `1XX`–`5XX` range responses and the `default` response. */ export interface ExpectedStatuses { /** * The explicit status codes, ascending and without duplicates: every * declared 2xx/3xx code (`responseStatusCode`, the primary success * response's, plus every `successResponses` entry) and every `errors` * code. An operation that declares no 2xx or 3xx response contributes no * success code: nothing is implied from the HTTP method. */ codes: number[]; /** * The `rangeResponses` keys, in declaration order. A range covers every * status in its hundred (`4XX` covers 400–499). */ ranges: StatusRange[]; /** * Whether the operation declares a `default` response, which covers every * status that `codes` and `ranges` do not. */ hasDefault: boolean; } /** * Read every status an operation's declared responses cover. Both * `getExpectedStatusCodes` and `isUnexpectedStatus` go through this, so the * one place that decides what counts as declared is here. */ export declare function getExpectedStatuses(op: Operation): ExpectedStatuses; /** * Whether `expected` covers `status`, resolved the way OpenAPI resolves a * status: an explicit code, else the range whose hundred contains it, else * `default`. */ export declare function coversStatus(expected: ExpectedStatuses, status: number): boolean; /** * The explicit status codes an operation declares — `getExpectedStatuses(op).codes` * alone. A range or `default` response cannot be expressed as a code and is * not listed, so this does not say whether a status is covered; * `isUnexpectedStatus` does. */ export declare function getExpectedStatusCodes(op: Operation): number[]; /** * `expected` as one token per entry, `/`-joined: `200/404/4XX/default`; an * operation that declares no responses covers nothing and reads * `none (no responses declared)`. */ export declare function formatExpectedStatuses(expected: ExpectedStatuses): string; /** * Whether the operation's declared responses leave `status` uncovered: no * explicit code, no range containing it and no `default` response. A status * of 0 is never unexpected — it marks a skipped call or a network error, not * a status mismatch. */ export declare function isUnexpectedStatus(status: number, op: Operation): boolean; /** One request the raw runner sends, with the labels its exchange is recorded under. */ export interface RawRequest { operationId: string; service: string; /** The HTTP method as sent, upper-case. */ method: string; /** The resolved path, recorded as `request.path`. */ path: string; /** The full URL to request, query string included. */ url: string; /** The query parameters, recorded as `request.queryParams`. */ queryParams: Record; /** The JSON body: sent on POST, PUT and PATCH, recorded as `request.body` either way. */ body: unknown | null; headers: Record; } export interface CaptureRawOptions { /** The `fetch` to send with; `globalThis.fetch` by default. A test passes a stub. */ fetchImpl?: typeof fetch; /** Milliseconds before the request is aborted; 30 000 by default. */ timeoutMs?: number; } /** * Send one request and record what came back as a `CapturedExchange`. * * Redirects are never followed (`redirect: 'manual'`): the exchange records * the operation's own response — the first hop — so a declared `302` is * recorded as 302 and judged like any other status by `isUnexpectedStatus`, * and a redirect the document does not declare is reported as unexpected * instead of being hidden behind its target's 200. The redirect target is * never requested. (Node's `fetch` returns a manual redirect with its real * status and `Location` header.) * * A 4xx or 5xx is an `api-error` exchange with `error: 'HTTP '`; a * `fetch` that throws (timeout, DNS, connection refused) is an `api-error` * with status 0 and the error message, which is never an unexpected status. * The response body is read as JSON and recorded as null when it is not. */ export declare function captureRawExchange(op: Operation, request: RawRequest, options?: CaptureRawOptions): Promise; export declare function resolvePath(op: Operation, pathParams: Record): string; export declare function delay(ms: number): Promise; export declare function parseCliArgs(): { spec: string; sdkPath?: string; smokeConfig?: string; }; //#endregion export type { StatusRange }; //# sourceMappingURL=smoke.d.mts.map