or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bundling.mddereferencing.mderrors.mdindex.mdoptions.mdparsing.mdresolution.md
tile.json

dereferencing.mddocs/

Schema Dereferencing

Fully dereferences all $ref pointers by replacing them with their resolved values, creating a self-contained schema object without any references. This results in a schema that can be easily crawled and used programmatically, but introduces the risk of circular references during serialization.

Capabilities

Dereference Function (Static)

Dereferences all $ref pointers in the JSON Schema, replacing each reference with its resolved value.

/**
 * Dereferences all $ref pointers by replacing them with resolved values
 * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
 * @returns Promise that resolves with the fully dereferenced schema object
 */
function dereference<S extends object = JSONSchema>(
  schema: S | string | unknown
): Promise<S>;

/**
 * Dereferences with callback support
 * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
 * @param callback - Error-first callback receiving the dereferenced schema
 * @returns Promise that resolves to void when using callback
 */
function dereference<S extends object = JSONSchema>(
  schema: S | string | unknown,
  callback: SchemaCallback<S>
): Promise<void>;

/**
 * Dereferences with custom options
 * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
 * @param options - Options that determine how the schema is dereferenced
 * @returns Promise that resolves with the dereferenced schema object
 */
function dereference<S extends object = JSONSchema>(
  schema: S | string | unknown,
  options: ParserOptions<S>
): Promise<S>;

/**
 * Dereferences with options and callback
 * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
 * @param options - Options that determine how the schema is dereferenced
 * @param callback - Error-first callback receiving the dereferenced schema
 * @returns Promise that resolves to void when using callback
 */
function dereference<S extends object = JSONSchema>(
  schema: S | string | unknown,
  options: ParserOptions<S>,
  callback: SchemaCallback<S>
): Promise<void>;

/**
 * Dereferences schema at specific path with separate schema object
 * @param path - The file path or URL of the JSON schema
 * @param schema - A JSON schema object to use instead of reading from path
 * @param options - Options that determine how the schema is dereferenced
 * @returns Promise that resolves with the dereferenced schema object
 */
function dereference<S extends object = JSONSchema>(
  path: string,
  schema: S | string | unknown,
  options: ParserOptions<S>
): Promise<S>;

/**
 * Dereferences with path, schema, options, and callback
 * @param path - The file path or URL of the JSON schema
 * @param schema - A JSON schema object to use instead of reading from path
 * @param options - Options that determine how the schema is dereferenced
 * @param callback - Error-first callback receiving the dereferenced schema
 * @returns Promise that resolves to void when using callback
 */
function dereference<S extends object = JSONSchema>(
  path: string,
  schema: S | string | unknown,
  options: ParserOptions<S>,
  callback: SchemaCallback<S>
): Promise<void>;

Dereference Method (Instance)

Instance method on $RefParser class for dereferencing schemas.

class $RefParser<S extends object = JSONSchema> {
  schema: S | null;
  $refs: $Refs<S>;
  
  /**
   * Dereferences all $ref pointers and updates instance schema property
   * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
   * @returns Promise that resolves with the dereferenced schema object
   */
  dereference(schema: S | string | unknown): Promise<S>;
  
  /**
   * Dereferences with callback support
   * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
   * @param callback - Error-first callback receiving the dereferenced schema
   * @returns Promise that resolves to void when using callback
   */
  dereference(schema: S | string | unknown, callback: SchemaCallback<S>): Promise<void>;
  
  /**
   * Dereferences with custom options
   * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
   * @param options - Options that determine how the schema is dereferenced
   * @returns Promise that resolves with the dereferenced schema object
   */
  dereference(schema: S | string | unknown, options: ParserOptions<S>): Promise<S>;
  
  /**
   * Dereferences with options and callback
   * @param schema - A JSON Schema object, or the file path or URL of a JSON Schema file
   * @param options - Options that determine how the schema is dereferenced
   * @param callback - Error-first callback receiving the dereferenced schema
   * @returns Promise that resolves to void when using callback
   */
  dereference(schema: S | string | unknown, options: ParserOptions<S>, callback: SchemaCallback<S>): Promise<void>;
  
  /**
   * Dereferences schema at specific path with separate schema object
   * @param path - The file path or URL of the JSON schema
   * @param schema - A JSON schema object to use instead of reading from path
   * @param options - Options that determine how the schema is dereferenced
   * @returns Promise that resolves with the dereferenced schema object
   */
  dereference(path: string, schema: S | string | unknown, options: ParserOptions<S>): Promise<S>;
  
  /**
   * Dereferences with path, schema, options, and callback
   * @param path - The file path or URL of the JSON schema
   * @param schema - A JSON schema object to use instead of reading from path
   * @param options - Options that determine how the schema is dereferenced
   * @param callback - Error-first callback receiving the dereferenced schema
   * @returns Promise that resolves to void when using callback
   */
  dereference(path: string, schema: S | string | unknown, options: ParserOptions<S>, callback: SchemaCallback<S>): Promise<void>;
}

Usage Examples:

import $RefParser from "@apidevtools/json-schema-ref-parser";

// Basic dereferencing from file
const dereferenced = await $RefParser.dereference("./schemas/api.json");

// The dereferenced schema has all $ref pointers replaced with actual values
console.log("Fully dereferenced schema:", dereferenced);

// Instance-based dereferencing
const parser = new $RefParser();
await parser.dereference("./schemas/api.json");
console.log("Dereferenced schema:", parser.schema);

// Dereferencing with circular reference handling
const dereferencedWithCircular = await $RefParser.dereference("./schemas/circular.json", {
  dereference: {
    circular: true  // Allow circular references
  }
});

// Dereferencing with path exclusions
const selective = await $RefParser.dereference("./schemas/api.json", {
  dereference: {
    excludedPathMatcher: (path) => path.includes("preserve-ref")
  }
});

Dereference Options

interface DereferenceOptions {
  /**
   * Determines whether circular $ref pointers are handled
   * - false: Throw ReferenceError if circular references found
   * - true: Allow circular references (default)
   * - "ignore": Ignore circular references without error
   */
  circular?: boolean | "ignore";

  /**
   * Function to exclude certain paths from dereferencing
   * @param path - The path being processed (the $ref string)
   * @returns True to exclude this path and all subpaths from dereferencing
   */
  excludedPathMatcher?(path: string): boolean;

  /**
   * Callback invoked during circular reference detection
   * @param path - The path that is circular (the $ref string)
   */
  onCircular?(path: string): void;

  /**
   * Callback invoked during dereferencing process
   * @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 alongside a $ref pointer
   * Useful for OpenAPI 3.1 compliance where description/summary are preserved
   */
  preservedProperties?: string[];

  /**
   * Whether references should resolve relative to their directory or from cwd
   * - "relative": Resolve relative to the reference's directory (default)
   * - "root": Resolve from the current working directory
   */
  externalReferenceResolution?: "relative" | "root";
}

How Dereferencing Works

  1. Resolution Phase: First resolves all external $ref pointers to gather referenced content
  2. Dereferencing Phase: Replaces each $ref pointer with the actual resolved content
  3. Object Reference Equality: Maintains reference equality for objects pointed to by multiple $refs
  4. Circular Handling: Detects and handles circular reference patterns based on options

Before and After Example

Before Dereferencing:

{
  "type": "object",
  "properties": {
    "user": { "$ref": "#/definitions/User" },
    "manager": { "$ref": "#/definitions/User" }
  },
  "definitions": {
    "User": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "number" }
      }
    }
  }
}

After Dereferencing:

{
  "type": "object",
  "properties": {
    "user": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "number" }
      }
    },
    "manager": {
      "type": "object", 
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "number" }
      }
    }
  },
  "definitions": {
    "User": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "age": { "type": "number" }
      }
    }
  }
}

Note: In JavaScript, both user and manager properties would reference the same object instance, maintaining reference equality.

Circular Reference Handling

Dereferencing provides sophisticated circular reference handling:

Detect and Allow (default):

const schema = await $RefParser.dereference("circular-schema.json", {
  dereference: { circular: true }
});
// Circular references preserved as object references

Detect and Ignore:

const schema = await $RefParser.dereference("circular-schema.json", {
  dereference: { circular: "ignore" }
});
// Circular $refs left as-is, no dereferencing applied

Detect and Error:

try {
  const schema = await $RefParser.dereference("circular-schema.json", {
    dereference: { circular: false }
  });
} catch (error) {
  // ReferenceError thrown for circular references
}

Object Reference Equality

When multiple $ref pointers reference the same object, dereferencing maintains JavaScript object reference equality:

const dereferenced = await $RefParser.dereference(schema);

// Both properties reference the same object instance
console.log(dereferenced.properties.user === dereferenced.properties.manager); // true

This is beneficial for:

  • Memory efficiency (shared object instances)
  • Programmatic processing (identity checks work correctly)
  • Maintaining logical relationships between schema parts

Preserved Properties

For OpenAPI 3.1 compatibility, you can preserve properties alongside $ref pointers:

const schema = await $RefParser.dereference(openApiSchema, {
  dereference: {
    preservedProperties: ["description", "summary"]
  }
});

Benefits of Dereferencing

  • Programmatic Processing: Easy to traverse and analyze schema structure
  • Tool Compatibility: Works with tools that don't understand $ref pointers
  • Reference Equality: Shared object instances for identical references
  • Self-Contained: No external dependencies or reference resolution needed

Drawbacks of Dereferencing

  • Circular Reference Risk: Cannot safely use JSON.stringify() with circular references
  • Memory Usage: Larger memory footprint due to duplicated content
  • Lost Reference Information: Original $ref paths are no longer available

Error Handling

Dereferencing operations can encounter various errors:

  • ReferenceError: Circular references when circular: false
  • Resolution errors: Problems accessing referenced files
  • JSONParserError: Invalid schema structure
try {
  const dereferenced = await $RefParser.dereference("./schemas/api.json");
} catch (error) {
  if (error instanceof ReferenceError) {
    console.log("Circular reference detected:", error.message);
  } else if (error instanceof JSONParserError) {
    console.log("Schema error:", error.message);
    console.log("Error location:", error.path);
  }
}