diff --git a/dist/graphql-codegen-pydantic.cjs.development.js b/dist/graphql-codegen-pydantic.cjs.development.js index e31f32c..e5851c5 100644 --- a/dist/graphql-codegen-pydantic.cjs.development.js +++ b/dist/graphql-codegen-pydantic.cjs.development.js @@ -54,7 +54,7 @@ class PydanticVisitor extends visitorPluginCommon.BaseVisitor { if (this.addFieldImport) { pydantic.push(`Field`); } - const enumInput = this.addEnumImport ? 'from enum import Enum' : ''; + const enumInput = this.addEnumImport ? 'from enum import StrEnum' : ''; const typingImport = typing.length ? `from typing import ${typing.join(', ')}` : ''; const pydanticImport = pydantic.length ? `from pydantic import ${pydantic.join(', ')}` : ''; return [enumInput, typingImport, pydanticImport].filter(i => i).join('\n'); @@ -178,7 +178,7 @@ class PydanticVisitor extends visitorPluginCommon.BaseVisitor { values } = node; const val = values.map(v => visitorPluginCommon.indent(`${v.name} = '${v.name}'`, 2)).join('\n'); - const source = `class ${name}(str, Enum):\n${val}`; + const source = `class ${name}(StrEnum):\n${val}`; this.upsertGraphNode(name); return { id: name, diff --git a/dist/graphql-codegen-pydantic.cjs.development.js.map b/dist/graphql-codegen-pydantic.cjs.development.js.map index 46d9ba7..a4c72a4 100644 --- a/dist/graphql-codegen-pydantic.cjs.development.js.map +++ b/dist/graphql-codegen-pydantic.cjs.development.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-codegen-pydantic.cjs.development.js","sources":["../src/visitor.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable lines-between-class-members */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable react/no-this-in-sfc */\nimport {\n BaseVisitor,\n ParsedConfig,\n buildScalars,\n indent,\n} from '@graphql-codegen/visitor-plugin-common';\nimport {\n NamedTypeNode,\n ListTypeNode,\n NonNullTypeNode,\n GraphQLSchema,\n FieldDefinitionNode,\n ObjectTypeDefinitionNode,\n NameNode,\n UnionTypeDefinitionNode,\n DocumentNode,\n InterfaceTypeDefinitionNode,\n EnumTypeDefinitionNode,\n InputObjectTypeDefinitionNode,\n InputValueDefinitionNode,\n} from 'graphql';\nimport { DepGraph } from 'dependency-graph';\n\nimport { PydanticPluginRawConfig } from './config';\n\nexport const PYTHON_SCALARS = {\n ID: 'str',\n String: 'str',\n Boolean: 'bool',\n Int: 'int',\n Float: 'float',\n};\n\nconst PYTHON_RESERVED = ['from'];\nconst PYDANTIC_MODEL_RESERVED = ['copy'];\nconst RESERVED = PYTHON_RESERVED.concat(PYDANTIC_MODEL_RESERVED);\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PydanticPluginParsedConfig extends ParsedConfig {\n /* intentionally empty for now */\n}\n\nexport class PydanticVisitor extends BaseVisitor<\n PydanticPluginRawConfig,\n PydanticPluginParsedConfig\n> {\n private addOptionalImport = false;\n private addAnyImport = false;\n private addListImport = false;\n private addUnionImport = false;\n private addEnumImport = false;\n private addFieldImport = false;\n\n private graph = new DepGraph({\n circular: false,\n });\n\n constructor(\n rawConfig: PydanticPluginRawConfig,\n private schema: GraphQLSchema,\n ) {\n super(rawConfig, {\n // enumValues: rawConfig.enumValues || {},\n // listType: rawConfig.listType || 'List',\n // package: rawConfig.package || defaultPackageName,\n scalars: buildScalars(schema, {}, PYTHON_SCALARS),\n });\n }\n\n public getImports(): string {\n const typing = [];\n const pydantic = ['BaseModel'];\n\n if (this.addAnyImport) {\n typing.push(`Any`);\n }\n\n if (this.addOptionalImport) {\n typing.push(`Optional`);\n }\n\n if (this.addListImport) {\n typing.push(`List`);\n }\n\n if (this.addUnionImport) {\n typing.push(`Union`);\n }\n\n if (this.addFieldImport) {\n pydantic.push(`Field`);\n }\n\n const enumInput = this.addEnumImport ? 'from enum import Enum' : '';\n\n const typingImport = typing.length\n ? `from typing import ${typing.join(', ')}`\n : '';\n\n const pydanticImport = pydantic.length\n ? `from pydantic import ${pydantic.join(', ')}`\n : '';\n\n return [enumInput, typingImport, pydanticImport].filter(i => i).join('\\n');\n }\n\n protected canAddGraphNode(id: string): boolean {\n if (Object.values(this.scalars).includes(id) || id === 'Any') {\n return false;\n }\n\n return true;\n }\n\n protected upsertGraphNode(id: string) {\n if (this.canAddGraphNode(id) && !this.graph.hasNode(id)) {\n this.graph.addNode(id);\n }\n }\n\n protected addGraphNodeDeps(id: string, ids: string[]) {\n if (!this.canAddGraphNode(id)) {\n return;\n }\n\n this.upsertGraphNode(id);\n\n ids.forEach((i: string) => {\n if (!this.canAddGraphNode(i)) {\n return;\n }\n\n this.upsertGraphNode(i);\n\n this.graph.addDependency(id, i);\n });\n }\n\n protected clearOptional(str: string): string {\n if (str.startsWith('Optional[')) {\n return str.replace(/Optional\\[(.*?)\\]$/, '$1');\n }\n\n return str;\n }\n\n Name(node: NameNode) {\n return node.value;\n }\n\n NamedType(node: NamedTypeNode) {\n const { name } = node as any;\n\n // Scalars\n if (Object.keys(this.scalars).includes(name)) {\n const id = this.scalars[name];\n\n // Special case for any\n if (id === 'any') {\n this.addAnyImport = true;\n return {\n id: 'Any',\n source: 'Any',\n };\n }\n\n this.addOptionalImport = true;\n return {\n id,\n source: `Optional[${id}]`,\n };\n }\n\n // Defined\n this.addOptionalImport = true;\n return {\n id: name,\n source: `Optional['${name}']`,\n };\n }\n\n ListType(node: ListTypeNode) {\n this.addListImport = true;\n this.addOptionalImport = true;\n\n const { type } = node as any;\n\n return {\n id: type.id,\n source: `Optional[List[${type.source}]]`,\n };\n }\n\n NonNullType(node: NonNullTypeNode) {\n const { type } = node as any;\n\n return {\n id: type.id,\n source: this.clearOptional(type.source),\n };\n }\n\n protected visitFieldOrInputDefinition(node: any) {\n const argName = node.name as any;\n\n const { type, directives } = node as any;\n\n // Handle deprecated\n // const ds = directives.map((d: any) => d.name);\n // if (ds.includes('deprecated')) {\n // return null;\n // }\n\n // Need to alias some field names\n // Otherwise pydantic throws\n if (RESERVED.includes(argName)) {\n this.addFieldImport = true;\n return {\n id: type.id,\n source: indent(\n `${argName}_: ${type.source} = Field(None, alias='${argName}')`,\n 2,\n ),\n };\n }\n\n return {\n id: type.id,\n source: indent(`${argName}: ${type.source}`, 2),\n };\n }\n\n FieldDefinition(node: FieldDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n InputValueDefinition(node: InputValueDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n EnumTypeDefinition(node: EnumTypeDefinitionNode) {\n this.addEnumImport = true;\n\n const { name, values } = node as any;\n\n const val = values\n .map((v: any) => indent(`${v.name} = '${v.name}'`, 2))\n .join('\\n');\n const source = `class ${name}(str, Enum):\\n${val}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n UnionTypeDefinition(node: UnionTypeDefinitionNode) {\n this.addUnionImport = true;\n\n const { name, types } = node as any;\n\n const unionTypes = (types ?? []).map((t: any) =>\n this.clearOptional(t.source),\n );\n\n this.addGraphNodeDeps(\n name,\n types.map((t: any) => t.id),\n );\n\n return {\n id: name,\n source: `${name} = Union[${unionTypes.join(', ')}]`,\n };\n }\n\n InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.addGraphNodeDeps(\n name,\n fields.map((f: any) => f.id),\n );\n\n return {\n id: name,\n source,\n };\n }\n\n ObjectTypeDefinition(node: ObjectTypeDefinitionNode) {\n const { name, fields: rawFields, interfaces: rawInterfaces } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const interfaces = rawInterfaces.map((n: any) =>\n this.clearOptional(n.source).replace(/'/g, ''),\n );\n\n const impl = interfaces.length ? interfaces.join(', ') : 'BaseModel';\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(${impl}):\\n${args}`;\n\n if (interfaces.length) {\n this.addGraphNodeDeps(name, interfaces);\n } else {\n this.upsertGraphNode(name);\n }\n\n return {\n id: name,\n source,\n };\n }\n\n InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n Document(node: DocumentNode) {\n const { definitions } = node as any;\n\n const nodesInOrder = this.graph.overallOrder();\n\n return nodesInOrder\n .map((n: any) => definitions.find((d: any) => d.id === n)?.source || '')\n .join('\\n\\n\\n');\n }\n}\n","import { parse, GraphQLSchema, printSchema, visit } from 'graphql';\nimport { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';\n\nimport { PydanticVisitor } from './visitor';\nimport { PydanticPluginRawConfig } from './config';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const plugin: PluginFunction = async (\n schema: GraphQLSchema,\n documents: Types.DocumentFile[],\n config: PydanticPluginRawConfig,\n info,\n): Promise => {\n const visitor = new PydanticVisitor(config, schema);\n const printedSchema = printSchema(schema);\n const astNode = parse(printedSchema);\n\n const visitorResult = visit(astNode, { leave: visitor as any });\n const imports = visitor.getImports();\n\n return `${imports}\\n\\n\\n${visitorResult}\\n`;\n};\n"],"names":["PYTHON_SCALARS","ID","String","Boolean","Int","Float","PYTHON_RESERVED","PYDANTIC_MODEL_RESERVED","RESERVED","concat","PydanticVisitor","BaseVisitor","constructor","rawConfig","schema","scalars","buildScalars","DepGraph","circular","getImports","typing","pydantic","addAnyImport","push","addOptionalImport","addListImport","addUnionImport","addFieldImport","enumInput","addEnumImport","typingImport","length","join","pydanticImport","filter","i","canAddGraphNode","id","Object","values","includes","upsertGraphNode","graph","hasNode","addNode","addGraphNodeDeps","ids","forEach","addDependency","clearOptional","str","startsWith","replace","Name","node","value","NamedType","name","keys","source","ListType","type","NonNullType","visitFieldOrInputDefinition","argName","directives","indent","FieldDefinition","InputValueDefinition","EnumTypeDefinition","val","map","v","UnionTypeDefinition","types","unionTypes","t","InterfaceTypeDefinition","fields","rawFields","f","args","ObjectTypeDefinition","interfaces","rawInterfaces","n","impl","InputObjectTypeDefinition","Document","definitions","nodesInOrder","overallOrder","find","d","plugin","documents","config","info","visitor","printedSchema","printSchema","astNode","parse","visitorResult","visit","leave","imports"],"mappings":";;;;;;;;AAAA;AA4BO,MAAMA,cAAc,GAAG;EAC5BC,EAAE,EAAE,KAAK;EACTC,MAAM,EAAE,KAAK;EACbC,OAAO,EAAE,MAAM;EACfC,GAAG,EAAE,KAAK;EACVC,KAAK,EAAE;CACR;AAED,MAAMC,eAAe,GAAG,CAAC,MAAM,CAAC;AAChC,MAAMC,uBAAuB,GAAG,CAAC,MAAM,CAAC;AACxC,MAAMC,QAAQ,gBAAGF,eAAe,CAACG,MAAM,CAACF,uBAAuB,CAAC;MAOnDG,eAAgB,SAAQC,+BAGpC;EAYCC,YACEC,SAAkC,EAC1BC,MAAqB;IAE7B,KAAK,CAACD,SAAS,EAAE;;;;MAIfE,OAAO,EAAEC,gCAAY,CAACF,MAAM,EAAE,EAAE,EAAEd,cAAc;KACjD,CAAC;IAPM,WAAM,GAANc,MAAM;IAbR,sBAAiB,GAAG,KAAK;IACzB,iBAAY,GAAG,KAAK;IACpB,kBAAa,GAAG,KAAK;IACrB,mBAAc,GAAG,KAAK;IACtB,kBAAa,GAAG,KAAK;IACrB,mBAAc,GAAG,KAAK;IAEtB,UAAK,GAAG,IAAIG,wBAAQ,CAAC;MAC3BC,QAAQ,EAAE;KACX,CAAC;;EAcKC,UAAU;IACf,MAAMC,MAAM,GAAG,EAAE;IACjB,MAAMC,QAAQ,GAAG,CAAC,WAAW,CAAC;IAE9B,IAAI,IAAI,CAACC,YAAY,EAAE;MACrBF,MAAM,CAACG,IAAI,MAAM,CAAC;;IAGpB,IAAI,IAAI,CAACC,iBAAiB,EAAE;MAC1BJ,MAAM,CAACG,IAAI,WAAW,CAAC;;IAGzB,IAAI,IAAI,CAACE,aAAa,EAAE;MACtBL,MAAM,CAACG,IAAI,OAAO,CAAC;;IAGrB,IAAI,IAAI,CAACG,cAA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,YAAY,CAChBnB,GAAG,CAAEc,CAAM;MAAA;MAAA,OAAK,sBAAAI,WAAW,CAACG,IAAI,CAAEC,CAAM,IAAKA,CAAC,CAACxD,EAAE,KAAKgD,CAAC,CAAC,qBAAxC,kBAA0C1B,MAAM,KAAI,EAAE;MAAC,CACvE3B,IAAI,CAAC,QAAQ,CAAC;;;;ACvVrB;AACA,MAAa8D,MAAM,GAA4C,OAC7DhF,MAAqB,EACrBiF,SAA+B,EAC/BC,MAA+B,EAC/BC,IAAI;EAEJ,MAAMC,OAAO,GAAG,IAAIxF,eAAe,CAACsF,MAAM,EAAElF,MAAM,CAAC;EACnD,MAAMqF,aAAa,GAAGC,mBAAW,CAACtF,MAAM,CAAC;EACzC,MAAMuF,OAAO,GAAGC,aAAK,CAACH,aAAa,CAAC;EAEpC,MAAMI,aAAa,GAAGC,aAAK,CAACH,OAAO,EAAE;IAAEI,KAAK,EAAEP;GAAgB,CAAC;EAC/D,MAAMQ,OAAO,GAAGR,OAAO,CAAC/E,UAAU,EAAE;EAEpC,UAAUuF,gBAAgBH,iBAAiB;AAC7C,CAAC;;;;"} \ No newline at end of file +{"version":3,"file":"graphql-codegen-pydantic.cjs.development.js","sources":["../src/visitor.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable lines-between-class-members */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable react/no-this-in-sfc */\nimport {\n BaseVisitor,\n ParsedConfig,\n buildScalars,\n indent,\n} from '@graphql-codegen/visitor-plugin-common';\nimport {\n NamedTypeNode,\n ListTypeNode,\n NonNullTypeNode,\n GraphQLSchema,\n FieldDefinitionNode,\n ObjectTypeDefinitionNode,\n NameNode,\n UnionTypeDefinitionNode,\n DocumentNode,\n InterfaceTypeDefinitionNode,\n EnumTypeDefinitionNode,\n InputObjectTypeDefinitionNode,\n InputValueDefinitionNode,\n} from 'graphql';\nimport { DepGraph } from 'dependency-graph';\n\nimport { PydanticPluginRawConfig } from './config';\n\nexport const PYTHON_SCALARS = {\n ID: 'str',\n String: 'str',\n Boolean: 'bool',\n Int: 'int',\n Float: 'float',\n};\n\nconst PYTHON_RESERVED = ['from'];\nconst PYDANTIC_MODEL_RESERVED = ['copy'];\nconst RESERVED = PYTHON_RESERVED.concat(PYDANTIC_MODEL_RESERVED);\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PydanticPluginParsedConfig extends ParsedConfig {\n /* intentionally empty for now */\n}\n\nexport class PydanticVisitor extends BaseVisitor<\n PydanticPluginRawConfig,\n PydanticPluginParsedConfig\n> {\n private addOptionalImport = false;\n private addAnyImport = false;\n private addListImport = false;\n private addUnionImport = false;\n private addEnumImport = false;\n private addFieldImport = false;\n\n private graph = new DepGraph({\n circular: false,\n });\n\n constructor(\n rawConfig: PydanticPluginRawConfig,\n private schema: GraphQLSchema,\n ) {\n super(rawConfig, {\n // enumValues: rawConfig.enumValues || {},\n // listType: rawConfig.listType || 'List',\n // package: rawConfig.package || defaultPackageName,\n scalars: buildScalars(schema, {}, PYTHON_SCALARS),\n });\n }\n\n public getImports(): string {\n const typing = [];\n const pydantic = ['BaseModel'];\n\n if (this.addAnyImport) {\n typing.push(`Any`);\n }\n\n if (this.addOptionalImport) {\n typing.push(`Optional`);\n }\n\n if (this.addListImport) {\n typing.push(`List`);\n }\n\n if (this.addUnionImport) {\n typing.push(`Union`);\n }\n\n if (this.addFieldImport) {\n pydantic.push(`Field`);\n }\n\n const enumInput = this.addEnumImport ? 'from enum import StrEnum' : '';\n\n const typingImport = typing.length\n ? `from typing import ${typing.join(', ')}`\n : '';\n\n const pydanticImport = pydantic.length\n ? `from pydantic import ${pydantic.join(', ')}`\n : '';\n\n return [enumInput, typingImport, pydanticImport].filter(i => i).join('\\n');\n }\n\n protected canAddGraphNode(id: string): boolean {\n if (Object.values(this.scalars).includes(id) || id === 'Any') {\n return false;\n }\n\n return true;\n }\n\n protected upsertGraphNode(id: string) {\n if (this.canAddGraphNode(id) && !this.graph.hasNode(id)) {\n this.graph.addNode(id);\n }\n }\n\n protected addGraphNodeDeps(id: string, ids: string[]) {\n if (!this.canAddGraphNode(id)) {\n return;\n }\n\n this.upsertGraphNode(id);\n\n ids.forEach((i: string) => {\n if (!this.canAddGraphNode(i)) {\n return;\n }\n\n this.upsertGraphNode(i);\n\n this.graph.addDependency(id, i);\n });\n }\n\n protected clearOptional(str: string): string {\n if (str.startsWith('Optional[')) {\n return str.replace(/Optional\\[(.*?)\\]$/, '$1');\n }\n\n return str;\n }\n\n Name(node: NameNode) {\n return node.value;\n }\n\n NamedType(node: NamedTypeNode) {\n const { name } = node as any;\n\n // Scalars\n if (Object.keys(this.scalars).includes(name)) {\n const id = this.scalars[name];\n\n // Special case for any\n if (id === 'any') {\n this.addAnyImport = true;\n return {\n id: 'Any',\n source: 'Any',\n };\n }\n\n this.addOptionalImport = true;\n return {\n id,\n source: `Optional[${id}]`,\n };\n }\n\n // Defined\n this.addOptionalImport = true;\n return {\n id: name,\n source: `Optional['${name}']`,\n };\n }\n\n ListType(node: ListTypeNode) {\n this.addListImport = true;\n this.addOptionalImport = true;\n\n const { type } = node as any;\n\n return {\n id: type.id,\n source: `Optional[List[${type.source}]]`,\n };\n }\n\n NonNullType(node: NonNullTypeNode) {\n const { type } = node as any;\n\n return {\n id: type.id,\n source: this.clearOptional(type.source),\n };\n }\n\n protected visitFieldOrInputDefinition(node: any) {\n const argName = node.name as any;\n\n const { type, directives } = node as any;\n\n // Handle deprecated\n // const ds = directives.map((d: any) => d.name);\n // if (ds.includes('deprecated')) {\n // return null;\n // }\n\n // Need to alias some field names\n // Otherwise pydantic throws\n if (RESERVED.includes(argName)) {\n this.addFieldImport = true;\n return {\n id: type.id,\n source: indent(\n `${argName}_: ${type.source} = Field(None, alias='${argName}')`,\n 2,\n ),\n };\n }\n\n return {\n id: type.id,\n source: indent(`${argName}: ${type.source}`, 2),\n };\n }\n\n FieldDefinition(node: FieldDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n InputValueDefinition(node: InputValueDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n EnumTypeDefinition(node: EnumTypeDefinitionNode) {\n this.addEnumImport = true;\n\n const { name, values } = node as any;\n\n const val = values\n .map((v: any) => indent(`${v.name} = '${v.name}'`, 2))\n .join('\\n');\n const source = `class ${name}(StrEnum):\\n${val}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n UnionTypeDefinition(node: UnionTypeDefinitionNode) {\n this.addUnionImport = true;\n\n const { name, types } = node as any;\n\n const unionTypes = (types ?? []).map((t: any) =>\n this.clearOptional(t.source),\n );\n\n this.addGraphNodeDeps(\n name,\n types.map((t: any) => t.id),\n );\n\n return {\n id: name,\n source: `${name} = Union[${unionTypes.join(', ')}]`,\n };\n }\n\n InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.addGraphNodeDeps(\n name,\n fields.map((f: any) => f.id),\n );\n\n return {\n id: name,\n source,\n };\n }\n\n ObjectTypeDefinition(node: ObjectTypeDefinitionNode) {\n const { name, fields: rawFields, interfaces: rawInterfaces } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const interfaces = rawInterfaces.map((n: any) =>\n this.clearOptional(n.source).replace(/'/g, ''),\n );\n\n const impl = interfaces.length ? interfaces.join(', ') : 'BaseModel';\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(${impl}):\\n${args}`;\n\n if (interfaces.length) {\n this.addGraphNodeDeps(name, interfaces);\n } else {\n this.upsertGraphNode(name);\n }\n\n return {\n id: name,\n source,\n };\n }\n\n InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n Document(node: DocumentNode) {\n const { definitions } = node as any;\n\n const nodesInOrder = this.graph.overallOrder();\n\n return nodesInOrder\n .map((n: any) => definitions.find((d: any) => d.id === n)?.source || '')\n .join('\\n\\n\\n');\n }\n}\n","import { parse, GraphQLSchema, printSchema, visit } from 'graphql';\nimport { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';\n\nimport { PydanticVisitor } from './visitor';\nimport { PydanticPluginRawConfig } from './config';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const plugin: PluginFunction = async (\n schema: GraphQLSchema,\n documents: Types.DocumentFile[],\n config: PydanticPluginRawConfig,\n info,\n): Promise => {\n const visitor = new PydanticVisitor(config, schema);\n const printedSchema = printSchema(schema);\n const astNode = parse(printedSchema);\n\n const visitorResult = visit(astNode, { leave: visitor as any });\n const imports = visitor.getImports();\n\n return `${imports}\\n\\n\\n${visitorResult}\\n`;\n};\n"],"names":["PYTHON_SCALARS","ID","String","Boolean","Int","Float","PYTHON_RESERVED","PYDANTIC_MODEL_RESERVED","RESERVED","concat","PydanticVisitor","BaseVisitor","constructor","rawConfig","schema","scalars","buildScalars","DepGraph","circular","getImports","typing","pydantic","addAnyImport","push","addOptionalImport","addListImport","addUnionImport","addFieldImport","enumInput","addEnumImport","typingImport","length","join","pydanticImport","filter","i","canAddGraphNode","id","Object","values","includes","upsertGraphNode","graph","hasNode","addNode","addGraphNodeDeps","ids","forEach","addDependency","clearOptional","str","startsWith","replace","Name","node","value","NamedType","name","keys","source","ListType","type","NonNullType","visitFieldOrInputDefinition","argName","directives","indent","FieldDefinition","InputValueDefinition","EnumTypeDefinition","val","map","v","UnionTypeDefinition","types","unionTypes","t","InterfaceTypeDefinition","fields","rawFields","f","args","ObjectTypeDefinition","interfaces","rawInterfaces","n","impl","InputObjectTypeDefinition","Document","definitions","nodesInOrder","overallOrder","find","d","plugin","documents","config","info","visitor","printedSchema","printSchema","astNode","parse","visitor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D,EAAE,KAAKgD,CAAC,CAAC,qBAAxC,kBAA0C1B,MAAM,KAAI,EAAE;MAAC,CACvE3B,IAAI,CAAC,QAAQ,CAAC;;;;ACvVrB;AACA,MAAa8D,MAAM,GAA4C,OAC7DhF,MAAqB,EACrBiF,SAA+B,EAC/BC,MAA+B,EAC/BC,IAAI;EAEJ,MAAMC,OAAO,GAAG,IAAIxF,eAAe,CAACsF,MAAM,EAAElF,MAAM,CAAC;EACnD,MAAMqF,aAAa,GAAGC,mBAAW,CAACtF,MAAM,CAAC;EACzC,MAAMuF,OAAO,GAAGC,aAAK,CAACH,aAAa,CAAC;EAEpC,MAAMI,aAAa,GAAGC,aAAK,CAACH,OAAO,EAAE;IAAEI,KAAK,EAAEP;GAAgB,CAAC;EAC/D,MAAMQ,OAAO,GAAGR,OAAO,CAAC/E,UAAU,EAAE;EAEpC,UAAUuF,gBAAgBH,iBAAiB;AAC7C,CAAC;;;;"} \ No newline at end of file diff --git a/dist/graphql-codegen-pydantic.cjs.production.min.js b/dist/graphql-codegen-pydantic.cjs.production.min.js index 945f296..d0b41dd 100644 --- a/dist/graphql-codegen-pydantic.cjs.production.min.js +++ b/dist/graphql-codegen-pydantic.cjs.production.min.js @@ -1,2 +1,2 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("graphql"),t=require("@graphql-codegen/visitor-plugin-common"),i=require("dependency-graph");const n={ID:"str",String:"str",Boolean:"bool",Int:"int",Float:"float"},r=["from"].concat(["copy"]);class s extends t.BaseVisitor{constructor(e,r){super(e,{scalars:t.buildScalars(r,{},n)}),this.schema=r,this.addOptionalImport=!1,this.addAnyImport=!1,this.addListImport=!1,this.addUnionImport=!1,this.addEnumImport=!1,this.addFieldImport=!1,this.graph=new i.DepGraph({circular:!1})}getImports(){const e=[],t=["BaseModel"];return this.addAnyImport&&e.push("Any"),this.addOptionalImport&&e.push("Optional"),this.addListImport&&e.push("List"),this.addUnionImport&&e.push("Union"),this.addFieldImport&&t.push("Field"),[this.addEnumImport?"from enum import Enum":"",e.length?"from typing import "+e.join(", "):"",t.length?"from pydantic import "+t.join(", "):""].filter(e=>e).join("\n")}canAddGraphNode(e){return!Object.values(this.scalars).includes(e)&&"Any"!==e}upsertGraphNode(e){this.canAddGraphNode(e)&&!this.graph.hasNode(e)&&this.graph.addNode(e)}addGraphNodeDeps(e,t){this.canAddGraphNode(e)&&(this.upsertGraphNode(e),t.forEach(t=>{this.canAddGraphNode(t)&&(this.upsertGraphNode(t),this.graph.addDependency(e,t))}))}clearOptional(e){return e.startsWith("Optional[")?e.replace(/Optional\[(.*?)\]$/,"$1"):e}Name(e){return e.value}NamedType(e){const{name:t}=e;if(Object.keys(this.scalars).includes(t)){const e=this.scalars[t];return"any"===e?(this.addAnyImport=!0,{id:"Any",source:"Any"}):(this.addOptionalImport=!0,{id:e,source:`Optional[${e}]`})}return this.addOptionalImport=!0,{id:t,source:`Optional['${t}']`}}ListType(e){this.addListImport=!0,this.addOptionalImport=!0;const{type:t}=e;return{id:t.id,source:`Optional[List[${t.source}]]`}}NonNullType(e){const{type:t}=e;return{id:t.id,source:this.clearOptional(t.source)}}visitFieldOrInputDefinition(e){const i=e.name,{type:n}=e;return r.includes(i)?(this.addFieldImport=!0,{id:n.id,source:t.indent(`${i}_: ${n.source} = Field(None, alias='${i}')`,2)}):{id:n.id,source:t.indent(`${i}: ${n.source}`,2)}}FieldDefinition(e){return this.visitFieldOrInputDefinition(e)}InputValueDefinition(e){return this.visitFieldOrInputDefinition(e)}EnumTypeDefinition(e){this.addEnumImport=!0;const{name:i,values:n}=e,r=`class ${i}(str, Enum):\n${n.map(e=>t.indent(`${e.name} = '${e.name}'`,2)).join("\n")}`;return this.upsertGraphNode(i),{id:i,source:r}}UnionTypeDefinition(e){this.addUnionImport=!0;const{name:t,types:i}=e,n=(null!=i?i:[]).map(e=>this.clearOptional(e.source));return this.addGraphNodeDeps(t,i.map(e=>e.id)),{id:t,source:`${t} = Union[${n.join(", ")}]`}}InterfaceTypeDefinition(e){const{name:t,fields:i}=e,n=i.filter(e=>e),r=`class ${t}(BaseModel):\n${n.map(e=>e.source).join("\n")}`;return this.addGraphNodeDeps(t,n.map(e=>e.id)),{id:t,source:r}}ObjectTypeDefinition(e){const{name:t,fields:i,interfaces:n}=e,r=i.filter(e=>e),s=n.map(e=>this.clearOptional(e.source).replace(/'/g,"")),o=`class ${t}(${s.length?s.join(", "):"BaseModel"}):\n${r.map(e=>e.source).join("\n")}`;return s.length?this.addGraphNodeDeps(t,s):this.upsertGraphNode(t),{id:t,source:o}}InputObjectTypeDefinition(e){const{name:t,fields:i}=e,n=`class ${t}(BaseModel):\n${i.filter(e=>e).map(e=>e.source).join("\n")}`;return this.upsertGraphNode(t),{id:t,source:n}}Document(e){const{definitions:t}=e;return this.graph.overallOrder().map(e=>{var i;return(null==(i=t.find(t=>t.id===e))?void 0:i.source)||""}).join("\n\n\n")}}exports.plugin=async(t,i,n,r)=>{const o=new s(n,t),a=e.printSchema(t),d=e.parse(a),p=e.visit(d,{leave:o});return`${o.getImports()}\n\n\n${p}\n`}; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("graphql"),e=require("@graphql-codegen/visitor-plugin-common"),i=require("dependency-graph");const n={ID:"str",String:"str",Boolean:"bool",Int:"int",Float:"float"},r=["from"].concat(["copy"]);class s extends e.BaseVisitor{constructor(t,r){super(t,{scalars:e.buildScalars(r,{},n)}),this.schema=r,this.addOptionalImport=!1,this.addAnyImport=!1,this.addListImport=!1,this.addUnionImport=!1,this.addEnumImport=!1,this.addFieldImport=!1,this.graph=new i.DepGraph({circular:!1})}getImports(){const t=[],e=["BaseModel"];return this.addAnyImport&&t.push("Any"),this.addOptionalImport&&t.push("Optional"),this.addListImport&&t.push("List"),this.addUnionImport&&t.push("Union"),this.addFieldImport&&e.push("Field"),[this.addEnumImport?"from enum import StrEnum":"",t.length?"from typing import "+t.join(", "):"",e.length?"from pydantic import "+e.join(", "):""].filter(t=>t).join("\n")}canAddGraphNode(t){return!Object.values(this.scalars).includes(t)&&"Any"!==t}upsertGraphNode(t){this.canAddGraphNode(t)&&!this.graph.hasNode(t)&&this.graph.addNode(t)}addGraphNodeDeps(t,e){this.canAddGraphNode(t)&&(this.upsertGraphNode(t),e.forEach(e=>{this.canAddGraphNode(e)&&(this.upsertGraphNode(e),this.graph.addDependency(t,e))}))}clearOptional(t){return t.startsWith("Optional[")?t.replace(/Optional\[(.*?)\]$/,"$1"):t}Name(t){return t.value}NamedType(t){const{name:e}=t;if(Object.keys(this.scalars).includes(e)){const t=this.scalars[e];return"any"===t?(this.addAnyImport=!0,{id:"Any",source:"Any"}):(this.addOptionalImport=!0,{id:t,source:`Optional[${t}]`})}return this.addOptionalImport=!0,{id:e,source:`Optional['${e}']`}}ListType(t){this.addListImport=!0,this.addOptionalImport=!0;const{type:e}=t;return{id:e.id,source:`Optional[List[${e.source}]]`}}NonNullType(t){const{type:e}=t;return{id:e.id,source:this.clearOptional(e.source)}}visitFieldOrInputDefinition(t){const i=t.name,{type:n}=t;return r.includes(i)?(this.addFieldImport=!0,{id:n.id,source:e.indent(`${i}_: ${n.source} = Field(None, alias='${i}')`,2)}):{id:n.id,source:e.indent(`${i}: ${n.source}`,2)}}FieldDefinition(t){return this.visitFieldOrInputDefinition(t)}InputValueDefinition(t){return this.visitFieldOrInputDefinition(t)}EnumTypeDefinition(t){this.addEnumImport=!0;const{name:i,values:n}=t,r=`class ${i}(StrEnum):\n${n.map(t=>e.indent(`${t.name} = '${t.name}'`,2)).join("\n")}`;return this.upsertGraphNode(i),{id:i,source:r}}UnionTypeDefinition(t){this.addUnionImport=!0;const{name:e,types:i}=t,n=(null!=i?i:[]).map(t=>this.clearOptional(t.source));return this.addGraphNodeDeps(e,i.map(t=>t.id)),{id:e,source:`${e} = Union[${n.join(", ")}]`}}InterfaceTypeDefinition(t){const{name:e,fields:i}=t,n=i.filter(t=>t),r=`class ${e}(BaseModel):\n${n.map(t=>t.source).join("\n")}`;return this.addGraphNodeDeps(e,n.map(t=>t.id)),{id:e,source:r}}ObjectTypeDefinition(t){const{name:e,fields:i,interfaces:n}=t,r=i.filter(t=>t),s=n.map(t=>this.clearOptional(t.source).replace(/'/g,"")),o=`class ${e}(${s.length?s.join(", "):"BaseModel"}):\n${r.map(t=>t.source).join("\n")}`;return s.length?this.addGraphNodeDeps(e,s):this.upsertGraphNode(e),{id:e,source:o}}InputObjectTypeDefinition(t){const{name:e,fields:i}=t,n=`class ${e}(BaseModel):\n${i.filter(t=>t).map(t=>t.source).join("\n")}`;return this.upsertGraphNode(e),{id:e,source:n}}Document(t){const{definitions:e}=t;return this.graph.overallOrder().map(t=>{var i;return(null==(i=e.find(e=>e.id===t))?void 0:i.source)||""}).join("\n\n\n")}}exports.plugin=async(e,i,n,r)=>{const o=new s(n,e),a=t.printSchema(e),d=t.parse(a),p=t.visit(d,{leave:o});return`${o.getImports()}\n\n\n${p}\n`}; //# sourceMappingURL=graphql-codegen-pydantic.cjs.production.min.js.map diff --git a/dist/graphql-codegen-pydantic.cjs.production.min.js.map b/dist/graphql-codegen-pydantic.cjs.production.min.js.map index b0d3afa..5eb8770 100644 --- a/dist/graphql-codegen-pydantic.cjs.production.min.js.map +++ b/dist/graphql-codegen-pydantic.cjs.production.min.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-codegen-pydantic.cjs.production.min.js","sources":["../src/visitor.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable lines-between-class-members */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable react/no-this-in-sfc */\nimport {\n BaseVisitor,\n ParsedConfig,\n buildScalars,\n indent,\n} from '@graphql-codegen/visitor-plugin-common';\nimport {\n NamedTypeNode,\n ListTypeNode,\n NonNullTypeNode,\n GraphQLSchema,\n FieldDefinitionNode,\n ObjectTypeDefinitionNode,\n NameNode,\n UnionTypeDefinitionNode,\n DocumentNode,\n InterfaceTypeDefinitionNode,\n EnumTypeDefinitionNode,\n InputObjectTypeDefinitionNode,\n InputValueDefinitionNode,\n} from 'graphql';\nimport { DepGraph } from 'dependency-graph';\n\nimport { PydanticPluginRawConfig } from './config';\n\nexport const PYTHON_SCALARS = {\n ID: 'str',\n String: 'str',\n Boolean: 'bool',\n Int: 'int',\n Float: 'float',\n};\n\nconst PYTHON_RESERVED = ['from'];\nconst PYDANTIC_MODEL_RESERVED = ['copy'];\nconst RESERVED = PYTHON_RESERVED.concat(PYDANTIC_MODEL_RESERVED);\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PydanticPluginParsedConfig extends ParsedConfig {\n /* intentionally empty for now */\n}\n\nexport class PydanticVisitor extends BaseVisitor<\n PydanticPluginRawConfig,\n PydanticPluginParsedConfig\n> {\n private addOptionalImport = false;\n private addAnyImport = false;\n private addListImport = false;\n private addUnionImport = false;\n private addEnumImport = false;\n private addFieldImport = false;\n\n private graph = new DepGraph({\n circular: false,\n });\n\n constructor(\n rawConfig: PydanticPluginRawConfig,\n private schema: GraphQLSchema,\n ) {\n super(rawConfig, {\n // enumValues: rawConfig.enumValues || {},\n // listType: rawConfig.listType || 'List',\n // package: rawConfig.package || defaultPackageName,\n scalars: buildScalars(schema, {}, PYTHON_SCALARS),\n });\n }\n\n public getImports(): string {\n const typing = [];\n const pydantic = ['BaseModel'];\n\n if (this.addAnyImport) {\n typing.push(`Any`);\n }\n\n if (this.addOptionalImport) {\n typing.push(`Optional`);\n }\n\n if (this.addListImport) {\n typing.push(`List`);\n }\n\n if (this.addUnionImport) {\n typing.push(`Union`);\n }\n\n if (this.addFieldImport) {\n pydantic.push(`Field`);\n }\n\n const enumInput = this.addEnumImport ? 'from enum import Enum' : '';\n\n const typingImport = typing.length\n ? `from typing import ${typing.join(', ')}`\n : '';\n\n const pydanticImport = pydantic.length\n ? `from pydantic import ${pydantic.join(', ')}`\n : '';\n\n return [enumInput, typingImport, pydanticImport].filter(i => i).join('\\n');\n }\n\n protected canAddGraphNode(id: string): boolean {\n if (Object.values(this.scalars).includes(id) || id === 'Any') {\n return false;\n }\n\n return true;\n }\n\n protected upsertGraphNode(id: string) {\n if (this.canAddGraphNode(id) && !this.graph.hasNode(id)) {\n this.graph.addNode(id);\n }\n }\n\n protected addGraphNodeDeps(id: string, ids: string[]) {\n if (!this.canAddGraphNode(id)) {\n return;\n }\n\n this.upsertGraphNode(id);\n\n ids.forEach((i: string) => {\n if (!this.canAddGraphNode(i)) {\n return;\n }\n\n this.upsertGraphNode(i);\n\n this.graph.addDependency(id, i);\n });\n }\n\n protected clearOptional(str: string): string {\n if (str.startsWith('Optional[')) {\n return str.replace(/Optional\\[(.*?)\\]$/, '$1');\n }\n\n return str;\n }\n\n Name(node: NameNode) {\n return node.value;\n }\n\n NamedType(node: NamedTypeNode) {\n const { name } = node as any;\n\n // Scalars\n if (Object.keys(this.scalars).includes(name)) {\n const id = this.scalars[name];\n\n // Special case for any\n if (id === 'any') {\n this.addAnyImport = true;\n return {\n id: 'Any',\n source: 'Any',\n };\n }\n\n this.addOptionalImport = true;\n return {\n id,\n source: `Optional[${id}]`,\n };\n }\n\n // Defined\n this.addOptionalImport = true;\n return {\n id: name,\n source: `Optional['${name}']`,\n };\n }\n\n ListType(node: ListTypeNode) {\n this.addListImport = true;\n this.addOptionalImport = true;\n\n const { type } = node as any;\n\n return {\n id: type.id,\n source: `Optional[List[${type.source}]]`,\n };\n }\n\n NonNullType(node: NonNullTypeNode) {\n const { type } = node as any;\n\n return {\n id: type.id,\n source: this.clearOptional(type.source),\n };\n }\n\n protected visitFieldOrInputDefinition(node: any) {\n const argName = node.name as any;\n\n const { type, directives } = node as any;\n\n // Handle deprecated\n // const ds = directives.map((d: any) => d.name);\n // if (ds.includes('deprecated')) {\n // return null;\n // }\n\n // Need to alias some field names\n // Otherwise pydantic throws\n if (RESERVED.includes(argName)) {\n this.addFieldImport = true;\n return {\n id: type.id,\n source: indent(\n `${argName}_: ${type.source} = Field(None, alias='${argName}')`,\n 2,\n ),\n };\n }\n\n return {\n id: type.id,\n source: indent(`${argName}: ${type.source}`, 2),\n };\n }\n\n FieldDefinition(node: FieldDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n InputValueDefinition(node: InputValueDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n EnumTypeDefinition(node: EnumTypeDefinitionNode) {\n this.addEnumImport = true;\n\n const { name, values } = node as any;\n\n const val = values\n .map((v: any) => indent(`${v.name} = '${v.name}'`, 2))\n .join('\\n');\n const source = `class ${name}(str, Enum):\\n${val}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n UnionTypeDefinition(node: UnionTypeDefinitionNode) {\n this.addUnionImport = true;\n\n const { name, types } = node as any;\n\n const unionTypes = (types ?? []).map((t: any) =>\n this.clearOptional(t.source),\n );\n\n this.addGraphNodeDeps(\n name,\n types.map((t: any) => t.id),\n );\n\n return {\n id: name,\n source: `${name} = Union[${unionTypes.join(', ')}]`,\n };\n }\n\n InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.addGraphNodeDeps(\n name,\n fields.map((f: any) => f.id),\n );\n\n return {\n id: name,\n source,\n };\n }\n\n ObjectTypeDefinition(node: ObjectTypeDefinitionNode) {\n const { name, fields: rawFields, interfaces: rawInterfaces } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const interfaces = rawInterfaces.map((n: any) =>\n this.clearOptional(n.source).replace(/'/g, ''),\n );\n\n const impl = interfaces.length ? interfaces.join(', ') : 'BaseModel';\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(${impl}):\\n${args}`;\n\n if (interfaces.length) {\n this.addGraphNodeDeps(name, interfaces);\n } else {\n this.upsertGraphNode(name);\n }\n\n return {\n id: name,\n source,\n };\n }\n\n InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n Document(node: DocumentNode) {\n const { definitions } = node as any;\n\n const nodesInOrder = this.graph.overallOrder();\n\n return nodesInOrder\n .map((n: any) => definitions.find((d: any) => d.id === n)?.source || '')\n .join('\\n\\n\\n');\n }\n}\n","import { parse, GraphQLSchema, printSchema, visit } from 'graphql';\nimport { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';\n\nimport { PydanticVisitor } from './visitor';\nimport { PydanticPluginRawConfig } from './config';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const plugin: PluginFunction = async (\n schema: GraphQLSchema,\n documents: Types.DocumentFile[],\n config: PydanticPluginRawConfig,\n info,\n): Promise => {\n const visitor = new PydanticVisitor(config, schema);\n const printedSchema = printSchema(schema);\n const astNode = parse(printedSchema);\n\n const visitorResult = visit(astNode, { leave: visitor as any });\n const imports = visitor.getImports();\n\n return `${imports}\\n\\n\\n${visitorResult}\\n`;\n};\n"],"names":["PYTHON_SCALARS","ID","String","Boolean","Int","Float","RESERVED","concat","PydanticVisitor","BaseVisitor","constructor","rawConfig","schema","super","scalars","buildScalars","this","DepGraph","circular","getImports","typing","pydantic","addAnyImport","push","addOptionalImport","addListImport","addUnionImport","addFieldImport","addEnumImport","length","join","filter","i","canAddGraphNode","id","Object","values","includes","upsertGraphNode","graph","hasNode","addNode","addGraphNodeDeps","ids","forEach","addDependency","clearOptional","str","startsWith","replace","Name","node","value","NamedType","name","keys","source","ListType","type","NonNullType","visitFieldOrInputDefinition","argName","indent","FieldDefinition","InputValueDefinition","EnumTypeDefinition","map","v","UnionTypeDefinition","types","unionTypes","t","InterfaceTypeDefinition","fields","rawFields","f","ObjectTypeDefinition","interfaces","rawInterfaces","n","InputObjectTypeDefinition","Document","definitions","overallOrder","find","d","_definitions$find","async","documents","config","info","visitor","printedSchema","printSchema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CACLpB,GAAIoB,EACJE,OAAAA,GAIJyB,SAAS9B,GACP,MAAM+B,YAAEA,GAAgB/B,EAIxB,OAFqBnC,KAAKuB,MAAM4C,eAG7BjB,IAAKa,IAAM,MAAA,gBAAKG,EAAYE,KAAMC,GAAWA,EAAEnD,KAAO6C,WAAtCO,EAA0C9B,SAAU,KACpE1B,KAAK,0BCtVmDyD,MAC7D3E,EACA4E,EACAC,EACAC,KAEA,MAAMC,EAAU,IAAInF,EAAgBiF,EAAQ7E,GACtCgF,EAAgBC,cAAYjF,GAC5BkF,EAAUC,QAAMH,GAEhBI,EAAgBC,QAAMH,EAAS,CAAEI,MAAOP,IAG9C,SAFgBA,EAAQxE,qBAEE6E"} \ No newline at end of file +{"version":3,"file":"graphql-codegen-pydantic.cjs.production.min.js","sources":["../src/visitor.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable lines-between-class-members */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable react/no-this-in-sfc */\nimport {\n BaseVisitor,\n ParsedConfig,\n buildScalars,\n indent,\n} from '@graphql-codegen/visitor-plugin-common';\nimport {\n NamedTypeNode,\n ListTypeNode,\n NonNullTypeNode,\n GraphQLSchema,\n FieldDefinitionNode,\n ObjectTypeDefinitionNode,\n NameNode,\n UnionTypeDefinitionNode,\n DocumentNode,\n InterfaceTypeDefinitionNode,\n EnumTypeDefinitionNode,\n InputObjectTypeDefinitionNode,\n InputValueDefinitionNode,\n} from 'graphql';\nimport { DepGraph } from 'dependency-graph';\n\nimport { PydanticPluginRawConfig } from './config';\n\nexport const PYTHON_SCALARS = {\n ID: 'str',\n String: 'str',\n Boolean: 'bool',\n Int: 'int',\n Float: 'float',\n};\n\nconst PYTHON_RESERVED = ['from'];\nconst PYDANTIC_MODEL_RESERVED = ['copy'];\nconst RESERVED = PYTHON_RESERVED.concat(PYDANTIC_MODEL_RESERVED);\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PydanticPluginParsedConfig extends ParsedConfig {\n /* intentionally empty for now */\n}\n\nexport class PydanticVisitor extends BaseVisitor<\n PydanticPluginRawConfig,\n PydanticPluginParsedConfig\n> {\n private addOptionalImport = false;\n private addAnyImport = false;\n private addListImport = false;\n private addUnionImport = false;\n private addEnumImport = false;\n private addFieldImport = false;\n\n private graph = new DepGraph({\n circular: false,\n });\n\n constructor(\n rawConfig: PydanticPluginRawConfig,\n private schema: GraphQLSchema,\n ) {\n super(rawConfig, {\n // enumValues: rawConfig.enumValues || {},\n // listType: rawConfig.listType || 'List',\n // package: rawConfig.package || defaultPackageName,\n scalars: buildScalars(schema, {}, PYTHON_SCALARS),\n });\n }\n\n public getImports(): string {\n const typing = [];\n const pydantic = ['BaseModel'];\n\n if (this.addAnyImport) {\n typing.push(`Any`);\n }\n\n if (this.addOptionalImport) {\n typing.push(`Optional`);\n }\n\n if (this.addListImport) {\n typing.push(`List`);\n }\n\n if (this.addUnionImport) {\n typing.push(`Union`);\n }\n\n if (this.addFieldImport) {\n pydantic.push(`Field`);\n }\n\n const enumInput = this.addEnumImport ? 'from enum import StrEnum' : '';\n\n const typingImport = typing.length\n ? `from typing import ${typing.join(', ')}`\n : '';\n\n const pydanticImport = pydantic.length\n ? `from pydantic import ${pydantic.join(', ')}`\n : '';\n\n return [enumInput, typingImport, pydanticImport].filter(i => i).join('\\n');\n }\n\n protected canAddGraphNode(id: string): boolean {\n if (Object.values(this.scalars).includes(id) || id === 'Any') {\n return false;\n }\n\n return true;\n }\n\n protected upsertGraphNode(id: string) {\n if (this.canAddGraphNode(id) && !this.graph.hasNode(id)) {\n this.graph.addNode(id);\n }\n }\n\n protected addGraphNodeDeps(id: string, ids: string[]) {\n if (!this.canAddGraphNode(id)) {\n return;\n }\n\n this.upsertGraphNode(id);\n\n ids.forEach((i: string) => {\n if (!this.canAddGraphNode(i)) {\n return;\n }\n\n this.upsertGraphNode(i);\n\n this.graph.addDependency(id, i);\n });\n }\n\n protected clearOptional(str: string): string {\n if (str.startsWith('Optional[')) {\n return str.replace(/Optional\\[(.*?)\\]$/, '$1');\n }\n\n return str;\n }\n\n Name(node: NameNode) {\n return node.value;\n }\n\n NamedType(node: NamedTypeNode) {\n const { name } = node as any;\n\n // Scalars\n if (Object.keys(this.scalars).includes(name)) {\n const id = this.scalars[name];\n\n // Special case for any\n if (id === 'any') {\n this.addAnyImport = true;\n return {\n id: 'Any',\n source: 'Any',\n };\n }\n\n this.addOptionalImport = true;\n return {\n id,\n source: `Optional[${id}]`,\n };\n }\n\n // Defined\n this.addOptionalImport = true;\n return {\n id: name,\n source: `Optional['${name}']`,\n };\n }\n\n ListType(node: ListTypeNode) {\n this.addListImport = true;\n this.addOptionalImport = true;\n\n const { type } = node as any;\n\n return {\n id: type.id,\n source: `Optional[List[${type.source}]]`,\n };\n }\n\n NonNullType(node: NonNullTypeNode) {\n const { type } = node as any;\n\n return {\n id: type.id,\n source: this.clearOptional(type.source),\n };\n }\n\n protected visitFieldOrInputDefinition(node: any) {\n const argName = node.name as any;\n\n const { type, directives } = node as any;\n\n // Handle deprecated\n // const ds = directives.map((d: any) => d.name);\n // if (ds.includes('deprecated')) {\n // return null;\n // }\n\n // Need to alias some field names\n // Otherwise pydantic throws\n if (RESERVED.includes(argName)) {\n this.addFieldImport = true;\n return {\n id: type.id,\n source: indent(\n `${argName}_: ${type.source} = Field(None, alias='${argName}')`,\n 2,\n ),\n };\n }\n\n return {\n id: type.id,\n source: indent(`${argName}: ${type.source}`, 2),\n };\n }\n\n FieldDefinition(node: FieldDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n InputValueDefinition(node: InputValueDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n EnumTypeDefinition(node: EnumTypeDefinitionNode) {\n this.addEnumImport = true;\n\n const { name, values } = node as any;\n\n const val = values\n .map((v: any) => indent(`${v.name} = '${v.name}'`, 2))\n .join('\\n');\n const source = `class ${name}(StrEnum):\\n${val}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n UnionTypeDefinition(node: UnionTypeDefinitionNode) {\n this.addUnionImport = true;\n\n const { name, types } = node as any;\n\n const unionTypes = (types ?? []).map((t: any) =>\n this.clearOptional(t.source),\n );\n\n this.addGraphNodeDeps(\n name,\n types.map((t: any) => t.id),\n );\n\n return {\n id: name,\n source: `${name} = Union[${unionTypes.join(', ')}]`,\n };\n }\n\n InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.addGraphNodeDeps(\n name,\n fields.map((f: any) => f.id),\n );\n\n return {\n id: name,\n source,\n };\n }\n\n ObjectTypeDefinition(node: ObjectTypeDefinitionNode) {\n const { name, fields: rawFields, interfaces: rawInterfaces } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const interfaces = rawInterfaces.map((n: any) =>\n this.clearOptional(n.source).replace(/'/g, ''),\n );\n\n const impl = interfaces.length ? interfaces.join(', ') : 'BaseModel';\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(${impl}):\\n${args}`;\n\n if (interfaces.length) {\n this.addGraphNodeDeps(name, interfaces);\n } else {\n this.upsertGraphNode(name);\n }\n\n return {\n id: name,\n source,\n };\n }\n\n InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n Document(node: DocumentNode) {\n const { definitions } = node as any;\n\n const nodesInOrder = this.graph.overallOrder();\n\n return nodesInOrder\n .map((n: any) => definitions.find((d: any) => d.id === n)?.source || '')\n .join('\\n\\n\\n');\n }\n}\n","import { parse, GraphQLSchema, printSchema, visit } from 'graphql';\nimport { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';\n\nimport { PydanticVisitor } from './visitor';\nimport { PydanticPluginRawConfig } from './config';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const plugin: PluginFunction = async (\n schema: GraphQLSchema,\n documents: Types.DocumentFile[],\n config: PydanticPluginRawConfig,\n info,\n): Promise => {\n const visitor = new PydanticVisitor(config, schema);\n const printedSchema = printSchema(schema);\n const astNode = parse(printedSchema);\n\n const visitorResult = visit(astNode, { leave: visitor as any });\n const imports = visitor.getImports();\n\n return `${imports}\\n\\n\\n${visitorResult}\\n`;\n};\n"],"names":["PYTHON_SCALARS","ID","String","Boolean","Int","Float","RESERVED","concat","PydanticVisitor","BaseVisitor","constructor","rawConfig","schema","super","scalars","buildScalars","this","DepGraph","circular","getImports","typing","pydantic","addAnyImport","push","addOptionalImport","addListImport","addUnionImport","addFieldImport","addEnumImport","length","join","filter","i","canAddGraphNode","id","Object","values","includes","upsertGraphNode","graph","hasNode","addNode","addGraphNodeDeps","ids","forEach","addDependency","clearOptional","str","startsWith","replace","Name","node","value","NamedType","name","keys","source","ListType","type","NonNullType","visitFieldOrInputDefinition","argName","indent","FieldDefinition","InputValueDefinition","EnumTypeDefinition","map","v","UnionTypeDefinition","types","unionTypes","t","InterfaceTypeDefinition","fields","rawFields","f","ObjectTypeDefinition","interfaces","rawInterfaces","n","InputObjectTypeDefinition","Document","definitions","overallOrder","find","d","_definitions$find","async","documents","config","info","visitor","printedSchema","printSchema","astNode","parse","visitorResult","visit","leave"],"mappings":"+KA4BO,MAAMA,EAAiB,CAC5BC,GAAI,MACJC,OAAQ,MACRC,QAAS,OACTC,IAAK,MACLC,MAAO,SAKHC,EAFkB,CAAC,QAEQC,OADD,CAAC,eAQpBC,UAAwBC,cAenCC,YACEC,EACQC,GAERC,MAAMF,EAAW,CAIfG,QAASC,eAAaH,EAAQ,GAAIZ,KAN5BgB,YAAAJ,EAbFI,wBAAoB,EACpBA,mBAAe,EACfA,oBAAgB,EAChBA,qBAAiB,EACj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YjF,GAC5BkF,EAAUC,QAAMH,GAEhBI,EAAgBC,QAAMH,EAAS,CAAEI,MAAOP,IAG9C,SAFgBA,EAAQxE,qBAEE6E"} \ No newline at end of file diff --git a/dist/graphql-codegen-pydantic.esm.js b/dist/graphql-codegen-pydantic.esm.js index 41fb838..d69a0f8 100644 --- a/dist/graphql-codegen-pydantic.esm.js +++ b/dist/graphql-codegen-pydantic.esm.js @@ -50,7 +50,7 @@ class PydanticVisitor extends BaseVisitor { if (this.addFieldImport) { pydantic.push(`Field`); } - const enumInput = this.addEnumImport ? 'from enum import Enum' : ''; + const enumInput = this.addEnumImport ? 'from enum import StrEnum' : ''; const typingImport = typing.length ? `from typing import ${typing.join(', ')}` : ''; const pydanticImport = pydantic.length ? `from pydantic import ${pydantic.join(', ')}` : ''; return [enumInput, typingImport, pydanticImport].filter(i => i).join('\n'); @@ -174,7 +174,7 @@ class PydanticVisitor extends BaseVisitor { values } = node; const val = values.map(v => indent(`${v.name} = '${v.name}'`, 2)).join('\n'); - const source = `class ${name}(str, Enum):\n${val}`; + const source = `class ${name}(StrEnum):\n${val}`; this.upsertGraphNode(name); return { id: name, diff --git a/dist/graphql-codegen-pydantic.esm.js.map b/dist/graphql-codegen-pydantic.esm.js.map index 97369f9..8639a06 100644 --- a/dist/graphql-codegen-pydantic.esm.js.map +++ b/dist/graphql-codegen-pydantic.esm.js.map @@ -1 +1 @@ -{"version":3,"file":"graphql-codegen-pydantic.esm.js","sources":["../src/visitor.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable lines-between-class-members */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable react/no-this-in-sfc */\nimport {\n BaseVisitor,\n ParsedConfig,\n buildScalars,\n indent,\n} from '@graphql-codegen/visitor-plugin-common';\nimport {\n NamedTypeNode,\n ListTypeNode,\n NonNullTypeNode,\n GraphQLSchema,\n FieldDefinitionNode,\n ObjectTypeDefinitionNode,\n NameNode,\n UnionTypeDefinitionNode,\n DocumentNode,\n InterfaceTypeDefinitionNode,\n EnumTypeDefinitionNode,\n InputObjectTypeDefinitionNode,\n InputValueDefinitionNode,\n} from 'graphql';\nimport { DepGraph } from 'dependency-graph';\n\nimport { PydanticPluginRawConfig } from './config';\n\nexport const PYTHON_SCALARS = {\n ID: 'str',\n String: 'str',\n Boolean: 'bool',\n Int: 'int',\n Float: 'float',\n};\n\nconst PYTHON_RESERVED = ['from'];\nconst PYDANTIC_MODEL_RESERVED = ['copy'];\nconst RESERVED = PYTHON_RESERVED.concat(PYDANTIC_MODEL_RESERVED);\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PydanticPluginParsedConfig extends ParsedConfig {\n /* intentionally empty for now */\n}\n\nexport class PydanticVisitor extends BaseVisitor<\n PydanticPluginRawConfig,\n PydanticPluginParsedConfig\n> {\n private addOptionalImport = false;\n private addAnyImport = false;\n private addListImport = false;\n private addUnionImport = false;\n private addEnumImport = false;\n private addFieldImport = false;\n\n private graph = new DepGraph({\n circular: false,\n });\n\n constructor(\n rawConfig: PydanticPluginRawConfig,\n private schema: GraphQLSchema,\n ) {\n super(rawConfig, {\n // enumValues: rawConfig.enumValues || {},\n // listType: rawConfig.listType || 'List',\n // package: rawConfig.package || defaultPackageName,\n scalars: buildScalars(schema, {}, PYTHON_SCALARS),\n });\n }\n\n public getImports(): string {\n const typing = [];\n const pydantic = ['BaseModel'];\n\n if (this.addAnyImport) {\n typing.push(`Any`);\n }\n\n if (this.addOptionalImport) {\n typing.push(`Optional`);\n }\n\n if (this.addListImport) {\n typing.push(`List`);\n }\n\n if (this.addUnionImport) {\n typing.push(`Union`);\n }\n\n if (this.addFieldImport) {\n pydantic.push(`Field`);\n }\n\n const enumInput = this.addEnumImport ? 'from enum import Enum' : '';\n\n const typingImport = typing.length\n ? `from typing import ${typing.join(', ')}`\n : '';\n\n const pydanticImport = pydantic.length\n ? `from pydantic import ${pydantic.join(', ')}`\n : '';\n\n return [enumInput, typingImport, pydanticImport].filter(i => i).join('\\n');\n }\n\n protected canAddGraphNode(id: string): boolean {\n if (Object.values(this.scalars).includes(id) || id === 'Any') {\n return false;\n }\n\n return true;\n }\n\n protected upsertGraphNode(id: string) {\n if (this.canAddGraphNode(id) && !this.graph.hasNode(id)) {\n this.graph.addNode(id);\n }\n }\n\n protected addGraphNodeDeps(id: string, ids: string[]) {\n if (!this.canAddGraphNode(id)) {\n return;\n }\n\n this.upsertGraphNode(id);\n\n ids.forEach((i: string) => {\n if (!this.canAddGraphNode(i)) {\n return;\n }\n\n this.upsertGraphNode(i);\n\n this.graph.addDependency(id, i);\n });\n }\n\n protected clearOptional(str: string): string {\n if (str.startsWith('Optional[')) {\n return str.replace(/Optional\\[(.*?)\\]$/, '$1');\n }\n\n return str;\n }\n\n Name(node: NameNode) {\n return node.value;\n }\n\n NamedType(node: NamedTypeNode) {\n const { name } = node as any;\n\n // Scalars\n if (Object.keys(this.scalars).includes(name)) {\n const id = this.scalars[name];\n\n // Special case for any\n if (id === 'any') {\n this.addAnyImport = true;\n return {\n id: 'Any',\n source: 'Any',\n };\n }\n\n this.addOptionalImport = true;\n return {\n id,\n source: `Optional[${id}]`,\n };\n }\n\n // Defined\n this.addOptionalImport = true;\n return {\n id: name,\n source: `Optional['${name}']`,\n };\n }\n\n ListType(node: ListTypeNode) {\n this.addListImport = true;\n this.addOptionalImport = true;\n\n const { type } = node as any;\n\n return {\n id: type.id,\n source: `Optional[List[${type.source}]]`,\n };\n }\n\n NonNullType(node: NonNullTypeNode) {\n const { type } = node as any;\n\n return {\n id: type.id,\n source: this.clearOptional(type.source),\n };\n }\n\n protected visitFieldOrInputDefinition(node: any) {\n const argName = node.name as any;\n\n const { type, directives } = node as any;\n\n // Handle deprecated\n // const ds = directives.map((d: any) => d.name);\n // if (ds.includes('deprecated')) {\n // return null;\n // }\n\n // Need to alias some field names\n // Otherwise pydantic throws\n if (RESERVED.includes(argName)) {\n this.addFieldImport = true;\n return {\n id: type.id,\n source: indent(\n `${argName}_: ${type.source} = Field(None, alias='${argName}')`,\n 2,\n ),\n };\n }\n\n return {\n id: type.id,\n source: indent(`${argName}: ${type.source}`, 2),\n };\n }\n\n FieldDefinition(node: FieldDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n InputValueDefinition(node: InputValueDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n EnumTypeDefinition(node: EnumTypeDefinitionNode) {\n this.addEnumImport = true;\n\n const { name, values } = node as any;\n\n const val = values\n .map((v: any) => indent(`${v.name} = '${v.name}'`, 2))\n .join('\\n');\n const source = `class ${name}(str, Enum):\\n${val}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n UnionTypeDefinition(node: UnionTypeDefinitionNode) {\n this.addUnionImport = true;\n\n const { name, types } = node as any;\n\n const unionTypes = (types ?? []).map((t: any) =>\n this.clearOptional(t.source),\n );\n\n this.addGraphNodeDeps(\n name,\n types.map((t: any) => t.id),\n );\n\n return {\n id: name,\n source: `${name} = Union[${unionTypes.join(', ')}]`,\n };\n }\n\n InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.addGraphNodeDeps(\n name,\n fields.map((f: any) => f.id),\n );\n\n return {\n id: name,\n source,\n };\n }\n\n ObjectTypeDefinition(node: ObjectTypeDefinitionNode) {\n const { name, fields: rawFields, interfaces: rawInterfaces } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const interfaces = rawInterfaces.map((n: any) =>\n this.clearOptional(n.source).replace(/'/g, ''),\n );\n\n const impl = interfaces.length ? interfaces.join(', ') : 'BaseModel';\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(${impl}):\\n${args}`;\n\n if (interfaces.length) {\n this.addGraphNodeDeps(name, interfaces);\n } else {\n this.upsertGraphNode(name);\n }\n\n return {\n id: name,\n source,\n };\n }\n\n InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n Document(node: DocumentNode) {\n const { definitions } = node as any;\n\n const nodesInOrder = this.graph.overallOrder();\n\n return nodesInOrder\n .map((n: any) => definitions.find((d: any) => d.id === n)?.source || '')\n .join('\\n\\n\\n');\n }\n}\n","import { parse, GraphQLSchema, printSchema, visit } from 'graphql';\nimport { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';\n\nimport { PydanticVisitor } from './visitor';\nimport { PydanticPluginRawConfig } from './config';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const plugin: PluginFunction = async (\n schema: GraphQLSchema,\n documents: Types.DocumentFile[],\n config: PydanticPluginRawConfig,\n info,\n): Promise => {\n const visitor = new PydanticVisitor(config, schema);\n const printedSchema = printSchema(schema);\n const astNode = parse(printedSchema);\n\n const visitorResult = visit(astNode, { leave: visitor as any });\n const imports = visitor.getImports();\n\n return `${imports}\\n\\n\\n${visitorResult}\\n`;\n};\n"],"names":["PYTHON_SCALARS","ID","String","Boolean","Int","Float","PYTHON_RESERVED","PYDANTIC_MODEL_RESERVED","RESERVED","concat","PydanticVisitor","BaseVisitor","constructor","rawConfig","schema","scalars","buildScalars","DepGraph","circular","getImports","typing","pydantic","addAnyImport","push","addOptionalImport","addListImport","addUnionImport","addFieldImport","enumInput","addEnumImport","typingImport","length","join","pydanticImport","filter","i","canAddGraphNode","id","Object","values","includes","upsertGraphNode","graph","hasNode","addNode","addGraphNodeDeps","ids","forEach","addDependency","clearOptional","str","startsWith","replace","Name","node","value","NamedType","name","keys","source","ListType","type","NonNullType","visitFieldOrInputDefinition","argName","directives","indent","FieldDefinition","InputValueDefinition","EnumTypeDefinition","val","map","v","UnionTypeDefinition","types","unionTypes","t","InterfaceTypeDefinition","fields","rawFields","f","args","ObjectTypeDefinition","interfaces","rawInterfaces","n","impl","InputObjectTypeDefinition","Document","definitions","nodesInOrder","overallOrder","find","d","plugin","documents","config","info","visitor","printedSchema","printSchema","astNode","parse","visitorResult","visit","leave","imports"],"mappings":";;;;AAAA;AA4BO,MAAMA,cAAc,GAAG;EAC5BC,EAAE,EAAE,KAAK;EACTC,MAAM,EAAE,KAAK;EACbC,OAAO,EAAE,MAAM;EACfC,GAAG,EAAE,KAAK;EACVC,KAAK,EAAE;CACR;AAED,MAAMC,eAAe,GAAG,CAAC,MAAM,CAAC;AAChC,MAAMC,uBAAuB,GAAG,CAAC,MAAM,CAAC;AACxC,MAAMC,QAAQ,gBAAGF,eAAe,CAACG,MAAM,CAACF,uBAAuB,CAAC;MAOnDG,eAAgB,SAAQC,WAGpC;EAYCC,YACEC,SAAkC,EAC1BC,MAAqB;IAE7B,KAAK,CAACD,SAAS,EAAE;;;;MAIfE,OAAO,EAAEC,YAAY,CAACF,MAAM,EAAE,EAAE,EAAEd,cAAc;KACjD,CAAC;IAPM,WAAM,GAANc,MAAM;IAbR,sBAAiB,GAAG,KAAK;IACzB,iBAAY,GAAG,KAAK;IACpB,kBAAa,GAAG,KAAK;IACrB,mBAAc,GAAG,KAAK;IACtB,kBAAa,GAAG,KAAK;IACrB,mBAAc,GAAG,KAAK;IAEtB,UAAK,GAAG,IAAIG,QAAQ,CAAC;MAC3BC,QAAQ,EAAE;KACX,CAAC;;EAcKC,UAAU;IACf,MAAMC,MAAM,GAAG,EAAE;IACjB,MAAMC,QAAQ,GAAG,CAAC,WAAW,CAAC;IAE9B,IAAI,IAAI,CAACC,YAAY,EAAE;MACrBF,MAAM,CAACG,IAAI,MAAM,CAAC;;IAGpB,IAAI,IAAI,CAACC,iBAAiB,EAAE;MAC1BJ,MAAM,CAACG,IAAI,WAAW,CAAC;;IAGzB,IAAI,IAAI,CAACE,aAAa,EAAE;MACtBL,MAAM,CAACG,IAAI,OAA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K,CAACiD,YAAY,EAAE;IAE9C,OAAOD,YAAY,CAChBnB,GAAG,CAAEc,CAAM;MAAA;MAAA,OAAK,sBAAAI,WAAW,CAACG,IAAI,CAAEC,CAAM,IAAKA,CAAC,CAACxD,EAAE,KAAKgD,CAAC,CAAC,qBAAxC,kBAA0C1B,MAAM,KAAI,EAAE;MAAC,CACvE3B,IAAI,CAAC,QAAQ,CAAC;;;;ACvVrB;AACA,MAAa8D,MAAM,GAA4C,OAC7DhF,MAAqB,EACrBiF,SAA+B,EAC/BC,MAA+B,EAC/BC,IAAI;EAEJ,MAAMC,OAAO,GAAG,IAAIxF,eAAe,CAACsF,MAAM,EAAElF,MAAM,CAAC;EACnD,MAAMqF,aAAa,GAAGC,WAAW,CAACtF,MAAM,CAAC;EACzC,MAAMuF,OAAO,GAAGC,KAAK,CAACH,aAAa,CAAC;EAEpC,MAAMI,aAAa,GAAGC,KAAK,CAACH,OAAO,EAAE;IAAEI,KAAK,EAAEP;GAAgB,CAAC;EAC/D,MAAMQ,OAAO,GAAGR,OAAO,CAAC/E,UAAU,EAAE;EAEpC,UAAUuF,gBAAgBH,iBAAiB;AAC7C,CAAC;;;;"} \ No newline at end of file +{"version":3,"file":"graphql-codegen-pydantic.esm.js","sources":["../src/visitor.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable lines-between-class-members */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable react/no-this-in-sfc */\nimport {\n BaseVisitor,\n ParsedConfig,\n buildScalars,\n indent,\n} from '@graphql-codegen/visitor-plugin-common';\nimport {\n NamedTypeNode,\n ListTypeNode,\n NonNullTypeNode,\n GraphQLSchema,\n FieldDefinitionNode,\n ObjectTypeDefinitionNode,\n NameNode,\n UnionTypeDefinitionNode,\n DocumentNode,\n InterfaceTypeDefinitionNode,\n EnumTypeDefinitionNode,\n InputObjectTypeDefinitionNode,\n InputValueDefinitionNode,\n} from 'graphql';\nimport { DepGraph } from 'dependency-graph';\n\nimport { PydanticPluginRawConfig } from './config';\n\nexport const PYTHON_SCALARS = {\n ID: 'str',\n String: 'str',\n Boolean: 'bool',\n Int: 'int',\n Float: 'float',\n};\n\nconst PYTHON_RESERVED = ['from'];\nconst PYDANTIC_MODEL_RESERVED = ['copy'];\nconst RESERVED = PYTHON_RESERVED.concat(PYDANTIC_MODEL_RESERVED);\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PydanticPluginParsedConfig extends ParsedConfig {\n /* intentionally empty for now */\n}\n\nexport class PydanticVisitor extends BaseVisitor<\n PydanticPluginRawConfig,\n PydanticPluginParsedConfig\n> {\n private addOptionalImport = false;\n private addAnyImport = false;\n private addListImport = false;\n private addUnionImport = false;\n private addEnumImport = false;\n private addFieldImport = false;\n\n private graph = new DepGraph({\n circular: false,\n });\n\n constructor(\n rawConfig: PydanticPluginRawConfig,\n private schema: GraphQLSchema,\n ) {\n super(rawConfig, {\n // enumValues: rawConfig.enumValues || {},\n // listType: rawConfig.listType || 'List',\n // package: rawConfig.package || defaultPackageName,\n scalars: buildScalars(schema, {}, PYTHON_SCALARS),\n });\n }\n\n public getImports(): string {\n const typing = [];\n const pydantic = ['BaseModel'];\n\n if (this.addAnyImport) {\n typing.push(`Any`);\n }\n\n if (this.addOptionalImport) {\n typing.push(`Optional`);\n }\n\n if (this.addListImport) {\n typing.push(`List`);\n }\n\n if (this.addUnionImport) {\n typing.push(`Union`);\n }\n\n if (this.addFieldImport) {\n pydantic.push(`Field`);\n }\n\n const enumInput = this.addEnumImport ? 'from enum import StrEnum' : '';\n\n const typingImport = typing.length\n ? `from typing import ${typing.join(', ')}`\n : '';\n\n const pydanticImport = pydantic.length\n ? `from pydantic import ${pydantic.join(', ')}`\n : '';\n\n return [enumInput, typingImport, pydanticImport].filter(i => i).join('\\n');\n }\n\n protected canAddGraphNode(id: string): boolean {\n if (Object.values(this.scalars).includes(id) || id === 'Any') {\n return false;\n }\n\n return true;\n }\n\n protected upsertGraphNode(id: string) {\n if (this.canAddGraphNode(id) && !this.graph.hasNode(id)) {\n this.graph.addNode(id);\n }\n }\n\n protected addGraphNodeDeps(id: string, ids: string[]) {\n if (!this.canAddGraphNode(id)) {\n return;\n }\n\n this.upsertGraphNode(id);\n\n ids.forEach((i: string) => {\n if (!this.canAddGraphNode(i)) {\n return;\n }\n\n this.upsertGraphNode(i);\n\n this.graph.addDependency(id, i);\n });\n }\n\n protected clearOptional(str: string): string {\n if (str.startsWith('Optional[')) {\n return str.replace(/Optional\\[(.*?)\\]$/, '$1');\n }\n\n return str;\n }\n\n Name(node: NameNode) {\n return node.value;\n }\n\n NamedType(node: NamedTypeNode) {\n const { name } = node as any;\n\n // Scalars\n if (Object.keys(this.scalars).includes(name)) {\n const id = this.scalars[name];\n\n // Special case for any\n if (id === 'any') {\n this.addAnyImport = true;\n return {\n id: 'Any',\n source: 'Any',\n };\n }\n\n this.addOptionalImport = true;\n return {\n id,\n source: `Optional[${id}]`,\n };\n }\n\n // Defined\n this.addOptionalImport = true;\n return {\n id: name,\n source: `Optional['${name}']`,\n };\n }\n\n ListType(node: ListTypeNode) {\n this.addListImport = true;\n this.addOptionalImport = true;\n\n const { type } = node as any;\n\n return {\n id: type.id,\n source: `Optional[List[${type.source}]]`,\n };\n }\n\n NonNullType(node: NonNullTypeNode) {\n const { type } = node as any;\n\n return {\n id: type.id,\n source: this.clearOptional(type.source),\n };\n }\n\n protected visitFieldOrInputDefinition(node: any) {\n const argName = node.name as any;\n\n const { type, directives } = node as any;\n\n // Handle deprecated\n // const ds = directives.map((d: any) => d.name);\n // if (ds.includes('deprecated')) {\n // return null;\n // }\n\n // Need to alias some field names\n // Otherwise pydantic throws\n if (RESERVED.includes(argName)) {\n this.addFieldImport = true;\n return {\n id: type.id,\n source: indent(\n `${argName}_: ${type.source} = Field(None, alias='${argName}')`,\n 2,\n ),\n };\n }\n\n return {\n id: type.id,\n source: indent(`${argName}: ${type.source}`, 2),\n };\n }\n\n FieldDefinition(node: FieldDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n InputValueDefinition(node: InputValueDefinitionNode) {\n return this.visitFieldOrInputDefinition(node);\n }\n\n EnumTypeDefinition(node: EnumTypeDefinitionNode) {\n this.addEnumImport = true;\n\n const { name, values } = node as any;\n\n const val = values\n .map((v: any) => indent(`${v.name} = '${v.name}'`, 2))\n .join('\\n');\n const source = `class ${name}(StrEnum):\\n${val}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n UnionTypeDefinition(node: UnionTypeDefinitionNode) {\n this.addUnionImport = true;\n\n const { name, types } = node as any;\n\n const unionTypes = (types ?? []).map((t: any) =>\n this.clearOptional(t.source),\n );\n\n this.addGraphNodeDeps(\n name,\n types.map((t: any) => t.id),\n );\n\n return {\n id: name,\n source: `${name} = Union[${unionTypes.join(', ')}]`,\n };\n }\n\n InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.addGraphNodeDeps(\n name,\n fields.map((f: any) => f.id),\n );\n\n return {\n id: name,\n source,\n };\n }\n\n ObjectTypeDefinition(node: ObjectTypeDefinitionNode) {\n const { name, fields: rawFields, interfaces: rawInterfaces } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const interfaces = rawInterfaces.map((n: any) =>\n this.clearOptional(n.source).replace(/'/g, ''),\n );\n\n const impl = interfaces.length ? interfaces.join(', ') : 'BaseModel';\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(${impl}):\\n${args}`;\n\n if (interfaces.length) {\n this.addGraphNodeDeps(name, interfaces);\n } else {\n this.upsertGraphNode(name);\n }\n\n return {\n id: name,\n source,\n };\n }\n\n InputObjectTypeDefinition(node: InputObjectTypeDefinitionNode) {\n const { name, fields: rawFields } = node as any;\n\n const fields = rawFields.filter((f: any) => f);\n\n const args = fields.map((f: any) => f.source).join('\\n');\n const source = `class ${name}(BaseModel):\\n${args}`;\n\n this.upsertGraphNode(name);\n\n return {\n id: name,\n source,\n };\n }\n\n Document(node: DocumentNode) {\n const { definitions } = node as any;\n\n const nodesInOrder = this.graph.overallOrder();\n\n return nodesInOrder\n .map((n: any) => definitions.find((d: any) => d.id === n)?.source || '')\n .join('\\n\\n\\n');\n }\n}\n","import { parse, GraphQLSchema, printSchema, visit } from 'graphql';\nimport { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';\n\nimport { PydanticVisitor } from './visitor';\nimport { PydanticPluginRawConfig } from './config';\n\n// eslint-disable-next-line import/prefer-default-export\nexport const plugin: PluginFunction = async (\n schema: GraphQLSchema,\n documents: Types.DocumentFile[],\n config: PydanticPluginRawConfig,\n info,\n): Promise => {\n const visitor = new PydanticVisitor(config, schema);\n const printedSchema = printSchema(schema);\n const astNode = parse(printedSchema);\n\n const visitorResult = visit(astNode, { leave: visitor as any });\n const imports = visitor.getImports();\n\n return `${imports}\\n\\n\\n${visitorResult}\\n`;\n};\n"],"names":["PYTHON_SCALARS","ID","String","Boolean","Int","Float","PYTHON_RESERVED","PYDANTIC_MODEL_RESERVED","RESERVED","concat","PydanticVisitor","BaseVisitor","constructor","rawConfig","schema","scalars","buildScalars","DepGraph","circular","getImports","typing","pydantic","addAnyImport","push","addOptionalImport","addListImport","addUnionImport","addFieldImport","enumInput","addEnumImport","typingImport","length","join","pydanticImport","filter","i","canAddGraphNode","id","Object","values","includes","upsertGraphNode","graph","hasNode","addNode","addGraphNodeDeps","ids","forEach","addDependency","clearOptional","str","startsWith","replace","Name","node","value","NamedType","name","keys","source","ListType","type","NonNullType","visitFieldOrInputDefinition","argName","directives","indent","FieldDefinition","InputValueDefinition","EnumTypeDefinition","val","map","v","UnionTypeDefinition","types","unionTypes","t","InterfaceTypeDefinition","fields","rawFields","f","args","ObjectTypeDefinition","interfaces","rawInterfaces","n","impl","InputObjectTypeDefinition","Document","definitions","nodesInOrder","overallOrder","find","d","plugin","documents","config","info","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IAAKA,CAAC,CAACxD,EAAE,KAAKgD,CAAC,CAAC,qBAAxC,kBAA0C1B,MAAM,KAAI,EAAE;MAAC,CACvE3B,IAAI,CAAC,QAAQ,CAAC;;;;ACvVrB;AACA,MAAa8D,MAAM,GAA4C,OAC7DhF,MAAqB,EACrBiF,SAA+B,EAC/BC,MAA+B,EAC/BC,IAAI;EAEJ,MAAMC,OAAO,GAAG,IAAIxF,eAAe,CAACsF,MAAM,EAAElF,MAAM,CAAC;EACnD,MAAMqF,aAAa,GAAGC,WAAW,CAACtF,MAAM,CAAC;EACzC,MAAMuF,OAAO,GAAGC,KAAK,CAACH,aAAa,CAAC;EAEpC,MAAMI,aAAa,GAAGC,KAAK,CAACH,OAAO,EAAE;IAAEI,KAAK,EAAEP;GAAgB,CAAC;EAC/D,MAAMQ,OAAO,GAAGR,OAAO,CAAC/E,UAAU,EAAE;EAEpC,UAAUuF,gBAAgBH,iBAAiB;AAC7C,CAAC;;;;"} \ No newline at end of file diff --git a/src/visitor.ts b/src/visitor.ts index 4d1da5c..8967663 100644 --- a/src/visitor.ts +++ b/src/visitor.ts @@ -94,7 +94,7 @@ export class PydanticVisitor extends BaseVisitor< pydantic.push(`Field`); } - const enumInput = this.addEnumImport ? 'from enum import Enum' : ''; + const enumInput = this.addEnumImport ? 'from enum import StrEnum' : ''; const typingImport = typing.length ? `from typing import ${typing.join(', ')}` @@ -249,7 +249,7 @@ export class PydanticVisitor extends BaseVisitor< const val = values .map((v: any) => indent(`${v.name} = '${v.name}'`, 2)) .join('\n'); - const source = `class ${name}(str, Enum):\n${val}`; + const source = `class ${name}(StrEnum):\n${val}`; this.upsertGraphNode(name); diff --git a/test/pydantic.test.ts b/test/pydantic.test.ts index df0db20..2dddb0d 100644 --- a/test/pydantic.test.ts +++ b/test/pydantic.test.ts @@ -83,11 +83,11 @@ describe('Pydantic', () => { const result = await plugin(schema, [], {}); expect(result).toBeSimilarStringTo(` - from enum import Enum + from enum import StrEnum from pydantic import BaseModel - class Type(str, Enum): + class Type(StrEnum): FIRST = 'FIRST' SECOND = 'SECOND' THIRD = 'THIRD' @@ -212,4 +212,4 @@ describe('Pydantic', () => { copy_: Optional[int] = Field(None, alias='copy') `); }); -}); +}); \ No newline at end of file