Skip to content

Commit

Permalink
Fixed issue with optional schemas (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
meinlebenswerk committed Jun 22, 2023
1 parent c262e5e commit 7bb316c
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 9 deletions.
3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { cwd } from 'process'
import path from 'node:path'
import { type Plugin, loadEnv, normalizePath } from 'vite'
import { type ConfigEnv, type Plugin, type UserConfig, loadEnv, normalizePath } from 'vite'
import { createConfigLoader as createLoader } from 'unconfig'
import { builtinValidation } from './validators/builtin'
import { zodValidation } from './validators/zod'
import type { FullPluginOptions, PluginOptions, Schema } from './contracts'
import type { ConfigEnv, UserConfig } from 'vite'

/**
* Load schema defined in `env.ts` file using unconfig
Expand Down
7 changes: 7 additions & 0 deletions src/validators/builtin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ export function builtinValidation(env: Record<string, string>, schema: PoppinsSc
for (const [key, validator] of Object.entries(schema!)) {
try {
const res = validator(key, env[key])

// Handle undefined aka optional results
if (typeof res === 'undefined') {
delete process.env[key]
return
}

process.env[key] = res
} catch (err) {
errors.push({ key, err })
Expand Down
6 changes: 6 additions & 0 deletions src/validators/zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ export async function zodValidation(env: Record<string, string>, schema: ZodSche
continue
}

// Handle undefined aka optional results
if (typeof result.data === 'undefined') {
delete process.env[key]
return
}

process.env[key] = result.data
}

Expand Down
24 changes: 24 additions & 0 deletions tests/common.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,28 @@ test.group('vite-plugin-validate-env', (group) => {
assert.include(error.message, 'Missing environment variable "VITE_TEST2"')
}
})

test('Optional Variables', async ({ assert }) => {
// assert.plan(2);

const plugin = ValidateEnv({ VITE_OPTIONAL: Schema.number.optional() })

// Test with the variable set, but invalid
await fs.add('.env.development', 'VITE_OPTIONAL=not a number')
try {
// @ts-ignore
await plugin.config(viteConfig, viteEnvConfig)
} catch (error: any) {
assert.include(
error.message,
'Value for environment variable "VITE_OPTIONAL" must be numeric, instead received'
)
}

// Test without variable
await fs.add('.env.development', '')
// @ts-ignore
await plugin.config(viteConfig, viteEnvConfig)
assert.equal(process.env.VITE_OPTIONAL, undefined)
})
})
47 changes: 40 additions & 7 deletions tests/zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ const fs = new Filesystem(join(__dirname, 'fixtures'))
const viteConfig = { root: fs.basePath }
const viteEnvConfig = { mode: 'development', command: 'serve' } as const

test.group('Zod validation adaptater', () => {
const ENV_FILENAME = '.env.development'

test.group('Zod validation adaptater', (group) => {
group.each.teardown(async () => {
await fs.cleanup()
})

test('Basic', async ({ assert }) => {
assert.plan(1)

Expand All @@ -20,7 +26,7 @@ test.group('Zod validation adaptater', () => {
schema: { VITE_TEST: z.string().url().max(10) },
})

await fs.add(`.env.development`, `VITE_TEST=htest`)
await fs.add(ENV_FILENAME, 'VITE_TEST=htest')

try {
// @ts-ignore
Expand All @@ -41,9 +47,9 @@ test.group('Zod validation adaptater', () => {
},
})

await fs.add(`.env.development`, `VITE_TEST=hello`)
await fs.add(ENV_FILENAME, 'VITE_TEST=hello')

// @ts-expect-error - `config` is the handler
// @ts-expect-error - 'config' is the handler
await plugin.config!(viteConfig, viteEnvConfig)
assert.equal(process.env.VITE_TEST, 'HELLO')
})
Expand All @@ -58,7 +64,7 @@ test.group('Zod validation adaptater', () => {
},
})

await fs.add(`.env.development`, `VITE_LONG_STRING=superlongstring`)
await fs.add(ENV_FILENAME, 'VITE_LONG_STRING=superlongstring')

try {
// @ts-ignore
Expand All @@ -80,7 +86,7 @@ test.group('Zod validation adaptater', () => {
},
})

await fs.add(`.env.development`, `VITE_REFINED=superlongstring`)
await fs.add(ENV_FILENAME, 'VITE_REFINED=superlongstring')

try {
// @ts-ignore
Expand All @@ -101,7 +107,7 @@ test.group('Zod validation adaptater', () => {
},
})

await fs.add(`.env.development`, ``)
await fs.add(ENV_FILENAME, '')

try {
// @ts-ignore
Expand All @@ -111,4 +117,31 @@ test.group('Zod validation adaptater', () => {
assert.include(error.message, 'Invalid value for "VITE_B" : Required')
}
})

test('Optional Variables', async ({ assert }) => {
assert.plan(2)

const plugin = ValidateEnv({
validator: 'zod',
schema: { VITE_OPTIONAL_ZOD: z.string().max(2).optional() },
})

// Test with the variable set, but invalid
await fs.add(ENV_FILENAME, 'VITE_OPTIONAL_ZOD=hello')
try {
// @ts-ignore
await plugin.config(viteConfig, viteEnvConfig)
} catch (error: any) {
assert.include(
error.message,
'Invalid value for "VITE_OPTIONAL_ZOD" : String must contain at most 2 character(s)'
)
}

// Test without variable
await fs.add(ENV_FILENAME, '')
// @ts-ignore
await plugin.config(viteConfig, viteEnvConfig)
assert.equal(process.env.VITE_OPTIONAL_ZOD, undefined)
})
})

0 comments on commit 7bb316c

Please sign in to comment.