fastify / env-schema

Validate your env variable using Ajv and dotenv
MIT License
212 stars 25 forks source link

Type.RegExp fails at Ajv compilation #173

Closed Sufiane closed 7 months ago

Sufiane commented 7 months ago

Prerequisites

Fastify version

4.26.0

Plugin version

5.2.1

Node.js version

20.10.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

Sonoma 14.3

Description

Type.RegExp() throw an error no matter what pattern I use.

The error:

Error: schema is invalid: data/properties/JWT_MAX_AGE/type must be equal to one of the allowed values, data/properties/JWT_MAX_AGE/type must be array, data/properties/JWT_MAX_AGE/type must match a schema in anyOf
    at Ajv.validateSchema

I used Type.String({ pattern: '....'}) as a work around.

Steps to Reproduce

import { Static, Type } from '@sinclair/typebox';

import { envSchema } from 'env-schema';

const schema = Type.Object({
    JWT_SECRET: Type.String({ minLength: 1 }),
    JWT_MAX_AGE: Type.RegExp( '^[1-9]\\d*d$' ),
});

export type Env = Static<typeof schema>;

export const config = envSchema<Env>({ schema });

Expected Behavior

To be able to use Type.RegExp() instead of using Type.String({ pattern}) work around.

climba03003 commented 7 months ago

I would like to close this issue (no privilege for me) because we do not support the type that is not JSON Schema.

Type.RegExp return type: 'RegExp' instead of type: 'string'. https://github.com/sinclairzx81/typebox/blob/master/src/type/regexp/regexp.ts#L55

cc @sinclairzx81 It there any reason to use RegExp instead of string?

sinclairzx81 commented 7 months ago

@climba03003 Hi,

This was updated in 0.32.0 with the RegExp type moved to the [JavaScript] type set to draw greater distinction between the regular expressions supported by Json Schema, and expressions supported by the full ECMA 262 syntax. The subset syntax supported by Json Schema (and Ajv) can be found here

The general recommendation is to use Type.String({ pattern: '...' }) to ensure compliance with the specification moving forward. However the RegExp type does enable full support of the full ECMA 262 syntax, including UTF-16 (Unicode) and flags at a cost of being "non-standard". As such, it only works with the TypeBox Value and TypeCompiler modules.

// The following expression cannot be encoded in Json Schema
const E = Type.RegExp(/<a?:.+?:\d{18}>|\p{Extended_Pictographic}/gu)

Value.Check(E, '♥️♦️♠️♣️') // true

Type.RegExp does enable international character set support options for users. But do still recommend Type.String({ pattern: '...' }) for most cases. For Ajv users, the above can be largely expressed via custom string format.

Hope this helps! S

Sufiane commented 7 months ago

@climba03003 you're right we can close this issue. At first I thought it was related to how fastify-env would interprete the ajv schema.

My bad on this one.

And thanks @sinclairzx81 for the clarification :)