From 6990a3ebb5201152b1de66e795ee22a1c29d1c67 Mon Sep 17 00:00:00 2001 From: simeng-li Date: Thu, 28 Mar 2024 10:23:08 +0800 Subject: [PATCH] fix(console): fix the zod-to-ts type infer bug (#5566) fix the zod-to-ts type infer bug --- .../generate-jwt-customizer-type-definition.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/console/scripts/generate-jwt-customizer-type-definition.ts b/packages/console/scripts/generate-jwt-customizer-type-definition.ts index 744b74d46..9b25077a2 100644 --- a/packages/console/scripts/generate-jwt-customizer-type-definition.ts +++ b/packages/console/scripts/generate-jwt-customizer-type-definition.ts @@ -1,13 +1,13 @@ import fs from 'node:fs'; import { - jwtCustomizerUserContextGuard, accessTokenPayloadGuard, clientCredentialsPayloadGuard, + jwtCustomizerUserContextGuard, } from '@logto/schemas'; import prettier from 'prettier'; import { type ZodTypeAny } from 'zod'; -import { zodToTs, printNode } from 'zod-to-ts'; +import { printNode, zodToTs } from 'zod-to-ts'; const filePath = 'src/consts/jwt-customizer-type-definition.ts'; @@ -19,7 +19,18 @@ const typeIdentifiers = `export enum JwtCustomizerTypeDefinitionKey { };`; const inferTsDefinitionFromZod = (zodSchema: ZodTypeAny, identifier: string): string => { - const { node } = zodToTs(zodSchema, identifier); + /** + * We have z.lazy() used for defining Json objects in the zod schemas. + * @see https://zod.dev/?id=json-type + * zod-to-ts does not support z.lazy() yet. It will use the root type of the lazy schema. Which will be the identifier we pass to the function. + * @see https://github.com/sachinraja/zod-to-ts?tab=readme-ov-file#zlazy + * + * The second argument is the root type identifier for the schema. + * Here we use 'Record' as the root type identifier. So all the Json objects will be inferred as Record. + * This is a limitation of zod-to-ts. We can't infer the exact type of the Json objects. + * This solution is hacky but it works for now. The impact is it will always define the type identifer as Record. + */ + const { node } = zodToTs(zodSchema, 'Record', { nativeEnums: 'union' }); const typeDefinition = printNode(node); return `type ${identifier} = ${typeDefinition};`;