Comprehensive tooling for working with OpenAPI definitions
npx @tessl/cli install tessl/npm-oas@28.1.00
# OAS
1
2
OAS is a comprehensive TypeScript library for working with OpenAPI definitions. It provides parsing, validation, operation discovery, parameter handling, security analysis, and extensive manipulation tools for OpenAPI 3.0/3.1 specifications. The library is designed for maximum reusability across CLI tools, documentation systems, code generation, request execution, and any application requiring robust OpenAPI definition processing.
3
4
## Package Information
5
6
- **Package Name**: oas
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install oas`
10
11
## Core Imports
12
13
```typescript
14
import Oas from "oas";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const Oas = require("oas");
21
```
22
23
Additional imports for specific functionality:
24
25
```typescript
26
import { Operation, Callback, Webhook } from "oas/operation";
27
import analyzer from "oas/analyzer";
28
import reducer from "oas/reducer";
29
import { findSchemaDefinition, matchesMimeType, supportedMethods, jsonSchemaTypes } from "oas/utils";
30
import { isRef, isOAS31, isSchema, type OASDocument, type HttpMethods, type SecurityType, type User } from "oas/types";
31
```
32
33
## Basic Usage
34
35
```typescript
36
import Oas from "oas";
37
38
// Load an OpenAPI definition
39
const oas = new Oas({
40
openapi: "3.1.0",
41
info: { title: "My API", version: "1.0.0" },
42
servers: [{ url: "https://api.example.com" }],
43
paths: {
44
"/users/{id}": {
45
get: {
46
operationId: "getUser",
47
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
48
responses: { "200": { description: "User found" } }
49
}
50
}
51
}
52
});
53
54
// Get server URL
55
const serverUrl = oas.url(); // "https://api.example.com"
56
57
// Find an operation
58
const operation = oas.operation("/users/{id}", "get");
59
console.log(operation.getSummary());
60
console.log(operation.getParameters());
61
62
// Get operation by URL
63
const foundOp = oas.getOperation("https://api.example.com/users/123", "get");
64
console.log(foundOp?.getOperationId()); // "getUser"
65
```
66
67
## Architecture
68
69
OAS is built around several key components:
70
71
- **Core API**: `Oas` class for parsing and manipulating OpenAPI specifications
72
- **Operation System**: `Operation`, `Callback`, and `Webhook` classes for detailed operation analysis
73
- **Discovery Engine**: URL-based operation matching and parameter extraction
74
- **Type System**: Complete TypeScript definitions with full OpenAPI 3.0/3.1 support
75
- **Analysis Tools**: Feature detection and complexity measurement utilities
76
- **Transformation Pipeline**: Schema dereferencing, reduction, and manipulation tools
77
78
## Capabilities
79
80
### OpenAPI Definition Management
81
82
Core functionality for loading, parsing, and accessing OpenAPI definitions with full 3.0/3.1 support.
83
84
```typescript { .api }
85
class Oas {
86
constructor(oas: OASDocument | string, user?: User);
87
static init(oas: OASDocument | Record<string, unknown>, user?: User): Oas;
88
static hasOperationId(schema: OperationObject): boolean;
89
static getOperationId(path: string, method: string, schema: OperationObject, opts?: OperationIDGeneratorOptions): string;
90
getVersion(): string;
91
getDefinition(): OASDocument;
92
getPaths(): Record<string, Record<HttpMethods, Operation | Webhook>>;
93
getWebhooks(): Record<string, Record<HttpMethods, Webhook>>;
94
getTags(setIfMissing?: boolean): string[];
95
}
96
```
97
98
[OpenAPI Definition Management](./openapi-definition-management.md)
99
100
### Server and URL Management
101
102
Server URL handling with variable substitution, templating, and multi-server support.
103
104
```typescript { .api }
105
url(selected?: number, variables?: ServerVariable): string;
106
variables(selected?: number): ServerVariablesObject;
107
defaultVariables(selected?: number): ServerVariable;
108
replaceUrl(url: string, variables?: ServerVariable): string;
109
splitVariables(baseUrl: string): Servers | false;
110
```
111
112
[Server and URL Management](./server-url-management.md)
113
114
### Operation Discovery and Analysis
115
116
Advanced operation discovery by URL, method, operationId, and comprehensive operation analysis.
117
118
```typescript { .api }
119
operation(path: string, method: HttpMethods, opts?: { isWebhook?: boolean }): Operation;
120
findOperation(url: string, method: HttpMethods): PathMatch;
121
getOperation(url: string, method: HttpMethods): Operation;
122
getOperationById(id: string): Operation | Webhook;
123
```
124
125
[Operation Discovery and Analysis](./operation-discovery-analysis.md)
126
127
### Parameter Handling and JSON Schema
128
129
Parameter extraction, JSON Schema conversion, and type-safe parameter processing.
130
131
```typescript { .api }
132
interface Operation {
133
getParameters(): ParameterObject[];
134
getParametersAsJSONSchema(opts?: getParametersAsJSONSchemaOptions): SchemaWrapper[];
135
hasParameters(): boolean;
136
hasRequiredParameters(): boolean;
137
}
138
```
139
140
[Parameter Handling and JSON Schema](./parameter-handling-json-schema.md)
141
142
### Request and Response Management
143
144
Comprehensive request body and response handling with content type detection and examples.
145
146
```typescript { .api }
147
interface Operation {
148
hasRequestBody(): boolean;
149
getRequestBody(mediaType?: string): MediaTypeObject | false | [string, MediaTypeObject, ...string[]];
150
getResponseByStatusCode(statusCode: number | string): ResponseObject | boolean;
151
getResponseAsJSONSchema(statusCode: number | string, opts?: object): SchemaObject;
152
}
153
```
154
155
[Request and Response Management](./request-response-management.md)
156
157
### Security and Authentication
158
159
Security scheme parsing, authentication handling, and user-based auth token extraction.
160
161
```typescript { .api }
162
interface Operation {
163
getSecurity(): SecurityRequirementObject[];
164
getSecurityWithTypes(filterInvalid?: boolean): Array<Array<{security: KeyedSecuritySchemeObject, type: SecurityType} | false> | false>;
165
prepareSecurity(): Record<SecurityType, KeyedSecuritySchemeObject[]>;
166
}
167
168
getAuth(user: User, selectedApp?: number | string): AuthForHAR;
169
```
170
171
[Security and Authentication](./security-authentication.md)
172
173
### Schema Dereferencing and References
174
175
Advanced schema dereferencing with circular reference detection and resolution.
176
177
```typescript { .api }
178
dereference(opts?: {
179
cb?: () => void;
180
preserveRefAsJSONSchemaTitle?: boolean;
181
}): Promise<any>;
182
getCircularReferences(): string[];
183
```
184
185
[Schema Dereferencing and References](./schema-dereferencing-references.md)
186
187
### Analysis and Metrics
188
189
API definition analysis, feature detection, and complexity measurement tools.
190
191
```typescript { .api }
192
function analyzer(definition: OASDocument): Promise<OASAnalysis>;
193
194
interface OASAnalysis {
195
general: {
196
dereferencedFileSize: OASAnalysisGeneral;
197
mediaTypes: OASAnalysisGeneral;
198
operationTotal: OASAnalysisGeneral;
199
rawFileSize: OASAnalysisGeneral;
200
securityTypes: OASAnalysisGeneral;
201
};
202
openapi: Record<string, OASAnalysisFeature>;
203
readme: Record<string, OASAnalysisFeature>;
204
}
205
```
206
207
[Analysis and Metrics](./analysis-metrics.md)
208
209
### API Definition Reduction
210
211
Tools for extracting subsets of large OpenAPI definitions by tags or specific paths.
212
213
```typescript { .api }
214
function reducer(definition: OASDocument, opts?: ReducerOptions): OASDocument;
215
216
interface ReducerOptions {
217
paths?: Record<string, string[] | '*'>;
218
tags?: string[];
219
}
220
```
221
222
[API Definition Reduction](./api-definition-reduction.md)
223
224
### Extensions and Customization
225
226
ReadMe-specific OpenAPI extensions with validation and configuration management.
227
228
```typescript { .api }
229
hasExtension(extension: string): boolean;
230
getExtension(extension: string | keyof Extensions, operation?: Operation): any;
231
validateExtension(extension: keyof Extensions): void;
232
validateExtensions(): void;
233
```
234
235
[Extensions and Customization](./extensions-customization.md)
236
237
### Utility Functions
238
239
Utility functions for schema manipulation, MIME type detection, and OpenAPI processing.
240
241
```typescript { .api }
242
function findSchemaDefinition(ref: string, api: OASDocument): any;
243
function matchesMimeType: {
244
formUrlEncoded(mimeType: string): boolean;
245
json(contentType: string): boolean;
246
multipart(contentType: string): boolean;
247
wildcard(contentType: string): boolean;
248
xml(contentType: string): boolean;
249
};
250
const jsonSchemaTypes: Record<keyof OASDocument, string>;
251
const supportedMethods: readonly string[];
252
```
253
254
[Utility Functions](./utils.md)
255
256
## Types
257
258
```typescript { .api }
259
type OASDocument = (OpenAPIV3_1.Document | OpenAPIV3.Document) & Record<string, unknown>;
260
type HttpMethods = 'get' | 'put' | 'post' | 'delete' | 'options' | 'head' | 'patch' | 'trace';
261
type SecurityType = 'apiKey' | 'Basic' | 'Bearer' | 'Cookie' | 'Header' | 'http' | 'OAuth2' | 'Query';
262
263
interface User {
264
[key: string]: unknown;
265
keys?: {
266
[key: string]: unknown;
267
name: number | string;
268
pass?: number | string;
269
user?: number | string;
270
}[];
271
}
272
273
interface PathMatch {
274
match?: Match<ParamData>;
275
operation: PathsObject;
276
url: {
277
method?: HttpMethods;
278
nonNormalizedPath: string;
279
origin: string;
280
path: string;
281
slugs: Record<string, string>;
282
};
283
}
284
285
interface PathMatches {
286
[x: string]: PathMatch[];
287
}
288
289
interface OperationObject {
290
operationId?: string;
291
summary?: string;
292
description?: string;
293
tags?: string[];
294
deprecated?: boolean;
295
security?: SecurityRequirementObject[];
296
parameters?: ParameterObject[];
297
requestBody?: RequestBodyObject;
298
responses: Record<string, ResponseObject>;
299
callbacks?: Record<string, CallbackObject>;
300
}
301
302
interface OperationIDGeneratorOptions {
303
camelCase?: boolean;
304
onlyUseExistingOperationIds?: boolean;
305
}
306
307
interface OASAnalysis {
308
general: {
309
dereferencedFileSize: OASAnalysisGeneral;
310
mediaTypes: OASAnalysisGeneral;
311
operationTotal: OASAnalysisGeneral;
312
rawFileSize: OASAnalysisGeneral;
313
securityTypes: OASAnalysisGeneral;
314
};
315
openapi: Record<string, OASAnalysisFeature>;
316
readme: Record<string, OASAnalysisFeature>;
317
}
318
319
interface OASAnalysisGeneral {
320
found: any;
321
}
322
323
interface OASAnalysisFeature {
324
present: boolean;
325
}
326
327
interface ReducerOptions {
328
paths?: Record<string, string[] | '*'>;
329
tags?: string[];
330
}
331
332
interface AuthForHAR {
333
[key: string]: any;
334
}
335
336
interface Servers {
337
selected: number;
338
variables: ServerVariable;
339
}
340
341
type ServerVariable = Record<
342
string,
343
{ default?: number | string }[] | Record<string, never> | number | string | { default?: number | string }
344
>;
345
346
type OAS31Document = OpenAPIV3_1.Document & Record<string, unknown>;
347
```