UNPKG

validate-env-vars

Version:

A lightweight utility to check the presence and validity of environment variables, as specified by a Zod schema

2 lines (1 loc) 2.68 kB
var h=Object.defineProperty,S=Object.defineProperties;var x=Object.getOwnPropertyDescriptors;var f=Object.getOwnPropertySymbols;var L=Object.prototype.hasOwnProperty,_=Object.prototype.propertyIsEnumerable;var y=(e,o,n)=>o in e?h(e,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[o]=n,E=(e,o)=>{for(var n in o||(o={}))L.call(o,n)&&y(e,n,o[n]);if(f)for(var n of f(o))_.call(o,n)&&y(e,n,o[n]);return e},m=(e,o)=>S(e,x(o));import{config as A}from"dotenv";import{expand as P}from"dotenv-expand";import{existsSync as j}from"fs";import{ZodObject as C}from"zod";var p="\x1B[31m",l="\x1B[33m",d="\x1B[32m",s="\x1B[0m",O=`${p}\u2715${s}`,v=`${d}\u2714${s}`,u=`${l}\u26A0${s}`,g=["ZodString","ZodEnum","ZodLiteral","ZodEffects","ZodUnion","ZodOptional"];function R(e){if(!(e instanceof C))throw new Error(`The provided schema must be a ZodObject. Received: ${typeof e}`);Object.values(e.shape).forEach(o=>{let n=o._def.typeName;if(!g.includes(n))throw new Error(`All fields in the schema must be Zod strings, Zod literals, or Zod enums. Received: ${n}`)})}function T(e){if(!j(e))throw new Error(`File not found: ${e}`)}function w(e,o,n){let i={};for(let t of Object.keys(o.shape))i[t]={optional:o.shape[t].isOptional(),error:null,data:`${process.env[t]}`};if(e.success)for(let t of Object.keys(e.data))i[t].data=e.data[t];else for(let t of e.error.issues){let r=t.path[0],c=t.message;i[r]=m(E({},i[r]),{data:null,error:c})}let a=0;return Object.entries(i).forEach(([t,r])=>{if(r.error===null&&r.data!==""&&r.data!=="undefined"){let c=n?` ${d}'${r.data}'${s}`:"";console.log(`${v} ${t}${c}`)}else r.error===null&&r.optional?console.log(`${u} ${t} ${l}'${r.data}'${s}`):(console.error(`${O} ${t}: ${p}${r.error}${s}`),a++)}),a}var Z=w;import{string as D,enum as q,literal as G,z as b}from"zod";var $=()=>b.string().min(1,{message:"Variable cannot be empty"}),H=()=>$().refine(e=>e!="undefined",{message:"Variable cannot equal 'undefined'"}),J=()=>$().regex(/^-?\d+$/,{message:"Variable must be a valid integer"}),Q=e=>b.object(e);function W(e){let{schema:o,envPath:n,logVars:i}=e;R(o),T(n);let a=A({path:n});if(a.error)throw new Error(a.error.message);P(a);let t=o.safeParse(process.env),r=Z(t,o,i);if(!t.success)throw new Error(`${r} missing or invalid environment variable${r===1?"":"s"}`);console.log(`${d}All required environment variables are valid${s}`)}function z({schema:e,envPath:o=".env",exitOnError:n=!1,logVars:i=!0}){try{W({schema:e,envPath:o,logVars:i})}catch(a){if(n)console.error(`${p}${a.message}${s}`),process.exit(1);else throw a}}var se=z;export{se as default,q as envEnum,J as envInteger,G as envLiteral,H as envNonEmptyString,Q as envObject,D as envString};