lostfictions / znv

Type-safe environment parsing and validation for Node.js with Zod schemas
https://github.com/lostfictions/znv
MIT License
349 stars 6 forks source link

Add edge runtime compatibility and allow custom formatters #15

Open lostfictions opened 9 months ago

lostfictions commented 9 months ago

Resolves #2, supersedes #9 and #11.

This PR adds support for non-Node runtimes via a new entrypoint, znv/compat. To accomplish this, I've added the ability to pass a custom reporter to parseEnv, or more granular token formatters.

The default entrypoint, znv, now exports a version of parseEnv that defaults to colorized tokens, which matches the current behaviour. This relies on Node's tty module.

The new znv/compat entrypoint exports a version of parseEnv that doesn't colorize any tokens; nothing in this codepath imports tty or any other Node module, so it should be compatible with serverless environments (and even browsers, if you somehow need environment parsing there).

Additionally, I've removed the dependency on the colorette module and have instead added a simplified version of it for our own use.


One small thing I'm unsure about is that I had to change the signature of the "internal" parseEnv:

 function parseEnvImpl<T extends Schemas>(
   env: Record<string, string | undefined>,
-  schemas: T & RestrictSchemas<T>,
+  schemas: T,
   reporterOrTokenFormatters: Reporter | TokenFormatters,
 ): DeepReadonlyObject<ParsedSchema<T>> {

but the exported parseEnv that wraps the above parseEnvImpl retains RestrictSchemas<T>, so everything should work the same:

type ParseEnv = <T extends Schemas>(
  env: Record<string, string | undefined>,
  schemas: T & RestrictSchemas<T>,
  reporterOrTokenFormatters?: Reporter | TokenFormatters,
) => DeepReadonlyObject<ParsedSchema<T>>;

All this feels a little clunky, but I couldn't think of any other way to do this that doesn't add a bunch of other complexity. Alternate suggestions welcome!


Please take a look if you're one of the people who requested serverless support for znv! I've published it to npm under the next tag, so you can use npm i znv@next to try it out.

capaj commented 3 months ago

Nice one! Will definitely try next out

capaj commented 3 months ago

Just one question-why was this not merged yet?

lostfictions commented 3 months ago

Just one question-why was this not merged yet?

Because I work on this project unpaid as volunteer :)

I don't currently use any edge runtimes and didn't have the time to investigate how well this solution works, so I was relying on feedback from those who raised issues and requested a solution. I didn't receive any, so the pull request has been sitting here. If you're willing to try the next branch and confirm that it works for you, I'll be happy to merge it this week!

mikkel-arturo commented 6 days ago

Thanks, this works for me.