Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: improve env polyfill #138

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 41 additions & 23 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,59 @@
const _envShim = Object.create(null);

export type EnvObject = Record<string, string | undefined>;

const _getEnv = (useShim?: boolean) =>
globalThis.process?.env ||
import.meta.env ||
globalThis.Deno?.env.toObject() ||
globalThis.__env__ ||
(useShim ? _envShim : globalThis);
const _envShim = Object.create(null) as EnvObject;

export const env = new Proxy<EnvObject>(_envShim, {
get(_, prop) {
const env = _getEnv();
return env[prop as any] ?? _envShim[prop];
return getEnvValue(prop as string);
},
has(_, prop) {
const env = _getEnv();
return prop in env || prop in _envShim;
return getEnvValue(prop as string) !== undefined;
},
set(_, prop, value) {
const env = _getEnv(true);
env[prop as any] = value;
return true;
return Reflect.set(getEnvObj(), prop as string, `${value}`);
},
deleteProperty(_, prop) {
if (!prop) {
return false;
}
const env = _getEnv(true);
delete env[prop as any];
return true;
return Reflect.deleteProperty(getEnvObj(), prop as string);
},
ownKeys() {
const env = _getEnv(true);
return Object.keys(env);
return Reflect.ownKeys(getEnvObj());
},
defineProperty(_, prop, descriptor) {
const value = descriptor.get?.() ?? descriptor.value;
return Reflect.set(getEnvObj(), prop as string, `${value}`);
},
});

function getEnvObj(fallbackToGlobal?: boolean): EnvObject {
if (globalThis.__env__) {
return globalThis.__env__;
}
if (globalThis.process?.env) {
return globalThis.process.env;
}
if (import.meta.env) {
return import.meta.env;
}
return fallbackToGlobal ? (globalThis as unknown as EnvObject) : _envShim;
}

function getEnvValue(key: string): string | undefined {
if (globalThis.__env__ && key in globalThis.__env__) {
return globalThis.__env__[key];
}
if (globalThis.process?.env && key in globalThis.process.env) {
return globalThis.process.env[key];
}
if (import.meta?.env && key in import.meta.env) {
return import.meta.env[key];
}
if (globalThis.Deno?.env) {
return (globalThis.Deno.env as any).get(key);
}
if (key in _envShim) {
return _envShim[key];
}
}

export const nodeENV =
(typeof process !== "undefined" && process.env && process.env.NODE_ENV) || "";
Loading