{"version":3,"file":"core.cjs","sources":["../../src/core.ts"],"sourcesContent":["import type { SwaggerTransform, SwaggerTransformObject } from '@fastify/swagger'\nimport type {\n  FastifyPluginAsync,\n  FastifyPluginCallback,\n  FastifyPluginOptions,\n  FastifySchema,\n  FastifySchemaCompiler,\n  FastifySerializerCompiler,\n  FastifyTypeProvider,\n  RawServerBase,\n  RawServerDefault,\n} from 'fastify'\nimport type { $ZodRegistry, input, output } from 'zod/v4/core'\nimport { $ZodType, globalRegistry, safeParse } from 'zod/v4/core'\nimport { createValidationError, InvalidSchemaError, ResponseSerializationError } from './errors'\nimport { getOASVersion, jsonSchemaToOAS } from './json-to-oas'\nimport { type ZodToJsonConfig, zodRegistryToJson, zodSchemaToJson } from './zod-to-json'\n\ntype FreeformRecord = Record<string, any>\n\nconst defaultSkipList = [\n  '/documentation/',\n  '/documentation/initOAuth',\n  '/documentation/json',\n  '/documentation/uiConfig',\n  '/documentation/yaml',\n  '/documentation/*',\n  '/documentation/static/*',\n]\n\nexport interface ZodTypeProvider extends FastifyTypeProvider {\n  validator: this['schema'] extends $ZodType ? output<this['schema']> : unknown\n  serializer: this['schema'] extends $ZodType ? input<this['schema']> : unknown\n}\n\ninterface Schema extends FastifySchema {\n  hide?: boolean\n}\n\ntype CreateJsonSchemaTransformOptions = {\n  skipList?: readonly string[]\n  schemaRegistry?: $ZodRegistry<{ id?: string | undefined }>\n  zodToJsonConfig?: ZodToJsonConfig\n}\n\nexport const createJsonSchemaTransform = ({\n  skipList = defaultSkipList,\n  schemaRegistry = globalRegistry,\n  zodToJsonConfig = {},\n}: CreateJsonSchemaTransformOptions): SwaggerTransform<Schema> => {\n  return (input) => {\n    if ('swaggerObject' in input) {\n      throw new Error('OpenAPI 2.0 is not supported')\n    }\n\n    const { schema, url } = input\n\n    if (!schema) {\n      return {\n        schema,\n        url,\n      }\n    }\n\n    const { response, headers, querystring, body, params, hide, ...rest } = schema\n\n    const transformed: FreeformRecord = {}\n\n    if (skipList.includes(url) || hide) {\n      transformed.hide = true\n      return { schema: transformed, url }\n    }\n\n    const zodSchemas: FreeformRecord = { headers, querystring, body, params }\n\n    const oasVersion = getOASVersion(input)\n\n    for (const prop in zodSchemas) {\n      const zodSchema = zodSchemas[prop]\n      if (zodSchema) {\n        const jsonSchema = zodSchemaToJson(\n          zodSchema,\n          schemaRegistry,\n          'input',\n          oasVersion,\n          zodToJsonConfig,\n        )\n        const oasSchema = jsonSchemaToOAS(jsonSchema, oasVersion)\n\n        transformed[prop] = oasSchema\n      }\n    }\n\n    if (response) {\n      transformed.response = {}\n\n      for (const prop in response as any) {\n        const zodSchema = resolveSchema((response as any)[prop])\n        const jsonSchema = zodSchemaToJson(\n          zodSchema,\n          schemaRegistry,\n          'output',\n          oasVersion,\n          zodToJsonConfig,\n        )\n\n        // Check is the JSON schema is null then return as it is since fastify-swagger will handle it\n        if (jsonSchema.type === 'null') {\n          transformed.response[prop] = jsonSchema\n          continue\n        }\n\n        const oasSchema = jsonSchemaToOAS(jsonSchema, oasVersion)\n\n        transformed.response[prop] = oasSchema\n      }\n    }\n\n    for (const prop in rest) {\n      const meta = rest[prop as keyof typeof rest]\n      if (meta) {\n        transformed[prop] = meta\n      }\n    }\n\n    return { schema: transformed, url }\n  }\n}\n\nexport const jsonSchemaTransform: SwaggerTransform<Schema> = createJsonSchemaTransform({})\n\ntype CreateJsonSchemaTransformObjectOptions = {\n  schemaRegistry?: $ZodRegistry<{ id?: string | undefined }>\n  zodToJsonConfig?: ZodToJsonConfig\n}\n\nexport const createJsonSchemaTransformObject =\n  ({\n    schemaRegistry = globalRegistry,\n    zodToJsonConfig = {},\n  }: CreateJsonSchemaTransformObjectOptions): SwaggerTransformObject =>\n  (input) => {\n    if ('swaggerObject' in input) {\n      throw new Error('OpenAPI 2.0 is not supported')\n    }\n\n    const oasVersion = getOASVersion(input)\n\n    const inputSchemas = zodRegistryToJson(schemaRegistry, 'input', zodToJsonConfig)\n    const outputSchemas = zodRegistryToJson(schemaRegistry, 'output', zodToJsonConfig)\n\n    for (const key in outputSchemas) {\n      if (inputSchemas[key]) {\n        throw new Error(\n          `Collision detected for schema \"${key}\". The is already an input schema with the same name.`,\n        )\n      }\n    }\n\n    const jsonSchemas = {\n      ...inputSchemas,\n      ...outputSchemas,\n    }\n\n    const oasSchemas = Object.fromEntries(\n      Object.entries(jsonSchemas).map(([key, value]) => [key, jsonSchemaToOAS(value, oasVersion)]),\n    )\n\n    return {\n      ...input.openapiObject,\n      components: {\n        ...input.openapiObject.components,\n        schemas: {\n          ...input.openapiObject.components?.schemas,\n          ...oasSchemas,\n        },\n      },\n    } as ReturnType<SwaggerTransformObject>\n  }\n\nexport const jsonSchemaTransformObject: SwaggerTransformObject = createJsonSchemaTransformObject({})\n\nexport const validatorCompiler: FastifySchemaCompiler<$ZodType> =\n  ({ schema }) =>\n  (data) => {\n    const result = safeParse(schema, data)\n    if (result.error) {\n      return { error: createValidationError(result.error) as unknown as Error }\n    }\n\n    return { value: result.data }\n  }\n\nfunction resolveSchema(maybeSchema: $ZodType | { properties: $ZodType }): $ZodType {\n  if (maybeSchema instanceof $ZodType) {\n    return maybeSchema\n  }\n  if ('properties' in maybeSchema && maybeSchema.properties instanceof $ZodType) {\n    return maybeSchema.properties\n  }\n  throw new InvalidSchemaError(JSON.stringify(maybeSchema))\n}\n\ntype ReplacerFunction = (this: any, key: string, value: any) => any\n\nexport type ZodSerializerCompilerOptions = {\n  replacer?: ReplacerFunction\n}\n\nexport const createSerializerCompiler =\n  (\n    options?: ZodSerializerCompilerOptions,\n  ): FastifySerializerCompiler<$ZodType | { properties: $ZodType }> =>\n  ({ schema: maybeSchema, method, url }) =>\n  (data) => {\n    const schema = resolveSchema(maybeSchema)\n\n    const result = safeParse(schema, data)\n    if (result.error) {\n      throw new ResponseSerializationError(method, url, {\n        cause: result.error,\n      })\n    }\n\n    return JSON.stringify(result.data, options?.replacer)\n  }\n\nexport const serializerCompiler: ReturnType<typeof createSerializerCompiler> =\n  createSerializerCompiler({})\n\n/**\n * FastifyPluginCallbackZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginCallbackZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginCallbackZod = (fastify, options, done) => {\n *   done()\n * }\n * ```\n */\nexport type FastifyPluginCallbackZod<\n  Options extends FastifyPluginOptions = Record<never, never>,\n  Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginCallback<Options, Server, ZodTypeProvider>\n\n/**\n * FastifyPluginAsyncZod with Zod automatic type inference\n *\n * @example\n * ```typescript\n * import { FastifyPluginAsyncZod } from \"fastify-type-provider-zod\"\n *\n * const plugin: FastifyPluginAsyncZod = async (fastify, options) => {\n * }\n * ```\n */\nexport type FastifyPluginAsyncZod<\n  Options extends FastifyPluginOptions = Record<never, never>,\n  Server extends RawServerBase = RawServerDefault,\n> = FastifyPluginAsync<Options, Server, ZodTypeProvider>\n"],"names":["globalRegistry","getOASVersion","zodSchemaToJson","jsonSchemaToOAS","zodRegistryToJson","safeParse","createValidationError","$ZodType","InvalidSchemaError","ResponseSerializationError"],"mappings":";;;;;;AAoBA,MAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAiBO,MAAM,4BAA4B,CAAC;AAAA,EACxC,WAAW;AAAA,EACX,iBAAiBA,KAAAA;AAAAA,EACjB,kBAAkB,CAAA;AACpB,MAAkE;AAChE,SAAO,CAAC,UAAU;AAChB,QAAI,mBAAmB,OAAO;AAC5B,YAAM,IAAI,MAAM,8BAA8B;AAAA,IAChD;AAEA,UAAM,EAAE,QAAQ,IAAA,IAAQ;AAExB,QAAI,CAAC,QAAQ;AACX,aAAO;AAAA,QACL;AAAA,QACA;AAAA,MAAA;AAAA,IAEJ;AAEA,UAAM,EAAE,UAAU,SAAS,aAAa,MAAM,QAAQ,MAAM,GAAG,KAAA,IAAS;AAExE,UAAM,cAA8B,CAAA;AAEpC,QAAI,SAAS,SAAS,G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