### Install JSON Schema $Ref Parser Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Install the library using npm, pnpm, or bun. This is the first step to using the parser. ```bash npm install @apidevtools/json-schema-ref-parser pnpm add @apidevtools/json-schema-ref-parser bun add @apidevtools/json-schema-ref-parser ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Installs the project dependencies using pnpm. Ensure pnpm is installed globally. ```bash pnpm install ``` -------------------------------- ### Create a Custom CSV Parser Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/parsers.md This example demonstrates how to create a simple custom parser for CSV files. It defines the `order`, `canParse`, and `parse` properties to handle CSV data and integrates it with the dereference function. ```javascript let myParser = { order: 1, canParse: ".csv", parse(file) { let lines = file.data.toString().split("\n"); return lines.map((line) => { return line.split(","); }); }, }; $RefParser.dereference(mySchema, { parse: { csv: myParser } }); ``` -------------------------------- ### Create a Custom MongoDB Resolver Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/resolvers.md This example shows how to create a custom resolver for MongoDB URLs. It defines the `order`, `canRead`, and `read` properties for the resolver and then uses it with `$RefParser.dereference`. ```javascript let myResolver = { order: 1, canRead: /^mongodb:/i, read(file, callback, $refs) { MongoClient.connect(file.url, (err, db) => { if (err) { callback(err); } else { db.find({}).toArray((err, document) => { callback(null, document); }); } } } }; $RefParser.dereference(mySchema, { resolve: { mongo: myResolver }}); ``` -------------------------------- ### Example JSON Schema with $ref Pointers Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md This JSON schema demonstrates various types of $ref pointers, including local file references, remote URL references, and internal schema references. ```json { "definitions": { "person": { "$ref": "schemas/people/Bruce-Wayne.json" }, "place": { "$ref": "schemas/places.yaml#/definitions/Gotham-City" }, "thing": { "$ref": "http://wayne-enterprises.com/things/batmobile" }, "color": { "$ref": "#/definitions/thing/properties/colors/black-as-the-night" } } } ``` -------------------------------- ### Node.js Fetch Polyfill Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Provides a polyfill for the fetch API for Node.js versions older than 18. Ensure node-fetch is installed. ```javascript import fetch from "node-fetch"; globalThis.fetch = fetch; ``` -------------------------------- ### get($ref) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Retrieves the value at a specified JSON Reference path within the schema. ```APIDOC ## get($ref) ### Description Gets the value at the given path in the schema. Throws an error if the path does not exist. ### Parameters #### Path Parameters - **$ref** (_required_) - `string`
The JSON Reference path, optionally with a JSON Pointer in the hash ### Return Value - `boolean`
Gets the value at the given path in the schema. Throws an error if the path does not exist. ### Example ```javascript let $refs = await $RefParser.resolve("my-schema.json"); let value = $refs.get("schemas/people/Bruce-Wayne.json#/properties/address"); ``` ``` -------------------------------- ### Get a Specific Value by Reference Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Retrieve the value at a given JSON Reference path using the `get()` method. An error is thrown if the specified path does not exist in the schema. ```javascript let $refs = await $RefParser.resolve("my-schema.json"); let value = $refs.get("schemas/people/Bruce-Wayne.json#/properties/address"); ``` -------------------------------- ### Get All Values from Schema Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Obtain a map of all paths and their corresponding values within the schema using the `values()` method. This is equivalent to calling `$refs.toJSON()`. ```javascript let $refs = await $RefParser.resolve("my-schema.json"); // Get ALL paths & values in the schema // (this is the same as $refs.toJSON()) let values = $refs.values(); values["schemas/people/Bruce-Wayne.json"]; values["schemas/places.yaml"]; values["http://wayne-enterprises.com/things/batmobile"]; ``` -------------------------------- ### Get All Paths from Schema Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Retrieve an array of all file paths and URLs present in the schema using the `paths()` method. You can optionally filter by type, such as 'file' or 'http'. ```javascript let $refs = await $RefParser.resolve("my-schema.json"); // Get the paths of ALL files in the schema $refs.paths(); // Get the paths of local files only $refs.paths("file"); // Get all URLs $refs.paths("http"); ``` -------------------------------- ### Dereference Schema with Custom Options Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/options.md Configure parsing, resolution, and dereferencing options for `$RefParser.dereference`. This example shows how to disable the JSON parser, set file parsing options, configure HTTP timeouts, and prevent circular $refs. ```javascript $RefParser.dereference("my-schema.yaml", { continueOnError: true, // Don't throw on the first error parse: { json: false, // Disable the JSON parser yaml: { allowEmpty: false, // Don't allow empty YAML files }, text: { canParse: [".txt", ".html"], // Parse .txt and .html files as plain text (strings) encoding: "utf16", // Use UTF-16 encoding }, }, resolve: { file: false, // Don't resolve local file references http: { timeout: 2000, // 2 second timeout withCredentials: true, // Include auth credentials when resolving HTTP references }, }, dereference: { circular: false, // Don't allow circular $refs excludedPathMatcher: ( path, // Skip dereferencing content under any 'example' key ) => path.includes("/example/"), onCircular: ( path, // Callback invoked during circular $ref detection ) => console.log(path), onDereference: ( path, value, // Callback invoked during dereferencing ) => console.log(path, value), }, }); ``` -------------------------------- ### Resolver `canRead` Property Examples Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/resolvers.md Demonstrates different ways to define the `canRead` property for a custom resolver. It can be a boolean, a regular expression, or a function that returns a truthy/falsy value. ```javascript let myResolver = { // Read ALL files canRead: true // Read all files on localhost canRead: /localhost/i // A function that returns a truthy/falsy value canRead(file) { return file.url.indexOf("127.0.0.1") !== -1; } }; ``` -------------------------------- ### Circular Reference Example in Schema Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md This JSON snippet illustrates a circular reference within a schema definition, where the 'spouse' property's type references the parent 'person' schema. ```json "person": { "properties": { "name": { "type": "string" }, "spouse": { "type": { "$ref": "#/person" // circular reference } } } } ``` -------------------------------- ### Bundle Schema using Instance Method Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Create an instance of `$RefParser` and then call the `bundle` method. This allows access to the parser instance for retrieving schema and $refs after the operation. ```javascript let parser = new $RefParser(); parser.bundle("my-schema.json"); ``` -------------------------------- ### Run Project Tests Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Executes the project's test suite using pnpm. This verifies the project's functionality. ```bash pnpm test ``` -------------------------------- ### Code Quality Checks Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/AGENTS.md Run ESLint for code linting on the lib/ directory and format all code files using Prettier. ```bash pnpm lint # Run ESLint on lib/ directory pnpm prettier # Format all code files ``` -------------------------------- ### Bundle Schema using Class Method Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Use the static `bundle` method on the `$RefParser` class to bundle a JSON schema. This is equivalent to creating an instance and calling the instance method. ```javascript $RefParser.bundle("my-schema.json"); ``` -------------------------------- ### Custom Resolver `read` Method Implementations Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/resolvers.md Illustrates the three ways to implement the `read` method for asynchronous operations: synchronous return, Node.js-style error-first callback, and ES6 Promise. ```javascript let myCallbackResolver = { // Return the value synchronously read(file) { return fs.readFileSync(file.url); } // Return the value in a callback function read(file, callback) { doSomethingAsync(file.url, (data) => { if (data) { // Success ! callback(null, data); } else { // Error ! callback(new Error("No data!")); } }); } }; let myPromiseResolver = { // Return the value in an ES6 Promise async read(file) { let data = await doSomethingAsync(file.url); if (data) { // Success ! return data; } else { // Error ! throw new Error("No data!"); } } }; ``` -------------------------------- ### Run Individual Test File Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/AGENTS.md Execute a specific test file using Vitest by providing its path. ```bash pnpm exec vitest test/specs/circular/circular.spec.ts ``` -------------------------------- ### bundle(schema, [options], [callback]) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Bundles all referenced files/URLs into a single schema with only internal $ref pointers. This is useful for packaging schemas for distribution. ```APIDOC ## bundle(schema, [options], [callback]) ### Description Bundles all referenced files/URLs into a single schema that only has _internal_ `$ref` pointers. This lets you split-up your schema however you want while you're building it, but easily combine all those files together when it's time to package or distribute the schema to other people. The resulting schema size will be small, since it will still contain _internal_ JSON references rather than being [fully-dereferenced](#dereferenceschema-options-callback). This also eliminates the risk of [circular references](README.md#circular-refs), so the schema can be safely serialized using [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). ### Parameters #### schema (_required_) - **Type**: `string` or `object`
- **Description**: A JSON Schema object, or the file path or URL of a JSON Schema file. See the [`parse`](#parseschema-options-callback) method for more info. #### options (_optional_) - **Type**: `object`
- **Description**: See [options](options.md) for the full list of options. #### callback (_optional_) - **Type**: `function(err, schema)`
- **Description**: A callback that will receive the bundled schema object. ### Return Value - **Type**: `Promise`
- **Description**: See [Callbacks vs. Promises](README.md#callbacks-vs-promises) ### Request Example ```javascript let schema = await $RefParser.bundle("my-schema.yaml"); console.log(schema.definitions.person); // => {$ref: "#/definitions/schemas~1people~1Bruce-Wayne.json"} ``` ``` -------------------------------- ### Custom `canParse` Configurations Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/parsers.md Illustrates various ways to configure the `canParse` property for custom parsers, including boolean, array of extensions, regular expression, and a function for custom logic. ```javascript let myParser = { // Parse ALL file types canParse: true // An array of file extensions (lowercased) canParse: [".txt", ".csv"] // A regular expression (matched against the FULL file path) canParse: /\.(txt|csv)$/i // A function that returns a truthy/falsy value canParse(file) { return file.extension === ".csv" || file.extension === ".txt"; } }; ``` -------------------------------- ### Run Tests with Vitest Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/AGENTS.md Execute all tests with coverage, or run tests specifically in Node.js or browser environments. Watch mode and snapshot updates are also available. ```bash pnpm test # Run all tests with coverage (Vitest) pnpm test:node # Run tests in Node.js environment pnpm test:browser # Run tests in browser environment (jsdom) pnpm test:watch # Run tests in watch mode pnpm test:update # Update test snapshots ``` -------------------------------- ### Bundle JSON Schema with $Ref Parser Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Bundles all referenced files and URLs into a single schema with only internal $ref pointers. This is useful for packaging schemas for distribution and eliminates the risk of circular references. ```javascript let schema = await $RefParser.bundle("my-schema.yaml"); console.log(schema.definitions.person); // => {$ref: "#/definitions/schemas~1people~1Bruce-Wayne.json"} ``` -------------------------------- ### Build and Typecheck Project Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/AGENTS.md Compile TypeScript code to the dist/ directory or run TypeScript type checking without emitting files. ```bash pnpm build # Compile TypeScript to dist/ pnpm typecheck # Run TypeScript type checking without emitting files ``` -------------------------------- ### Asynchronous `parse` Method with Promise Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/parsers.md Demonstrates implementing an asynchronous `parse` method using an ES6 Promise. This approach is suitable for modern JavaScript environments and asynchronous operations. ```javascript let myPromiseParser = { // Return the value in an ES6 Promise async parse(file) { let data = await doSomethingAsync(file.data); if (data) { // Success ! return data; } else { // Error ! throw new Error("No data!"); } }, }; ``` -------------------------------- ### $Refs.paths() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Returns an array of all the $ref pointers in the schema. ```APIDOC ## $Refs.paths() ### Description Returns an array of all the $ref pointers in the schema. ### Method `$refs.paths(types)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **types** (string or array) - Optional - Specifies which types of paths to return (e.g., 'external', 'internal', 'all'). Defaults to 'all'. ### Request Example ```javascript let parser = new $RefParser(); parser.parse(mySchema, (err, api) => { if (!err) { const externalPaths = api.$refs.paths('external'); console.log(externalPaths); } }); ``` ### Response #### Success Response (200) - **paths** (array) - An array of $ref pointer strings. ``` -------------------------------- ### $RefParser.bundle() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Bundles all external $ref pointers in a JSON schema into internal $refs. Supports both callbacks and promises. ```APIDOC ## $RefParser.bundle() ### Description Bundles all external $ref pointers in a JSON schema into internal $refs. This method can be used with either callbacks or promises. ### Method `$RefParser.bundle(schema, options, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - The JSON schema to bundle. - **options** (object) - Optional - Configuration options for bundling. - **callback** (function) - Optional - A Node.js-style error-first callback function. ### Request Example ```javascript // Using Promises (async/await) async function bundleSchema(schema) { try { const bundledSchema = await $RefParser.bundle(schema); // Process the bundled schema return bundledSchema; } catch (err) { console.error(err); throw err; } } // Using Callbacks $RefParser.bundle(mySchema, (err, bundledSchema) => { if (err) { console.error(err); } else { // Process the bundled schema } }); ``` ### Response #### Success Response (200) - **bundledSchema** (object) - The bundled JSON schema. ``` -------------------------------- ### Asynchronous `parse` Method with Callback Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/plugins/parsers.md Shows how to implement an asynchronous `parse` method using a Node.js-style error-first callback. This is useful when the parsing process involves asynchronous operations. ```javascript let myCallbackParser = { // Return the value in a callback function parse(file, callback) { doSomethingAsync(file.data, (data) => { if (data) { // Success ! callback(null, data); } else { // Error ! callback(new Error("No data!")); } }); }, }; ``` -------------------------------- ### paths([types]) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Retrieves the paths or URLs of all files within the schema, optionally filtered by type. ```APIDOC ## paths([types]) ### Description Returns the paths/URLs of all the files in your schema (including the main schema file). ### Parameters #### Query Parameters - **types** (_optional_) - `string` (one or more)
Optionally only return certain types of paths ("file", "http", etc.) ### Return Value - `array` of `string`
Returns the paths/URLs of all the files in your schema (including the main schema file). ### Example ```javascript let $refs = await $RefParser.resolve("my-schema.json"); // Get the paths of ALL files in the schema $refs.paths(); // Get the paths of local files only $refs.paths("file"); // Get all URLs $refs.paths("http"); ``` ``` -------------------------------- ### Clone JSON Schema $Ref Parser Repository Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Clones the JSON Schema $Ref Parser repository from GitHub to your local machine. ```bash git clone https://github.com/APIDevTools/json-schema-ref-parser.git ``` -------------------------------- ### set($ref, value) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Sets a value at a specified JSON Reference path within the schema, creating parent properties if they do not exist. ```APIDOC ## set($ref, value) ### Description Sets the value at the given path in the schema. If the property, or any of its parents, don't exist, they will be created. ### Parameters #### Path Parameters - **$ref** (_required_) - `string`
The JSON Reference path, optionally with a JSON Pointer in the hash - **value** (_required_)
The value to assign. Can be anything (object, string, number, etc.) ### Example ```javascript let $refs = await $RefParser.resolve("my-schema.json"); $refs.set("schemas/people/Bruce-Wayne.json#/properties/favoriteColor/default", "black"); ``` ``` -------------------------------- ### resolve(schema, [options], [callback]) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Resolves all JSON references ($ref pointers) in a schema, downloading and resolving any referenced files. It returns a $Refs object, not a dereferenced schema. This method is primarily for internal use. ```APIDOC ## resolve(schema, [options], [callback]) ### Description Resolves all JSON references (`$ref` pointers) in the given JSON Schema file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a [`$Refs`](refs.md) object, which is a map of all the resolved references and their values. > This method is used internally by other methods, such as [`bundle`](#bundleschema-options-callback) and [`dereference`](#dereferenceschema-options-callback). You probably won't need to call this method yourself. ### Parameters #### path (_required_) - **Type**: `string` or `object`
- **Description**: A JSON Schema object, or the file path or URL of a JSON Schema file. See the [`parse`](#parseschema-options-callback) method for more info. #### options (_optional_) - **Type**: `object`
- **Description**: See [options](options.md) for the full list of options. #### callback (_optional_) - **Type**: `function(err, $refs)`
- **Description**: A callback that will receive a [`$Refs`](refs.md) object. ### Return Value - **Type**: `Promise`
- **Description**: See [Callbacks vs. Promises](README.md#callbacks-vs-promises) ### Request Example ```javascript let $refs = await $RefParser.resolve("my-schema.yaml"); // $refs.paths() returns the paths of all the files in your schema let filePaths = $refs.paths(); // $refs.get() lets you query parts of your schema let name = $refs.get("schemas/people/Bruce-Wayne.json#/properties/name"); // $refs.set() lets you change parts of your schema $refs.set("schemas/people/Bruce-Wayne.json#/properties/favoriteColor/default", "black"); ``` ``` -------------------------------- ### exists($ref) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Checks if a given JSON Reference path exists within the schema. ```APIDOC ## exists($ref) ### Description Returns `true` if the given path exists in the schema; otherwise, returns `false`. ### Parameters #### Path Parameters - **$ref** (_required_) - `string`
The JSON Reference path, optionally with a JSON Pointer in the hash ### Return Value - `boolean`
Returns `true` if the given path exists in the schema; otherwise, returns `false` ### Example ```javascript let $refs = await $RefParser.resolve("my-schema.json"); $refs.exists("schemas/places.yaml#/definitions/Gotham-City"); // => true $refs.exists("schemas/places.yaml#/definitions/Metropolis"); // => false ``` ``` -------------------------------- ### Set a Value at a Specific Reference Path Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Modify or add a value at a specified JSON Reference path using the `set()` method. If parent properties do not exist, they will be created automatically. ```javascript let $refs = await $RefParser.resolve("my-schema.json"); $refs.set("schemas/people/Bruce-Wayne.json#/properties/favoriteColor/default", "black"); ``` -------------------------------- ### Run Tests Matching a Pattern Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/AGENTS.md Filter and run tests that match a specific pattern using Vitest's grep functionality. ```bash pnpm exec vitest --grep "circular" ``` -------------------------------- ### Dereference Schema with Async/Await Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Use the `dereference` method with `async/await` syntax for Promise-based asynchronous operations. Wrap the call in a try-catch block to handle potential errors. ```javascript try { let api = await $RefParser.dereference(mySchema); // Success } catch (err) { // Error } ``` -------------------------------- ### $RefParser.parse() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Parses a JSON schema, resolving all external $refs and dereferencing them. ```APIDOC ## $RefParser.parse() ### Description Parses a JSON schema, resolving all external $ref pointers and dereferencing them. This method can be used with either callbacks or promises. ### Method `$RefParser.parse(schema, options, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - The JSON schema to parse. - **options** (object) - Optional - Configuration options for parsing. - **callback** (function) - Optional - A Node.js-style error-first callback function. ### Request Example ```javascript // Using Promises (async/await) async function parseSchema(schema) { try { const parsedSchema = await $RefParser.parse(schema); // Process the parsed schema return parsedSchema; } catch (err) { console.error(err); throw err; } } // Using Callbacks $RefParser.parse(mySchema, (err, parsedSchema) => { if (err) { console.error(err); } else { // Process the parsed schema } }); ``` ### Response #### Success Response (200) - **parsedSchema** (object) - The parsed JSON schema. ``` -------------------------------- ### Webpack 5 Resolve Fallback Configuration Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Configures Webpack 5 to resolve 'path' and 'fs' modules using browserify alternatives. This is necessary because Webpack 5 drops default exports of node core modules. ```javascript config.resolve.fallback = { path: require.resolve("path-browserify"), fs: require.resolve("browserify-fs"), }; config.plugins.push( new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"], }), ); ``` -------------------------------- ### $Refs.exists() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Checks if a given $ref pointer exists in the schema. ```APIDOC ## $Refs.exists() ### Description Checks if a given $ref pointer exists in the schema. ### Method `$refs.exists(ref)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ref** (string) - Required - The $ref pointer to check. ### Request Example ```javascript let parser = new $RefParser(); parser.parse(mySchema, (err, api) => { if (!err) { const exists = api.$refs.exists('#/definitions/Person'); console.log(exists); } }); ``` ### Response #### Success Response (200) - **exists** (boolean) - True if the $ref pointer exists, false otherwise. ``` -------------------------------- ### parse(schema, [options], [callback]) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Parses a JSON Schema file (JSON or YAML) into a JavaScript object without resolving $ref pointers. This method is primarily for internal use. ```APIDOC ## parse(schema, [options], [callback]) ### Description Parses the given JSON Schema file (in JSON or YAML format), and returns it as a JavaScript object. This method **does not** resolve `$ref` pointers or dereference anything. It simply parses _one_ file and returns it. > This method is used internally by other methods, such as [`bundle`](#bundleschema-options-callback) and [`dereference`](#dereferenceschema-options-callback). You probably won't need to call this method yourself. ### Parameters #### schema (_required_) - **Type**: `string` or `object`
- **Description**: A JSON Schema object, or the file path or URL of a JSON Schema file.

The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page. #### options (_optional_) - **Type**: `object`
- **Description**: See [options](options.md) for the full list of options. #### callback (_optional_) - **Type**: `function(err, schema)`
- **Description**: A callback that will receive the parsed schema object, or an error. ### Return Value - **Type**: `Promise`
- **Description**: See [Callbacks vs. Promises](README.md#callbacks-vs-promises) ### Request Example ```javascript let schema = await $RefParser.parse("my-schema.yaml"); console.log(schema.definitions.person); // => {$ref: "schemas/people/Bruce-Wayne.json"} ``` ``` -------------------------------- ### Accessing $Refs Property Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Shows how to use the `$refs` property to inspect external references. Initially, `$refs.paths()` returns an empty array until a schema is dereferenced. ```javascript let parser = new $RefParser(); parser.$refs.paths(); // => [] empty array await parser.dereference("my-schema.json"); parser.$refs.paths(); // => ["my-schema.json"] ``` -------------------------------- ### $Refs.values() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Returns an object containing all the dereferenced values in the schema. ```APIDOC ## $Refs.values() ### Description Returns an object containing all the dereferenced values in the schema. ### Method `$refs.values(types)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **types** (string or array) - Optional - Specifies which types of values to return (e.g., 'external', 'internal', 'all'). Defaults to 'all'. ### Request Example ```javascript let parser = new $RefParser(); parser.dereference(mySchema, (err, api) => { if (!err) { const allValues = api.$refs.values(); console.log(allValues); } }); ``` ### Response #### Success Response (200) - **values** (object) - An object where keys are $ref pointers and values are the dereferenced schema objects. ``` -------------------------------- ### Accessing Schema Property Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Demonstrates how to access the parsed schema after dereferencing. The `schema` property holds the result, which is initially null. ```javascript let parser = new $RefParser(); parser.schema; // => null let schema = await parser.dereference("my-schema.json"); typeof parser.schema; // => "object" schema === parser.schema; // => true ``` -------------------------------- ### Check if a Reference Exists Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Use the `exists()` method to determine if a specific JSON Reference path exists within the schema. This method returns a boolean value. ```javascript let $refs = await $RefParser.resolve("my-schema.json"); $refs.exists("schemas/places.yaml#/definitions/Gotham-City"); // => true $refs.exists("schemas/places.yaml#/definitions/Metropolis"); // => false ``` -------------------------------- ### $Refs.get() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Retrieves the dereferenced value for a given $ref pointer. ```APIDOC ## $Refs.get() ### Description Retrieves the dereferenced value for a given $ref pointer. ### Method `$refs.get(ref, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ref** (string) - Required - The $ref pointer to retrieve. - **options** (object) - Optional - Configuration options for retrieval. ### Request Example ```javascript let parser = new $RefParser(); parser.dereference(mySchema, (err, api) => { if (!err) { const person = api.$refs.get('#/definitions/Person'); console.log(person); } }); ``` ### Response #### Success Response (200) - **value** (object) - The dereferenced schema object for the given $ref pointer. ``` -------------------------------- ### values([types]) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Retrieves a map of paths/URLs and their corresponding resolved values, optionally filtered by type. ```APIDOC ## values([types]) ### Description Returns a map of paths/URLs and their correspond values. ### Parameters #### Query Parameters - **types** (_optional_) - `string` (one or more)
Optionally only return values from certain locations ("file", "http", etc.) ### Return Value - `object`
Returns a map of paths/URLs and their correspond values. ### Example ```javascript let $refs = await $RefParser.resolve("my-schema.json"); // Get ALL paths & values in the schema // (this is the same as $refs.toJSON()) let values = $refs.values(); values["schemas/people/Bruce-Wayne.json"]; values["schemas/places.yaml"]; values["http://wayne-enterprises.com/things/batmobile"]; ``` ``` -------------------------------- ### Resolve JSON Schema References with $Ref Parser Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Resolves all JSON references ($ref pointers) within a schema, downloading and resolving any referenced files or URLs. It returns a `$Refs` object containing all resolved references and their values, but does not dereference them. ```javascript let $refs = await $RefParser.resolve("my-schema.yaml"); // $refs.paths() returns the paths of all the files in your schema let filePaths = $refs.paths(); // $refs.get() lets you query parts of your schema let name = $refs.get("schemas/people/Bruce-Wayne.json#/properties/name"); // $refs.set() lets you change parts of your schema $refs.set("schemas/people/Bruce-Wayne.json#/properties/favoriteColor/default", "black"); ``` -------------------------------- ### $RefParser.resolve() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Resolves all external $ref pointers in a JSON schema, but does not dereference them. ```APIDOC ## $RefParser.resolve() ### Description Resolves all external $ref pointers in a JSON schema, but does not dereference them. This method can be used with either callbacks or promises. ### Method `$RefParser.resolve(schema, options, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - The JSON schema to resolve. - **options** (object) - Optional - Configuration options for resolving. - **callback** (function) - Optional - A Node.js-style error-first callback function. ### Request Example ```javascript // Using Promises (async/await) async function resolveSchema(schema) { try { const resolvedSchema = await $RefParser.resolve(schema); // Process the resolved schema return resolvedSchema; } catch (err) { console.error(err); throw err; } } // Using Callbacks $RefParser.resolve(mySchema, (err, resolvedSchema) => { if (err) { console.error(err); } else { // Process the resolved schema } }); ``` ### Response #### Success Response (200) - **resolvedSchema** (object) - The JSON schema with resolved $refs. ``` -------------------------------- ### dereference(schema, [options], [callback]) Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Dereferences all $ref pointers in the JSON Schema, replacing each reference with its resolved value. This results in a schema object that does not contain any $ref pointers. ```APIDOC ## dereference(schema, [options], [callback]) ### Description Dereferences all `$ref` pointers in the JSON Schema, replacing each reference with its resolved value. This results in a schema object that does not contain _any_ `$ref` pointers. This is great for programmatic usage, especially when using tools that don't understand JSON references. The `dereference` method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. This introduces the risk of [circular references](README.md#circular-refs), so be careful if you intend to serialize the schema using [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Consider using the [`bundle`](#bundleschema-options-callback) method instead, which does not create circular references. ### Parameters #### Path Parameters - **schema** (string or object) - Required - A JSON Schema object, or the file path or URL of a JSON Schema file. See the [`parse`](#parseschema-options-callback) method for more info. #### Query Parameters - **options** (object) - Optional - See [options](options.md) for the full list of options #### Callback - **callback** (function(err, schema)) - Optional - A callback that will receive the dereferenced schema object ### Return Value - **Promise** - See [Callbacks vs. Promises](README.md#callbacks-vs-promises) ### Request Example ```javascript let schema = await $RefParser.dereference("my-schema.yaml"); // The `schema` object is a normal JavaScript object, // so you can easily access any part of the schema using simple dot notation console.log(schema.definitions.person.properties.firstName); // => {type: "string"} // Object reference equality works as expected schema.definitions.thing === schema.definitions.batmobile; // => true ``` ``` -------------------------------- ### $RefParser.dereference() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Dereferences all external $ref pointers in a JSON schema. Supports both callbacks and promises. ```APIDOC ## $RefParser.dereference() ### Description Dereferences all external $ref pointers in a JSON schema. This method can be used with either callbacks or promises. ### Method `$RefParser.dereference(schema, options, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **schema** (object) - Required - The JSON schema to dereference. - **options** (object) - Optional - Configuration options for dereferencing. - **callback** (function) - Optional - A Node.js-style error-first callback function. ### Request Example ```javascript // Using Promises (async/await) async function dereferenceSchema(schema) { try { const api = await $RefParser.dereference(schema); // Process the dereferenced schema return api; } catch (err) { console.error(err); throw err; } } // Using Callbacks $RefParser.dereference(mySchema, (err, api) => { if (err) { console.error(err); } else { // Process the dereferenced schema } }); ``` ### Response #### Success Response (200) - **api** (object) - The dereferenced JSON schema. ``` -------------------------------- ### Dereference Schema with Callback Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Use the `dereference` method with a callback function for Node.js-style error-first handling. The callback receives an error object or the dereferenced API object. ```javascript $RefParser.dereference(mySchema, (err, api) => { if (err) { // Error } else { // Success } }); ``` -------------------------------- ### $Refs.set() Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/README.md Sets the dereferenced value for a given $ref pointer. ```APIDOC ## $Refs.set() ### Description Sets the dereferenced value for a given $ref pointer. ### Method `$refs.set(ref, value, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ref** (string) - Required - The $ref pointer to set. - **value** (object) - Required - The schema object to set. - **options** (object) - Optional - Configuration options for setting. ### Request Example ```javascript let parser = new $RefParser(); parser.dereference(mySchema, (err, api) => { if (!err) { const newPerson = { type: 'object', properties: { name: { type: 'string' } } }; api.$refs.set('#/definitions/Person', newPerson); // The schema is now updated with the new definition } }); ``` ### Response #### Success Response (200) None (operation modifies the internal state). ``` -------------------------------- ### circular Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Checks if the schema contains any circular references. This is useful before JSON stringification. ```APIDOC ## circular ### Description This property is `true` if the schema contains any [circular references](README.md#circular-refs). You may want to check this property before serializing the dereferenced schema as JSON, since [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) does not support circular references by default. ### Example ```javascript let parser = new $RefParser(); await parser.dereference("my-schema.json"); if (parser.$refs.circular) { console.log("The schema contains circular references"); } ``` ``` -------------------------------- ### Parse JSON Schema with $Ref Parser Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Parses a single JSON or YAML schema file into a JavaScript object without resolving or dereferencing any $ref pointers. This method is typically used internally by other library functions. ```javascript let schema = await $RefParser.parse("my-schema.yaml"); console.log(schema.definitions.person); // => {$ref: "schemas/people/Bruce-Wayne.json"} ``` -------------------------------- ### Dereference JSON Schema Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/README.md Dereferences a JSON schema, resolving all internal and external $ref pointers. By default, the input schema is modified in place. Use the `mutateInputSchema: false` option to return a cloned schema instead. ```javascript import $RefParser from "@apidevtools/json-schema-ref-parser"; try { await $RefParser.dereference(mySchema); // note - by default, mySchema is modified in place, and the returned value is a reference to the same object console.log(mySchema.definitions.person.properties.firstName); // if you want to avoid modifying the original schema, you can disable the `mutateInputSchema` option let clonedSchema = await $RefParser.dereference(mySchema, { mutateInputSchema: false }); console.log(clonedSchema.definitions.person.properties.firstName); } catch (err) { console.error(err); } ``` -------------------------------- ### Check for Circular References in Schema Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/refs.md Use the `circular` property to detect if the schema contains circular references. This is important before serializing to JSON, as `JSON.stringify` does not support them by default. ```javascript let parser = new $RefParser(); await parser.dereference("my-schema.json"); if (parser.$refs.circular) { console.log("The schema contains circular references"); } ``` -------------------------------- ### Dereferencing a Schema Source: https://github.com/apidevtools/json-schema-ref-parser/blob/main/docs/ref-parser.md Dereferences all $ref pointers in a JSON Schema, returning a plain JavaScript object. This method preserves object reference equality, which can lead to circular references. ```javascript let schema = await $RefParser.dereference("my-schema.yaml"); // The `schema` object is a normal JavaScript object, // so you can easily access any part of the schema using simple dot notation console.log(schema.definitions.person.properties.firstName); // => {type: "string"} // Object reference equality works as expected schema.definitions.thing === schema.definitions.batmobile; // => true ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.