Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ahochsteger opened this issue Apr 21, 2025 · 1 comment · Fixed by #383
Closed
Labels

Comments

@ahochsteger
Copy link

ahochsteger commented Apr 21, 2025

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.

Copy link

🎉 This issue has been resolved in version 12.0.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant