Skip to content

Support discriminatedUnions #45

@HaNdTriX

Description

@HaNdTriX

First of all: Thank you for this awesome package!


Currently vite-plugin-validate-env only takes a JSON Object as schema instead of an schema Object Type. This makes it hard to define discriminatedUnions since schemas can not be concatenated.

// env.ts
import { defineConfig } from '@julr/vite-plugin-validate-env'
import { z } from 'zod'

export default defineConfig({
  validator: "standard",
-  schema: {
-    VITE_MY_VAR: z.enum(['foo', 'bar']),
-  },
+  schema: z.object({
+    VITE_MY_VAR: z.enum(['foo', 'bar']),
+  }),
})

This tiny change could open the door for more complex dependent env validations:

Example

// env.ts
import { defineConfig } from '@julr/vite-plugin-validate-env'
import { z } from 'zod'

export default defineConfig({
  validator: 'standard',
  schema: z
    .object({
      VITE_MY_VAR: z.enum(['foo', 'bar'])
    })
    .and(
      z.discriminatedUnion('VITE_MY_VAR', [
        z.object({
          VITE_MY_VAR: z.literal('foo'),
          VITE_FOO_VAR: z.literal('foooooo')
        }),
        z.object({
          VITE_MY_VAR: z.literal('bar'),
          VITE_BAR_VAR: z.literal('baaaar')
        })
      ])
    )
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions