Tooling for converting, validating, and parsing OpenAPI, Swagger, and Postman API definitions
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Helper functions for type detection, schema validation, input processing, and URL handling that support the core OAS Normalize functionality.
Functions for detecting and identifying different types of inputs and API definition formats.
/**
* Determine the type of a given variable
* @param obj - Input to analyze
* @returns Input type or false if unrecognized
*/
function getType(obj: any): 'buffer' | 'json' | 'path' | 'string-json' | 'string-yaml' | 'url' | false;
/**
* Determine if a given variable is a Buffer
* @param obj - Object to test
* @returns True if obj is a Buffer
*/
function isBuffer(obj: any): boolean;Usage Examples:
import { getType, isBuffer } from "oas-normalize/lib/utils";
// Detect different input types
console.log(getType('https://api.example.com/spec.json')); // 'url'
console.log(getType('./local-spec.yaml')); // 'path'
console.log(getType('{"openapi": "3.0.0"}')); // 'string-json'
console.log(getType('openapi: 3.0.0\ninfo:')); // 'string-yaml'
console.log(getType({ openapi: '3.0.0' })); // 'json'
// Buffer detection
const buffer = Buffer.from('openapi: 3.0.0');
console.log(isBuffer(buffer)); // true
console.log(getType(buffer)); // 'buffer'Functions for identifying and validating different API specification formats.
/**
* Determine if a given schema is an OpenAPI definition
* @param schema - Schema object to test
* @returns True if schema is OpenAPI format
*/
function isOpenAPI(schema: Record<string, unknown>): boolean;
/**
* Determine if a given schema is a Swagger definition
* @param schema - Schema object to test
* @returns True if schema is Swagger format
*/
function isSwagger(schema: Record<string, unknown>): boolean;
/**
* Determine if a given schema is a Postman collection
* @param schema - Schema object to test
* @returns True if schema is Postman collection
*/
function isPostman(schema: Record<string, unknown>): boolean;
/**
* Determine if a given schema is any supported API definition
* @param schema - Schema object to test
* @returns True if schema is a supported API format
*/
function isAPIDefinition(schema: Record<string, unknown>): boolean;
/**
* Retrieve the specific type of API definition
* @param schema - Schema object to analyze
* @returns Specific API definition type
*/
function getAPIDefinitionType(schema: Record<string, unknown>): 'openapi' | 'postman' | 'swagger' | 'unknown';Usage Examples:
import {
isOpenAPI,
isSwagger,
isPostman,
isAPIDefinition,
getAPIDefinitionType
} from "oas-normalize/lib/utils";
// OpenAPI detection
const openapi = { openapi: '3.0.0', info: { title: 'API' } };
console.log(isOpenAPI(openapi)); // true
console.log(getAPIDefinitionType(openapi)); // 'openapi'
// Swagger detection
const swagger = { swagger: '2.0', info: { title: 'API' } };
console.log(isSwagger(swagger)); // true
console.log(getAPIDefinitionType(swagger)); // 'swagger'
// Postman collection detection
const postman = {
info: { name: 'Collection' },
item: [{ name: 'Request' }]
};
console.log(isPostman(postman)); // true
console.log(getAPIDefinitionType(postman)); // 'postman'
// Generic API definition check
console.log(isAPIDefinition(openapi)); // true
console.log(isAPIDefinition(swagger)); // true
console.log(isAPIDefinition(postman)); // true
console.log(isAPIDefinition({ random: 'object' })); // falseFunctions for converting and processing different data formats.
/**
* Convert a YAML blob or stringified JSON object into a JSON object
* @param string - Input string or object to convert
* @returns Parsed JSON object
*/
function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown>;Usage Examples:
import { stringToJSON } from "oas-normalize/lib/utils";
// JSON string conversion
const jsonString = '{"openapi": "3.0.0", "info": {"title": "API"}}';
const jsonObj = stringToJSON(jsonString);
console.log(jsonObj.openapi); // "3.0.0"
// YAML string conversion
const yamlString = `
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/users:
get:
summary: List users
`;
const yamlObj = stringToJSON(yamlString);
console.log(yamlObj.info.title); // "My API"
// Object pass-through
const existingObj = { openapi: '3.1.0' };
const result = stringToJSON(existingObj);
console.log(result === existingObj); // true (same reference)Functions for preparing and processing URLs for API requests.
/**
* Deconstruct a URL into a payload for a fetch request
* Handles authentication and GitHub URL conversion
* @param url - URL to prepare
* @returns Object with processed URL and fetch options
*/
function prepareURL(url: string): {
options: RequestInit;
url: string;
};Usage Examples:
import { prepareURL } from "oas-normalize/lib/utils";
// Basic URL preparation
const basic = prepareURL('https://api.example.com/openapi.json');
console.log(basic.url); // "https://api.example.com/openapi.json"
console.log(basic.options); // {}
// URL with authentication
const withAuth = prepareURL('https://user:pass@api.example.com/spec.yaml');
console.log(withAuth.url); // "https://api.example.com/spec.yaml" (credentials removed)
console.log(withAuth.options.headers); // { Authorization: "Basic dXNlcjpwYXNz" }
// GitHub blob URL conversion
const github = prepareURL('https://github.com/user/repo/blob/main/openapi.yaml');
console.log(github.url); // "https://raw.githubusercontent.com/user/repo/main/openapi.yaml"
console.log(github.options); // {}The getType function uses several heuristics to determine input type:
// Detection logic examples
getType(Buffer.from('data')); // 'buffer' - Uses isBuffer check
getType({ key: 'value' }); // 'json' - Object type
getType('{"key": "value"}'); // 'string-json' - Starts with whitespace + '{'
getType('key: value\nother: data'); // 'string-yaml' - Contains newlines
getType('https://example.com'); // 'url' - Starts with 'http'
getType('./file.yaml'); // 'path' - Default for strings not matching above
getType(123); // false - Unsupported typeEach format has specific detection logic:
// OpenAPI detection - looks for 'openapi' property
isOpenAPI({ openapi: '3.0.0' }); // true
isOpenAPI({ swagger: '2.0' }); // false
// Swagger detection - looks for 'swagger' property
isSwagger({ swagger: '2.0' }); // true
isSwagger({ openapi: '3.0.0' }); // false
// Postman detection - requires both 'info' and 'item' properties
isPostman({ info: {}, item: [] }); // true
isPostman({ info: {} }); // false (missing item)
isPostman({ item: [] }); // false (missing info)The prepareURL function handles several URL transformations:
// Authentication extraction
const authUrl = 'https://user:password@api.example.com/spec.json';
const prepared = prepareURL(authUrl);
// URL: "https://api.example.com/spec.json"
// Options: { headers: { Authorization: "Basic dXNlcjpwYXNzd29yZA==" } }
// GitHub blob to raw conversion
const blobUrl = 'https://github.com/owner/repo/blob/branch/file.yaml';
const githubPrepared = prepareURL(blobUrl);
// URL: "https://raw.githubusercontent.com/owner/repo/branch/file.yaml"
// Regular URLs pass through unchanged
const normalUrl = 'https://api.example.com/openapi.json';
const normalPrepared = prepareURL(normalUrl);
// URL: unchanged, Options: {}import { getType, stringToJSON, isAPIDefinition } from "oas-normalize/lib/utils";
function processAPIInput(input: any): Record<string, unknown> {
const inputType = getType(input);
switch (inputType) {
case 'json':
return input;
case 'string-json':
case 'string-yaml':
return stringToJSON(input);
case 'buffer':
return stringToJSON(input.toString());
case 'url':
throw new Error('URL inputs require async processing');
case 'path':
throw new Error('Path inputs require file system access');
default:
throw new Error(`Unsupported input type: ${inputType || 'unknown'}`);
}
}
// Usage
try {
const schema = processAPIInput('{"openapi": "3.0.0"}');
if (isAPIDefinition(schema)) {
console.log('Valid API definition detected');
}
} catch (error) {
console.error('Input processing failed:', error.message);
}import { isOpenAPI, isSwagger, isPostman } from "oas-normalize/lib/utils";
function analyzeAPIFormat(schema: Record<string, unknown>) {
const analysis = {
format: 'unknown',
version: 'unknown',
features: [] as string[]
};
if (isOpenAPI(schema)) {
analysis.format = 'openapi';
analysis.version = (schema.openapi as string) || 'unknown';
if (schema.webhooks) analysis.features.push('webhooks');
if (schema.components?.callbacks) analysis.features.push('callbacks');
} else if (isSwagger(schema)) {
analysis.format = 'swagger';
analysis.version = (schema.swagger as string) || 'unknown';
if (schema.definitions) analysis.features.push('definitions');
if (schema.securityDefinitions) analysis.features.push('security');
} else if (isPostman(schema)) {
analysis.format = 'postman';
// Extract version from schema URL if available
const schemaUrl = (schema.info as any)?.schema;
if (schemaUrl) {
const versionMatch = schemaUrl.match(/v([0-9.]+)/);
if (versionMatch) analysis.version = versionMatch[1];
}
if ((schema.auth as any)) analysis.features.push('authentication');
if ((schema.variable as any)) analysis.features.push('variables');
}
return analysis;
}
// Usage
const analysis = analyzeAPIFormat(apiSpec);
console.log(`Format: ${analysis.format} v${analysis.version}`);
console.log(`Features: ${analysis.features.join(', ')}`);import { prepareURL } from "oas-normalize/lib/utils";
async function fetchAPISpec(url: string): Promise<Record<string, unknown>> {
const { url: processedUrl, options } = prepareURL(url);
try {
const response = await fetch(processedUrl, {
...options,
headers: {
'Accept': 'application/json, application/yaml, text/yaml',
...options.headers
}
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const contentType = response.headers.get('content-type') || '';
const text = await response.text();
// Process based on content type
if (contentType.includes('json')) {
return JSON.parse(text);
} else {
// Assume YAML for other content types
return stringToJSON(text);
}
} catch (error) {
throw new Error(`Failed to fetch API spec from ${url}: ${error.message}`);
}
}
// Usage
try {
const spec = await fetchAPISpec('https://github.com/user/repo/blob/main/api.yaml');
console.log('Successfully fetched and parsed API spec');
} catch (error) {
console.error('Fetch failed:', error.message);
}Install with Tessl CLI
npx tessl i tessl/npm-oas-normalize