Skip to content

JSON Field - jsonSchema unable to generate types nor parse $ref correctly - uses payload-types.ts as target #11383

Open

Description

@greenlover1991

Describe the Bug

I have this jsonSchema that uses $ref (recursively) to validate a JSON field

JSON Schema
// src/collections/Posts/index.ts
import type { JSONField } from 'payload';

type JSONSchema = Exclude<JSONField['jsonSchema'], undefined>['schema'];
const filterSchema: JSONSchema = {
  $schema: 'http://json-schema.org/draft-07/schema#',
  type: 'object',
  definitions: {
    condition: {
      type: 'object',
      properties: {
        _int_eq: {
          type: 'object',
          additionalProperties: { type: 'integer' },
        },
        _str_in: {
          type: 'object',
          additionalProperties: {
            type: 'array',
            items: { type: 'string' },
          },
        },
        _str_not_in: {
          type: 'object',
          additionalProperties: {
            type: 'array',
            items: { type: 'string' },
          },
        },
        _str_eq: {
          type: 'object',
          additionalProperties: { type: 'string' },
        },
        _bool_eq: {
          type: 'object',
          additionalProperties: { type: 'boolean' },
        },
        _str_not_eq: {
          type: 'object',
          additionalProperties: { type: 'string' },
        },
        _int_in_range_exc: {
          type: 'object',
          additionalProperties: {
            type: 'object',
            properties: {
              min: { type: 'integer' },
              max: { type: 'integer' },
            },
            anyOf: [{ required: ['min'] }, { required: ['max'] }],
            additionalProperties: false,
          },
        },
        _array_contains: {
          type: 'object',
          additionalProperties: {
            anyOf: [
              { type: 'string' },
              { type: 'number' },
              { type: 'integer' },
              { type: 'boolean' },
            ],
          },
        },
        _array_not_contains: {
          type: 'object',
          additionalProperties: {
            anyOf: [
              { type: 'string' },
              { type: 'number' },
              { type: 'integer' },
              { type: 'boolean' },
            ],
          },
        },
        _int_in_range_inc: {
          type: 'object',
          additionalProperties: {
            type: 'object',
            properties: {
              min: { type: 'integer' },
              max: { type: 'integer' },
            },
            anyOf: [{ required: ['min'] }, { required: ['max'] }],
            additionalProperties: false,
          },
        },
        _is_null: {
          type: 'object',
          additionalProperties: { type: 'boolean' },
        },
        _is_not_null: {
          type: 'object',
          additionalProperties: { type: 'boolean' },
        },
        _days_from_now: {
          type: 'object',
          additionalProperties: { type: 'integer', minimum: 0 },
        },
        _or: {
          type: 'array',
          items: { $ref: '#/definitions/condition' },
        },
        _and: {
          type: 'array',
          items: { $ref: '#/definitions/condition' },
        },
      },
      additionalProperties: false,
    },
  },
  properties: {
    _or: {
      type: 'array',
      items: { $ref: '#/definitions/condition' },
    },
    _and: {
      type: 'array',
      items: { $ref: '#/definitions/condition' },
    },
  },
  additionalProperties: false,
};

export const Posts: CollectionConfig<'posts'> = {
  // ...snipped
  fields: [
    {
      name: 'criteria_json',
      type: 'json',
      jsonSchema: {
        uri: 'dummy://foo.json',
        fileMatch: ['dummy://foo.json'],
        schema: filterSchema,
      },
    },
  ]
}

And during editing, the browser is able to autosuggest and validate the JSON field correctly:

Image


But when I run pnpm generate:types, I get this error:

generate:types Error
  $ pnpm generate:types
  
  > [email protected] generate:types /workspaces/my-monorepo-project/javascript/apps/payload-website
  > cross-env NODE_OPTIONS=--no-deprecation payload generate:types
  
  [05:47:24] INFO: Compiling TS types for Collections and Globals...
  node:internal/process/promises:391
      triggerUncaughtException(err, true /* fromPromise */);
      ^
  
  JSONParserError: Missing $ref pointer "#/definitions/condition". Token "condition" does not exist.
      at Pointer.resolve (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/pointer.js:118:23)
      at $Ref.resolve (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/ref.js:81:28)
      at $Refs._resolve (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/refs.js:168:21)
      at dereference$Ref (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:191:27)
      at crawl (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:105:40)
      at crawl (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:136:44)
      at crawl (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:136:44)
      at crawl (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:136:44)
      at crawl (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:136:44)
      at crawl (/workspaces/my-monorepo-project/javascript/node_modules/.pnpm/@[email protected]/node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js:136:44) {
    code: 'EMISSINGPOINTER',
    name: 'MissingPointerError',
    source: '/workspaces/my-monorepo-project/javascript/apps/payload-website/',
    path: null,
    toJSON: [Function: toJSON],
    targetToken: 'condition',
    targetRef: '#/definitions/condition',
    targetFound: '#/definitions',
    parentPath: '#/definitions/posts/properties/criteria_json/definitions/condition/properties/_or/items',
    [Symbol(nodejs.util.inspect.custom)]: [Function: inspect]

This worked before in Payload V2 and I did not have to explicitly specify the JSONSchema type as well.


If i change the $ref

from:

  $ref: '#/definitions/condition'

to:

  $ref: '#/definitions/posts/properties/criteria_json/definitions/condition'

then it's able to generate the types:

JSON field with schema - generated types
  // payload-types.ts
  export interface Post {
     // ...snip
    criteria_json?: {
      _or?: Condition[];
      _and?: Condition[];
    };
  }

  export interface Condition {
    _int_eq?: {
      [k: string]: number;
    };
    _str_in?: {
      [k: string]: string[];
    };
    _str_not_in?: {
      [k: string]: string[];
    };
    _str_eq?: {
      [k: string]: string;
    };
    // ...snipped...
  }

But in the browser, when editing the JSON field, it does not suggest / validate based on the schema:

Image
Image


Troubleshooting this, it seems that the relative path being used for the $ref is the payload-types.ts? If I specify an external schema file as the jsonSchema.uri, then it seems to work in both the generation of types and in the browser field editor. But I don't want to host the external JSON schema file separately.


Expected behavior: should be able to generate types with JSON field with JSON schema using $ref

Link to the code that reproduces this issue

https://github.com/payloadcms/payload/blob/main/packages/payload/src/bin/generateTypes.ts#L32

Reproduction Steps

  1. Create new project pnpx create-payload-app@latest -t website
  2. Add JSON field to src/collections/Posts/index.tsx
  3. Specify a local jsonSchema using $ref (same as in the ticket description)
  4. Run pnpm generate:types
  5. [BUG] Unable to generate the types, and console will show error.

Which area(s) are affected? (Select all that apply)

area: core

Environment Info

Binaries:
  Node: 20.18.2
  npm: N/A
  Yarn: N/A
  pnpm: 9.14.2
Relevant Packages:
  payload: 3.23.0
Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Tue Jan 21 10:23:32 UTC 2025
  Available memory (MB): 27015
  Available CPU cores: 11

Activity

  1. added
    status: needs-triage
    validate-reproduction
    on Feb 25, 2025
  2. removed
    validate-reproduction
    on Feb 25, 2025
  3. removed
    status: needs-triage
    on Feb 27, 2025
  4. Tj3rk commented on Mar 20, 2025

    @Tj3rk

    Any updates on this? We’re experiencing the same issue.

  5. hgascoigne commented on May 8, 2025

    @hgascoigne

    Ran across this issue as well. Here's how I fixed it on our end until a proper fix is implemented:

    I created a utility that will traverse a JSON schema's $refs and check if the definition exists at the given $ref. If it doesn't, it will go and find the actual location of the definition and update the $ref.

    // utilities/fixRelativeDefinitions.ts
    import get from "lodash/get";
    import set from "lodash/set";
    
    function flattenObject(
      obj: Record<string, unknown>,
      prefix: string = "",
      result: Record<string, unknown> = {},
    ) {
      for (const key in obj) {
        if (key in obj) {
          const newKey = prefix ? `${prefix}/${key}` : key;
          if (typeof obj[key] === "object" && obj[key] !== null) {
            flattenObject(obj[key] as Record<string, unknown>, newKey, result);
          } else {
            result[newKey] = obj[key];
          }
        }
      }
      return result;
    }
    
    export function fixRelativeDefinitions(jsonSchema: any) {
      const flattened = flattenObject(jsonSchema);
      const refs = Object.entries(flattened).filter(
        (pair): pair is [string, string] =>
          pair[0].endsWith("$ref") && typeof pair[1] === "string",
      );
    
      for (const [key, ref] of refs) {
        const definitionPath = ref.split("/").slice(1).join("/");
        const definition = get(jsonSchema, definitionPath.split("/"));
    
        if (!definition) {
          const relativePath =
            Object.keys(flattened)
              .find((k) => k.includes(definitionPath))
              ?.split(`/${definitionPath}`)[0] || "";
          const absolutePath = ref.replace("#", `#/${relativePath}`);
    
          set(jsonSchema, key.split("/"), absolutePath);
        }
      }
    }

    And then usage in our Payload config to transform the schema before it's converted to TS types:

    // payload.config.ts
    typescript: {
      schema: [
        ({ jsonSchema }) => {
          // Fixes Payload bug: https://github.com/payloadcms/payload/issues/11383
          fixRelativeDefinitions(jsonSchema);
    
          return jsonSchema;
        },
      ],
    }

    Hope this helps temporarily!

  6. greenlover1991 commented on May 12, 2025

    @greenlover1991
    Author

    Thanks @hgascoigne! your workaround in #11383 (comment) worked well for us.

    Originally, our workaround was to comment out the jsonSchema, run the pnpm generate:types command and revert the unrelated changes in git

  7. Zwooosh commented on Jul 24, 2025

    @Zwooosh

    Adding to this thread by saying that the solution from @hgascoigne also worked in our case! We'll keep this in until this is eventually fixed in payload. Thanks!

  8. JessRynkar commented on Jul 14, 2026

    @JessRynkar
    Member

    Sorry you didn't get a team response on this sooner. Is this still reproducible on the latest v3 version (v3.86.0)? If so, could you confirm your repro steps still apply there and we'll take another look.

  9. greenlover1991 commented on Jul 15, 2026

    @greenlover1991
    Author

    Sorry you didn't get a team response on this sooner. Is this still reproducible on the latest v3 version (v3.86.0)? If so, could you confirm your repro steps still apply there and we'll take another look.

    Yes, this is still reproducible in v3.86.0 with the same steps and error. Sample repo https://github.com/greenlover1991/payloadcms-11383 that will throw an error on pnpm generate:types

    Reproduction Steps:

    1. Create new project pnpx create-payload-app@latest -t website
    2. Add JSON field to src/collections/Posts/index.tsx
    3. Specify a local jsonSchema using $ref (same as in the ticket description)
    4. Run pnpm generate:types
    5. [BUG] Unable to generate the types, and console will show error.
    $ pnpm generate:types
    [WARN] The "pnpm" field in package.json is no longer read by pnpm. The following keys were ignored: "pnpm.onlyBuiltDependencies". See https://pnpm.io/settings for the new home of each setting.
    $ cross-env NODE_OPTIONS=--no-deprecation payload generate:types
    [09:52:36] INFO: Compiling TS types for Collections and Globals...
    C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\pointer.js:129
                    throw new errors_js_1.MissingPointerError(token, decodeURI(this.originalPath), targetRef, targetFound, parentPath);
                          ^
    
    MissingPointerError: Missing $ref pointer "#/definitions/condition". Token "condition" does not exist.
        at Pointer.resolve (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\pointer.js:129:23)
        at $Ref.resolve (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\ref.js:111:38)
        at $Refs._resolve (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\refs.js:168:21)
        at dereference$Ref (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:191:27)
        at crawl (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:105:40)
        at crawl (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:136:44)
        at crawl (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:136:44)
        at crawl (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:136:44)
        at crawl (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:136:44)
        at crawl (C:\Users\User1\Code\Projects\payloadcms-11383\payloadcms-11383\node_modules\.pnpm\@[email protected]\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\dereference.js:136:44) {
      code: 'EMISSINGPOINTER',
      source: 'c:/Users/User1/Code/Projects/payloadcms-11383/payloadcms-11383/',
      path: null,
      toJSON: [Function: toJSON],
      targetToken: 'condition',
      targetRef: '#/definitions/condition',
      targetFound: '#/definitions',
      parentPath: '#/definitions/posts/properties/criteria_json/definitions/condition/properties/_or/items',
      Symbol(nodejs.util.inspect.custom): [Function: inspect]
    }
    

    Payload Info:

    $ pnpm payload info
    [WARN] The "pnpm" field in package.json is no longer read by pnpm. The following keys were ignored: "pnpm.onlyBuiltDependencies". See https://pnpm.io/settings for the new home of each setting.
    $ cross-env NODE_OPTIONS=--no-deprecation payload "info"
    
    Binaries:
      Node: 24.16.0
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant Packages:
      payload: 3.86.0
      next: 16.2.6
      @payloadcms/db-sqlite: 3.86.0
      @payloadcms/drizzle: 3.86.0
      @payloadcms/graphql: 3.86.0
      @payloadcms/live-preview: 3.86.0
      @payloadcms/live-preview-react: 3.86.0
      @payloadcms/next/utilities: 3.86.0
      @payloadcms/plugin-form-builder: 3.86.0
      @payloadcms/plugin-nested-docs: 3.86.0
      @payloadcms/plugin-redirects: 3.86.0
      @payloadcms/plugin-search: 3.86.0
      @payloadcms/plugin-seo: 3.86.0
      @payloadcms/richtext-lexical: 3.86.0
      @payloadcms/translations: 3.86.0
      @payloadcms/ui/shared: 3.86.0
      react: 19.2.6
      react-dom: 19.2.6
    Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 11 Home
      Available memory (MB): 16255
      Available CPU cores: 12
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions