Git Product home page Git Product logo

std-env's Introduction

std-env

npm npm bundlephobia

Runtime agnostic JS utils

Installation

# Using npm
npm i std-env

# Using pnpm
pnpm i std-env

# Using yarn
yarn add std-env

Usage

// ESM
import { env, isDevelopment, isProduction } from "std-env";

// CommonJS
const { env, isDevelopment, isProduction } = require("std-env");

Flags

  • hasTTY
  • hasWindow
  • isDebug
  • isDevelopment
  • isLinux
  • isMacOS
  • isMinimal
  • isProduction
  • isTest
  • isWindows
  • platform
  • isColorSupported
  • nodeVersion
  • nodeMajorVersion

You can read more about how each flag works from ./src/flags.ts.

Provider Detection

std-env can automatically detect the current runtime provider based on environment variables.

You can use isCI and platform exports to detect it:

import { isCI, provider, providerInfo } from "std-env";

console.log({
  isCI, // true
  provider, // "github_actions"
  providerInfo, // { name: "github_actions", isCI: true }
});

List of well known providers can be found from ./src/providers.ts.

Runtime Detection

std-env can automatically detect the current JavaScript runtime based on global variables, following the WinterCG Runtime Keys proposal:

import { runtime, runtimeInfo } from "std-env";

// "" | "node" | "deno" | "bun" | "workerd" ...
console.log(runtime);

// { name: "node" }
console.log(runtimeInfo);

You can also use individual named exports for each runtime detection:

Note

When running code in Bun and Deno with Node.js compatibility mode, isNode flag will be also true, indicating running in a Node.js compatible runtime.

Use runtime === "node" if you need strict check for Node.js runtime.

  • isNode
  • isBun
  • isDeno
  • isNetlify
  • isEdgeLight
  • isWorkerd
  • isFastly

List of well known providers can be found from ./src/runtimes.ts.

Platform-Agnostic env

std-env provides a lightweight proxy to access environment variables in a platform agnostic way.

import { env } from "std-env";

Platform-Agnostic process

std-env provides a lightweight proxy to access process object in a platform agnostic way.

import { process } from "std-env";

License

MIT

std-env's People

Contributors

anishghimire862 avatar atinux avatar danielroe avatar danifoldi avatar honkinggoose avatar intevel avatar maximepvrt avatar namesmt avatar narrator avatar nozomuikuta avatar ntnyq avatar o-az avatar patricklx avatar pi0 avatar quiibz avatar renovate[bot] avatar rstoenescu avatar sirlancelot avatar timursaurus avatar yuaanlin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

std-env's Issues

Document the environment variables in the README

I'm developing a Nuxt application inside a Docker container with a TTY connection tailing the logs. The fancy progress bars on build do not always render correctly so I wanted to disable them.

I wound up doing it the hard way by overriding the progress bar plugins in the webpack config, see here.

I only learned after the fact that the minimalCLI (which Nuxt uses to determine basic or fancy progress bars in the CLI) has environment variables that can force certain modes (eg: MINIMAL=1).

It would be really good to document the environment variables in the README.

Expose `provider`

(initial idea from @ascorbic) we can expose provider (maybe) by using ci-info that is already a dependency.

Additional environment variables that need either PR to ci-info's upstream or local patch:

  • NETLIFY_LOCAL
  • INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN (/cc @danielroe we don't have normal AZURE_PIPELINES in azure static right?)
  • Cloudflare pages (TODO: Ask or check if there is any)
  • Docker

Version 3.4.0 Incompatible with Node.js 12

Environment

std-env: v3.4.0
Node.js: v12.22.2

Reproduction

It looks like the 3.4.0 build doesn't work properly on Node.js v12 anymore, which uses ?? and ?. and other ES2020 syntax. But 3.3.3 doesn't have this problem. Wouldn't it be more appropriate as a BREAKING CHANGE?

Describe the bug

Throw error when run in Node.js v12. SyntaxError: Unexpected token '.'

Additional context

No response

Logs

No response

ci-info update

After digging a bit, I found out that the plugin you use to detect CI, does not support GitHub action with the pinned version. There was no release (watson/ci-info#48) since support was implemented (watson/ci-info#42). Consider pinning a commit, or forking the project.

Bug: Obect keys for env object

Environment

Node.JS: 18.18.0
Package: 3.7.0

Reproduction

Check out the provided test in the pr, without modifications of the src/env.ts file

Describe the bug

At the moment it is not possible to use Object.keys with the exported variable.

Additional context

No response

Logs

No response

Cannot find module `std-env` with `"moduleResolution": "bundler"` tsconfig

Environment

"devDependencies": {
  "nuxt": "^3.4.1",
  "std-env": "^3.3.2"
}

Reproduction

https://stackblitz.com/edit/nuxt-starter-clagn3?file=nuxt.config.ts,tsconfig.json

Describe the bug

std-env package is not resolved when using "moduleResolution": "bundler"

import { isDebug } from 'std-env'
// Cannot find module 'std-env'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?(2792)
{
  // https://v3.nuxtjs.org/concepts/typescript
  "extends": "./.nuxt/tsconfig.json",
  "compilerOptions": {
    "moduleResolution": "bundler"
  }
}

Additional context

No response

Logs

No response

`process.env` is prefered over `import.meta.env`

Environment

node 20.11
std-env 3.7

Reproduction

not really relevant

Describe the bug

So I'm not sure if I'd call this a bug per-se, maybe more of an observation to open up a discussion how we could solve this.

Astro is a bit (if you ask me) dumb in the way that they have a process.env on the server but they don't populate it with stuff from your env file. That stuff goes on import.meta.env. This means that the following logs undefined:

import { process } from "std-env";
console.log(process.env.SOME_ENV_FROM_ENVFILE);

This is cause (like I said), process does exists, so std-env chooses it as the env object:

std-env/src/env.ts

Lines 5 to 10 in 7528b13

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

Any ideas how to solve this in a nice way? I think this is just a stupid behavior from Astro but any workaround we can do to support this would be great. We recently moved to std-env in uploadthing to have a single source of truth for accessing environment variables but then I stumbled on this edge-case...

Additional context

No response

Logs

process.env {
  MANPATH: '/opt/homebrew/share/man::',
  COREPACK_ROOT: '/Users/julius/Library/Application Support/fnm/node-versions/v20.11.0/installation/lib/node_modules/corepack',
  BUNCH_OF_STUFF: "THAT I REMOVED",
  NODE_ENV: 'development'
}
import.meta.env {
  BASE_URL: '/',
  MODE: 'development',
  DEV: true,
  PROD: false,
  SSR: true,
  SITE: undefined,
  ASSETS_PREFIX: undefined,
  UPLOADTHING_SECRET: 'sk_live_xxxxxx' // <-- this is coming from .env.local
}

Add detection for tests runners ? (Jest, Vitest, Playwright, etc...)

Describe the feature

Most test framework sets a couple of env variables that we could use to detect them.

We could have a similar API here to the provider detection :

import { isTest, testRunner, testRunnerInfo } from "std-env";

console.log({
  isCI, // true
  provider, // "vitest"
  providerInfo, // { name: "vitest", isTest: true, ...etc }
});

Additional information

  • Would you be willing to help implement this feature?

Uncaught TypeError: Cannot read properties of undefined (reading 'bun')

Environment

browser, edge

Reproduction

Upgrading from 3.3.3 to 3.4.2

Describe the bug

After upgrading from 3.3.3 to 3.4.2 I get this error upon starting the nuxt app:
Uncaught TypeError: Cannot read properties of undefined (reading 'bun') at index.mjs:1:2785

Reverting back to 3.3.3: no issues anymore

Additional context

No response

Logs

No response

Support static `NODE_ENV` detection

In some environments (like nuxt builds with vite/webpack and nitropack) process.env.NODE_ENV is statically replaced. This makes std-env not working as expected. We might use an inline syntax instead that get's replaced.

E2E reproduction:

https://stackblitz.com/edit/nuxt-starter-7oay4d?file=components%2Fapp-config-client.client.vue,components%2Fapp-config-server.server.vue,app.vue,nuxt.config.ts,app.config.ts,components%2Fapp-config-api.vue,server%2Fapi%2Fapp-config.ts

Support new runtime `isJiti` and `isTsx`?

Describe the feature

I'm developing a vite plugin using unbuild, if it's in stub mode(jiti), inject a package for main.ts using a relative path, otherwise use the package name.

Additional information

  • Would you be willing to help implement this feature?

QuickJS and JerryScript detection

Describe the feature

QuickJS and JerryScript (maybe also Duktape) are also used in actual JavaScript development. Is it feasible to add support for these runtimes?

Also console usually aren't provided directly from these runtimes, might also add a platform-agnostic console here?

Additional information

  • Would you be willing to help implement this feature?

Support standard build envs for CI / Git integrations

CI/CD pipelines often provide variables such as deployment URL, git hash, git branch, etc. We might expose standard exports that can scan them.

Some providers:

Vercel

https://vercel.com/docs/projects/environment-variables/system-environment-variables

VERCEL_URL, VERCEL_BRANCH_URL, VERCEL_GIT_PROVIDER, VERCEL_GIT_REPO_SLUG, VERCEL_GIT_REPO_OWNER, VERCEL_GIT_REPO_ID, VERCEL_GIT_COMMIT_REF, VERCEL_GIT_COMMIT_SHA, VERCEL_GIT_COMMIT_MESSAGE, VERCEL_GIT_COMMIT_AUTHOR_LOGIN, VERCEL_GIT_COMMIT_AUTHOR_NAME, VERCEL_GIT_PREVIOUS_SHA

Netlify

https://docs.netlify.com/configure-builds/environment-variables/

REPOSITORY_URL, BRANCH, HEAD, COMMIT_REF, CACHED_COMMIT_REF, CACHED_COMMIT_REF, PULL_REQUEST, REVIEW_ID, URL, DEPLOY_URL, DEPLOY_PRIME_URL

Github Actions

https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables

GITHUB_SHA, GITHUB_ACTOR, GITHUB_API_URL, GITHUB_BASE_REF, GITHUB_HEAD_REF, GITHUB_REF, GITHUB_REF_NAME, GITHUB_REPOSITORY, GITHUB_REPOSITORY_OWNER, GITHUB_REPOSITORY_OWNER_ID, GITHUB_WORKFLOW_SHA

Gitlab CI

https://docs.gitlab.com/ee/ci/variables/predefined_variables.html

CI_COMMIT_AUTHOR, CI_COMMIT_BEFORE_SHA, CI_COMMIT_BRANCH, CI_COMMIT_DESCRIPTION, CI_COMMIT_MESSAGE, CI_COMMIT_REF_NAME, CI_COMMIT_SHA, CI_COMMIT_SHORT_SHA, CI_COMMIT_TAG, CI_ENVIRONMENT_URL, CI_PAGES_URL,

Cloudflare pages

https://developers.cloudflare.com/pages/configuration/build-configuration/#environment-variables

CF_PAGES, CF_PAGES_COMMIT_SHA, CF_PAGES_BRANCH, CF_PAGES_URL

Reduce bundle size, when using a flag that does not depend on

Describe the feature

What to Expect

If we use this flag, providers will be bundled, but even if we use a flag that does not depend on providers, such as isWindows, they will still be bundled.

If they do not depend on it, we expect them not to be bundled.

Also, if you use isCI, all providers' code will be bundled. It might be nice to have a way for users to resolve providers themselves by exporting an API that resolves them.

Reproduction repo

https://github.com/kazupon/std-env-repro1

Related

rolldown/rolldown#754 (comment)

Additional information

  • Would you be willing to help implement this feature?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/autofix.yml
  • actions/checkout v4
  • actions/setup-node v4
  • autofix-ci/action ea32e3a12414e6d3183163c3424a7d7a8631ad84
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • codecov/codecov-action v4
npm
package.json
  • @types/node ^20.12.5
  • @vitest/coverage-v8 ^1.4.0
  • changelogen ^0.5.5
  • esbuild ^0.20.2
  • eslint ^8.57.0
  • eslint-config-unjs ^0.2.1
  • jiti ^1.21.0
  • prettier ^3.2.5
  • rollup ^4.14.1
  • typescript ^5.4.4
  • unbuild ^2.0.0
  • vitest ^1.4.0
  • pnpm 8.15.6

  • Check this box to trigger a request for Renovate to run again on this repository

Using package in Bun or in Deno with `npm:` specifier reports `isNode` as `true`

Environment

Package version:

Deno:

  • version: 1.38.2
  • OS: Windows

Reproduction

In a Deno REPL, run the following:

import {isNode, isDeno} from 'https://esm.sh/std-env';
console.log(isNode, isDeno); // false true
import {isNode, isDeno} from 'npm:std-env';
console.log(isNode, isDeno); // true true

Describe the bug

Under Deno, when using the package in a "regular" way, the platform detection works as expected.

But when using the npm: specifier, isNode is set to true.

If you log the process object exported by the package, you can see the difference: package loaded using URL import has an empty one, while the one loaded with npm has a "regular Node.js" process object, leading to the false positive.

Additional context

It would be feasible to correct that false positive by checking if isDeno is true, then forcing isNode to false. I guess it would be required under Bun as well since it provides Node.js compatibility too.

However, that leads to a question of semantics: do you want the library to report an identity, or a compatibility? Flags starting with is suggest identity, hence my opinion of thinking of this as a bug. However, you could extend the features of your package by also adding flags for compatibility, e.g. isLikeNode, etc.

However the latter would be very tricky: in my tests, globalThis.process, which you use for detection, is undefined except inside the context of evaluation of the package loaded with the npm: specifier. So the package could report a positive Node.js compatibility, when it's not 100% the case: the user has to import the process object here with import process from 'node:process', which is still making a difference. Besides that, Deno embeds Node.js compatibility but is more strict, for instance the node: specifier in imports is required.

I believe it should be double checked for Bun too. EDIT: I checked Bun (on WSL) and it really pushed Node.js' compatibility further: not only process is always global (and process.release.name does equal "node"), but it also doesn't force using node: specifier when importing builtin Node.js modules. And I confirm it also reports isNode as true.

Integrate runtime detection

Describe the feature

I've created detect-runtime a few months ago as a way to detect the current JavaScript runtime where the code is running. As Atinux suggested, we could bring this feature to std-env, which could be a great fit.

detect-runtime follows the WinterCG Runtime Keys specification, which sometimes duplicate the same underlying JavaScript runtime (edge-light is technically workerd, netlify is technically deno). Do we also want to follow this specification, or instead use a subset? (node, deno, bun, workerd, lagon, fastly)

Additional information

  • Would you be willing to help implement this feature?

process is not defined in browser

Environment

browser, chrome

Reproduction

e.g run vitest browser mode

Describe the bug

vitest fails to run because of invalid process access

Additional context

No response

Logs

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.