-
-
Notifications
You must be signed in to change notification settings - Fork 556
/
Copy pathenv.js
64 lines (54 loc) · 2.21 KB
/
env.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* SPDX-FileCopyrightText: 2014-present Kriasoft */
/* SPDX-License-Identifier: MIT */
import { SecretManagerServiceClient } from "@google-cloud/secret-manager";
import { resolve } from "node:path";
import { fileURLToPath, URL } from "node:url";
import { load } from "ts-import";
import { loadEnv as loadViteEnv } from "vite";
// The root workspace folder
const rootDir = fileURLToPath(new URL("../", import.meta.url));
// Matches Google Secret Manager secret names
const secretRegExp = /^projects\/[\w-]+\/secrets\/[\w-]+\/versions\/[\w-]+/;
/**
* Loads environment variables from the `.env` file(s).
*
* @param {string | undefined} mode Environment name such as "development" or "production"
* @param {string} envFile Path to the `env.ts` file (using `envalid`)
* @returns {Promise<void>}
*/
export async function loadEnv(mode, envFile) {
const originalEnv = process.env;
// Load environment variables from `.env` file(s) using Vite's `loadEnv()`
// https://vitejs.dev/guide/api-javascript.html#loadenv
const env = loadViteEnv(mode, rootDir, "");
// Load the list of environment variables required by the application
process.env = { ...process.env, ...env };
const envModule = await load(envFile, {
useCache: false,
transpileOptions: {
cache: { dir: resolve("./node_modules/.cache/ts-import") },
},
});
// Restore the original environment variables
process.env = originalEnv;
// Initialize Google Secret Manager client
// https://cloud.google.com/secret-manager/docs
const sm = new SecretManagerServiceClient();
// Add environment variables required by the application to the `process.env`
await Promise.all(
Object.keys(envModule.env ?? envModule.default ?? {}).map(async (key) => {
if (env[key]) {
if (secretRegExp.test(env[key])) {
// Load the secret value from Google Secret Manager
// https://cloud.google.com/secret-manager/docs/access-secret-version
const [res] = await sm.accessSecretVersion({ name: env[key] });
const secret = res.payload?.data?.toString();
if (secret) process.env[key] = secret;
} else {
process.env[key] = env[key];
}
}
}),
);
}
loadEnv("development", "./env.ts");