Comprehensive configuration system for customizing parsing, resolution, bundling, and dereferencing behavior. The options system provides fine-grained control over every aspect of schema processing through a hierarchical configuration structure.
The primary configuration interface used across all operations.
/**
* Complete options interface for JSON Schema $Ref Parser operations
*/
interface $RefParserOptions<S extends object = JSONSchema> {
/**
* Parser configuration for different file formats
*/
parse: {
json?: Plugin | boolean;
yaml?: Plugin | boolean;
binary?: Plugin | boolean;
text?: Plugin | boolean;
[key: string]: Plugin | boolean | undefined;
};
/**
* Resolver configuration for different protocols and sources
*/
resolve: {
external?: boolean;
file?: Partial<ResolverOptions<S>> | boolean;
http?: HTTPResolverOptions<S> | boolean;
[key: string]: Partial<ResolverOptions<S>> | HTTPResolverOptions<S> | boolean | undefined;
};
/**
* Whether to continue processing when errors are encountered
*/
continueOnError: boolean;
/**
* Configuration for bundling operations
*/
bundle: BundleOptions;
/**
* Configuration for dereferencing operations
*/
dereference: DereferenceOptions;
/**
* Whether to clone the schema before processing (default: true)
*/
mutateInputSchema?: boolean;
/**
* Maximum processing time in milliseconds before timeout
*/
timeoutMs?: number;
}
/**
* User-friendly options interface with all properties optional
*/
type ParserOptions<S extends object = JSONSchema> = DeepPartial<$RefParserOptions<S>>;Configure how different file formats are parsed.
interface Plugin {
/**
* Parser name for identification
*/
name?: string;
/**
* Execution order relative to other parsers (lower runs first)
*/
order?: number;
/**
* Whether empty files are allowed (default: true)
*/
allowEmpty?: boolean;
/**
* Whether Byte Order Mark (BOM) is allowed (JSON only, default: true)
*/
allowBOM?: boolean;
/**
* Text encoding for file reading
*/
encoding?: BufferEncoding;
/**
* Determines which files this parser can handle
*/
canParse?: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
/**
* Parser implementation
*/
parse:
| ((file: FileInfo, callback?: (error: Error | null, data: string | null) => any) => unknown | Promise<unknown>)
| number
| string;
}Usage Examples:
// Custom parse configuration
const options = {
parse: {
json: true, // Enable JSON parser
yaml: false, // Disable YAML parser
text: { // Custom text parser config
encoding: "utf8",
allowEmpty: false
},
csv: { // Custom CSV parser
name: "csv-parser",
order: 200,
canParse: /\.csv$/i,
parse: (file) => {
// Custom CSV parsing logic
return parseCsv(file.data);
}
}
}
};Configure how different URL schemes and protocols are resolved.
/**
* Base resolver interface
*/
interface ResolverOptions<S extends object = JSONSchema> {
/**
* Resolver name for identification
*/
name?: string;
/**
* Execution order relative to other resolvers (lower runs first)
*/
order?: number;
/**
* Determines which URLs this resolver can handle
*/
canRead: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
/**
* Resolver implementation
*/
read:
| string
| object
| ((
file: FileInfo,
callback?: (error: Error | null, data: string | null) => any,
) => string | Buffer | S | Promise<string | Buffer | S>);
}
/**
* HTTP-specific resolver options
*/
interface HTTPResolverOptions<S extends object = JSONSchema> extends Partial<ResolverOptions<S>> {
/**
* HTTP headers to send with requests
*/
headers?: RequestInit["headers"] | null;
/**
* Request timeout in milliseconds (default: 5000)
*/
timeout?: number;
/**
* Maximum number of redirects to follow (default: 5)
*/
redirects?: number;
/**
* Send credentials for CORS requests (default: false)
*/
withCredentials?: boolean;
/**
* Allow unsafe URLs like localhost (default: true)
*/
safeUrlResolver?: boolean;
}Usage Examples:
// HTTP resolver configuration
const options = {
resolve: {
external: true, // Enable external reference resolution
file: true, // Enable file resolver
http: { // Custom HTTP resolver config
timeout: 10000, // 10 second timeout
headers: {
"Accept": "application/json",
"Authorization": "Bearer token123"
},
redirects: 3, // Follow up to 3 redirects
withCredentials: true
},
mongodb: { // Custom MongoDB resolver
name: "mongodb-resolver",
order: 100,
canRead: /^mongodb:/,
read: async (file) => {
// Custom MongoDB resolution logic
return await fetchFromMongoDB(file.url);
}
}
}
};Configure schema bundling behavior.
interface BundleOptions {
/**
* Function to exclude paths from bundling
* @param path - The path being processed (the $ref string)
* @returns True to exclude this path and subpaths from bundling
*/
excludedPathMatcher?(path: string): boolean;
/**
* Callback invoked during bundling
* @param path - The path being processed (the $ref string)
* @param value - The JSON-Schema that the $ref resolved to
* @param parent - The parent of the processed object
* @param parentPropName - The property name of the parent object
*/
onBundle?(
path: string,
value: JSONSchemaObject,
parent?: JSONSchemaObject,
parentPropName?: string
): void;
}Usage Examples:
const options = {
bundle: {
// Exclude internal references from bundling
excludedPathMatcher: (path) => {
return path.includes("/internal/") || path.endsWith(".internal.json");
},
// Log bundling progress
onBundle: (path, value, parent, propName) => {
console.log(`Bundling reference: ${path}`);
}
}
};Configure schema dereferencing behavior.
interface DereferenceOptions {
/**
* How to handle circular references
* - true: Allow circular references (default)
* - false: Throw error on circular references
* - "ignore": Ignore circular references
*/
circular?: boolean | "ignore";
/**
* Function to exclude paths from dereferencing
* @param path - The path being processed (the $ref string)
* @returns True to exclude this path and subpaths from dereferencing
*/
excludedPathMatcher?(path: string): boolean;
/**
* Callback invoked when circular references are detected
* @param path - The circular path (the $ref string)
*/
onCircular?(path: string): void;
/**
* Callback invoked during dereferencing
* @param path - The path being dereferenced (the $ref string)
* @param value - The JSON-Schema that the $ref resolved to
* @param parent - The parent of the dereferenced object
* @param parentPropName - The property name of the parent object
*/
onDereference?(
path: string,
value: JSONSchemaObject,
parent?: JSONSchemaObject,
parentPropName?: string
): void;
/**
* Properties to preserve when dereferencing a $ref schema
* Useful for OpenAPI 3.1 spec compliance
*/
preservedProperties?: string[];
/**
* Whether references resolve relative to their directory or root
* - "relative": Resolve relative to reference's directory (default)
* - "root": Resolve from current working directory
*/
externalReferenceResolution?: "relative" | "root";
}Usage Examples:
const options = {
dereference: {
circular: "ignore", // Ignore circular references
// Preserve OpenAPI properties
preservedProperties: ["description", "summary", "example"],
// Exclude certain paths from dereferencing
excludedPathMatcher: (path) => {
return path.includes("preserve-ref");
},
// Track circular references
onCircular: (path) => {
console.warn(`Circular reference detected: ${path}`);
},
// Log dereferencing progress
onDereference: (path, value) => {
console.log(`Dereferenced: ${path}`);
}
}
};Get and customize default configuration.
/**
* Returns the default parser options
* @returns Default $RefParserOptions object
*/
function getJsonSchemaRefParserDefaultOptions(): $RefParserOptions<JSONSchema>;
/**
* Creates new options by merging with defaults
* @param options - User options to merge with defaults
* @returns Merged options object
*/
function getNewOptions<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
options: O | undefined
): O & $RefParserOptions<S>;Usage Examples:
import { getJsonSchemaRefParserDefaultOptions } from "@apidevtools/json-schema-ref-parser";
// Get default options
const defaults = getJsonSchemaRefParserDefaultOptions();
console.log("Default options:", defaults);
// Customize specific options while keeping defaults
const customOptions = {
parse: {
yaml: false // Disable YAML parsing
},
resolve: {
http: {
timeout: 30000 // Increase HTTP timeout
}
}
};
const schema = await $RefParser.dereference("schema.json", customOptions);Information about files being processed by parsers and resolvers.
/**
* File information passed to parsers and resolvers
*/
interface FileInfo {
/**
* Full URL of the file (any protocol: http, https, file, custom, etc.)
*/
url: string;
/**
* URL fragment/hash including the # symbol (empty string if no hash)
*/
hash: string;
/**
* Lowercase file extension (.json, .yaml, .txt, etc.)
*/
extension: string;
/**
* Raw file contents as returned by the resolver
*/
data: string | Buffer;
}Options for controlling overall behavior across all operations.
interface GlobalOptions {
/**
* Continue processing when errors are encountered (default: false)
* When true, collects all errors and throws JSONParserErrorGroup
*/
continueOnError?: boolean;
/**
* Whether to mutate the input schema object (default: true)
* When false, creates a clone before processing
*/
mutateInputSchema?: boolean;
/**
* Maximum processing time in milliseconds before timeout
* Useful for preventing infinite loops or very slow operations
*/
timeoutMs?: number;
}Usage Examples:
// Error handling configuration
const options = {
continueOnError: true, // Collect all errors instead of failing fast
mutateInputSchema: false, // Don't modify original schema object
timeoutMs: 60000 // 1 minute timeout
};
try {
const result = await $RefParser.dereference("complex-schema.json", options);
} catch (error) {
if (error instanceof JSONParserErrorGroup) {
console.log("Multiple errors encountered:");
// Access individual errors through error.files.$refs
}
}Helper types for working with options.
/**
* Makes all properties of T optional recursively
*/
type DeepPartial<T> = T extends object
? {
[P in keyof T]?: DeepPartial<T[P]>;
}
: T;
/**
* Alias for the main options interface
*/
type Options<S extends object = JSONSchema> = $RefParserOptions<S>;import $RefParser, {
getJsonSchemaRefParserDefaultOptions,
type ParserOptions,
type JSONSchema
} from "@apidevtools/json-schema-ref-parser";
// Comprehensive configuration example
const comprehensiveOptions: ParserOptions<JSONSchema> = {
// Parser configuration
parse: {
json: { allowBOM: false },
yaml: true,
text: false,
binary: false
},
// Resolver configuration
resolve: {
external: true,
file: true,
http: {
timeout: 15000,
headers: { "User-Agent": "MyApp/1.0" },
redirects: 5,
safeUrlResolver: false
}
},
// Bundling configuration
bundle: {
excludedPathMatcher: (path) => path.includes("internal"),
onBundle: (path) => console.log(`Bundling: ${path}`)
},
// Dereferencing configuration
dereference: {
circular: true,
preservedProperties: ["description", "example"],
onCircular: (path) => console.warn(`Circular: ${path}`),
externalReferenceResolution: "relative"
},
// Global configuration
continueOnError: false,
mutateInputSchema: false,
timeoutMs: 120000
};
// Use comprehensive configuration
const result = await $RefParser.dereference("schema.json", comprehensiveOptions);