Skip to content

Resolving top-level $ref fails with TypeError: Converting circular structure to JSON #382

Open
@ahochsteger

Description

@ahochsteger

When using $ref on the top-level to reference a defined type in $defs it wrongly results in a TypeError: Converting circular structure to JSON which is not a circular reference.
According to the JSON Schema Core Specification Draft 2020-12 (see 7.5. Applicators) it is valid to use $ref on the top-level.
Here's a example schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$ref": "#/$defs/TopLevelType",
  "$defs": {
    "PropType": {
      "title": "Property",
      "type": "string"
    },
    "TopLevelType": {
      "properties": {
        "prop1": {
          "$ref": "#/$defs/PropType"
        }
      },
      "title": "Top Level Type",
      "type": "object"
    }
  }
}

Trying to resolve this issue using the following test program:

import $RefParser from "@apidevtools/json-schema-ref-parser";
import mySchema from "./bundler-demo-non-working.json" with { type: "json" };

try {
  await $RefParser.dereference(mySchema);
  const clonedSchema = await $RefParser.dereference(mySchema, { mutateInputSchema: false });
  console.log(clonedSchema);
} catch (err) {
  console.error(err);
}

Results in the following error:

node test.js 
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property 'TopLevelType' -> object with constructor 'Object'
    |     property 'properties' -> object with constructor 'Object'
    |     property 'prop1' -> object with constructor 'Object'
    --- property '$defs' closes the circle
    at JSON.stringify (<anonymous>)
    at normalizeArgs (node_modules/@apidevtools/json-schema-ref-parser/dist/lib/normalize-args.js:46:34)
    at $RefParser.dereference (node_modules/@apidevtools/json-schema-ref-parser/dist/lib/index.js:193:54)
    at Object.dereference (node_modules/@apidevtools/json-schema-ref-parser/dist/lib/index.js:190:37)
    at file://test.js:6:41

It has been reproduced with version 12.0.1 of @apidevtools/json-schema-ref-parser.

The resolution of this issue is required for skriptfabrik/json-schema-bundler#28.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions