config.ts 1.0 KB

12345678910111213141516171819202122232425
  1. /**
  2. * Deeply injects environment variables into a configuration object/string/json
  3. *
  4. * Uses VSCode env:name pattern: https://code.visualstudio.com/docs/reference/variables-reference#_environment-variables
  5. *
  6. * Does not mutate original object
  7. */
  8. export async function injectEnv<C extends string | Record<PropertyKey, any>>(config: C, notFoundValue: any = "") {
  9. // Use simple regex replace for now, will see if object traversal and recursion is needed here (e.g: for non-serializable objects)
  10. const isObject = typeof config === "object"
  11. let _config: string = isObject ? JSON.stringify(config) : config
  12. _config = _config.replace(/\$\{env:([\w]+)\}/g, (_, name) => {
  13. // Check if null or undefined
  14. // intentionally using == to match null | undefined
  15. if (process.env[name] == null) {
  16. console.warn(`[injectEnv] env variable ${name} referenced but not found in process.env`)
  17. }
  18. return process.env[name] ?? notFoundValue
  19. })
  20. return (isObject ? JSON.parse(_config) : _config) as C extends string ? string : C
  21. }