Skip to content

plugin typed-document-mode with documentMode "string" cannot handle unescaped backticks/backslashes/dollar-signs in GraphQL description strings #10480

@gibson042

Description

@gibson042

Which packages are impacted by your issue?

@graphql-codegen/visitor-plugin-common, @graphql-codegen/cli, @graphql-codegen/typed-document-node, @graphql-codegen/client-preset

Describe the bug

The output for documentMode "string" is incorrect when a backtick ` appears in a source GraphQL document (e.g., in a description string), because plugin @graphql-codegen/visitor-plugin-common's ClientSideBaseVisitor _gql method does not account for template literal special characters when building its output. This is somewhat analogous to #2272.

Your Example Website or App

https://stackblitz.com/edit/github-jpcp2x3s?file=document.graphql

Steps to Reproduce the Bug or Issue

  1. Create a configuration with documentMode: 'string'.
  2. Create a GraphQL document whose contents include an unescaped backtick or backslash or dollar sign, e.g.
    """
    A ` backtick here makes types.ts syntactically invalid
    with documentMode "string".
    """
    query user {
        user(id: 1) {
            id
            username
            email
        }
    }
  3. Execute graphql-codegen (e.g., yarn generate in the provided example).
  4. Observe the syntactically invalid new TypedDocumentString(`…`) output:
    export const UserDocument = new TypedDocumentString(`
        """
    A ` backtick here makes types.ts syntactically invalid
    with documentMode "string".
    """
    query user {
      user(id: 1) {
        id
        username
        email
      }
    }
        `) as unknown as TypedDocumentString<UserQuery, UserQueryVariables>;

Expected behavior

As a user, I expected any special characters in my input GraphQL document to be properly escaped in the generated output.

Screenshots or Videos

No response

Platform

node -p 'require("./package.json").dependencies'
{
  '@graphql-codegen/add': '^5.0.0',
  '@graphql-codegen/cli': '^4.0.1',
  '@graphql-codegen/typed-document-node': '^6.1.0',
  '@graphql-codegen/typescript': '^4.0.1',
  '@graphql-codegen/typescript-operations': '^4.0.1',
  graphql: '^16.2.0'
}

Codegen Config File

import { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: 'schema.graphql',
  documents: 'document.graphql',
  generates: {
    'types.ts': {
      plugins: ['typescript', 'typescript-operations', 'typed-document-node'],
      config: {
        documentMode: 'string',
      },
    },
  },
};

export default config;

Additional context

No response

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions