Collection of utility functions that support the core env-cmd functionality, including environment variable expansion, path resolution, argument parsing, and type checking utilities.
Function for expanding environment variable references in strings using $var and ${var} syntax.
/**
* expandEnvs Replaces $var and ${var} in args and command with environment variables
* if the environment variable doesn't exist, it leaves it as is.
* @param str - String containing variable references to expand
* @param envs - Environment variables to use for expansion
* @returns String with variables expanded
*/
function expandEnvs(str: string, envs: Environment): string;Variable Syntax Support:
$VAR_NAME - Simple variable reference${VAR_NAME} - Braced variable reference\$VAR_NAME - Literal dollar sign (not expanded)Usage Examples:
import { expandEnvs } from "env-cmd/dist/expand-envs.js";
const env = {
API_URL: "https://api.example.com",
VERSION: "v1",
PORT: "3000"
};
// Simple expansion
expandEnvs("$API_URL/users", env);
// Result: "https://api.example.com/users"
// Braced expansion
expandEnvs("${API_URL}/${VERSION}/users", env);
// Result: "https://api.example.com/v1/users"
// Mixed expansion
expandEnvs("Server running on $API_URL:$PORT", env);
// Result: "Server running on https://api.example.com:3000"
// Undefined variables remain unchanged
expandEnvs("$API_URL/$MISSING_VAR", env);
// Result: "https://api.example.com/$MISSING_VAR"
// Escaped variables
expandEnvs("Price: \\$19.99", env);
// Result: "Price: $19.99"Expansion Behavior:
envs are replaced with their values$VAR or ${VAR}\$) become literal dollar signsFunction for resolving user-provided file paths with home directory expansion and absolute path conversion.
/**
* A simple function for resolving the path the user entered
* @param userPath - User-provided file path (may include ~ for home directory)
* @returns Absolute resolved path
*/
function resolveEnvFilePath(userPath: string): string;Path Resolution Features:
import { resolveEnvFilePath } from "env-cmd/dist/utils.js";
// Home directory expansion
resolveEnvFilePath("~/.env");
// Result: "/home/username/.env" (on Unix-like systems)
resolveEnvFilePath("~/config/.env.production");
// Result: "/home/username/config/.env.production"
// Relative path resolution
resolveEnvFilePath("./config/.env");
// Result: "/current/working/directory/config/.env"
resolveEnvFilePath("../shared/.env");
// Result: "/current/working/shared/.env"
// Absolute paths pass through unchanged
resolveEnvFilePath("/etc/environment");
// Result: "/etc/environment"Simple utility for parsing comma-separated argument lists.
/**
* A simple function that parses a comma separated string into an array of strings
* @param list - Comma-separated string
* @returns Array of trimmed strings
*/
function parseArgList(list: string): string[];Usage Examples:
import { parseArgList } from "env-cmd/dist/utils.js";
// Basic comma separation
parseArgList("development,staging,production");
// Result: ["development", "staging", "production"]
// With spaces (automatically trimmed)
parseArgList("dev, staging , prod");
// Result: ["dev", "staging", "prod"]
// Single item
parseArgList("production");
// Result: ["production"]
// Empty string
parseArgList("");
// Result: [""]Utility function for detecting promise-like objects (thenables).
/**
* A simple function to test if the value is a promise/thenable
* @param value - Value to test for promise-like behavior
* @returns True if value has a 'then' method
*/
function isPromise<T>(value?: T | PromiseLike<T>): value is PromiseLike<T>;Usage Examples:
import { isPromise } from "env-cmd/dist/utils.js";
// Regular promise
const promise = Promise.resolve("value");
isPromise(promise); // true
// Thenable object
const thenable = { then: (resolve) => resolve("value") };
isPromise(thenable); // true
// Regular values
isPromise("string"); // false
isPromise(42); // false
isPromise(null); // false
isPromise(undefined); // false
// In file loading context
const moduleExport = await import('./config.js');
if (isPromise(moduleExport.default)) {
const config = await moduleExport.default;
return config;
}Utility function for identifying specific loader errors during module imports.
/**
* @returns true if the error is `ERR_UNKNOWN_FILE_EXTENSION`
* @param error - Error object to check
*/
function isLoaderError(error: unknown): error is Error;Usage Examples:
import { isLoaderError } from "env-cmd/dist/utils.js";
try {
const config = await import('./config.unknown');
} catch (error) {
if (isLoaderError(error)) {
// Handle file extension errors specifically
throw new Error(`Unsupported file format: ${error.message}`);
}
// Handle other import errors
throw error;
}Error Detection Logic:
function isLoaderError(error: unknown): error is Error {
return (
error instanceof Error &&
'code' in error &&
error.code === 'ERR_UNKNOWN_FILE_EXTENSION'
);
}Array of file extensions that support dynamic imports:
const IMPORT_HOOK_EXTENSIONS = [
'.json',
'.js',
'.cjs',
'.mjs',
'.ts',
'.mts',
'.cts',
'.tsx',
];Extension Categories:
.json - JSON files with type assertion.js, .mjs, .cjs - Various JavaScript module formats.ts, .mts, .cts, .tsx - TypeScript modules (require loader)The expandEnvs function uses a sophisticated regular expression for variable matching:
const pattern = /(?<!\\)\$(\{\w+\}|\w+)?/g;Pattern Breakdown:
(?<!\\) - Negative lookbehind: not preceded by backslash (escape)\$ - Literal dollar sign(\{\w+\}|\w+)? - Capture group with two alternatives:
\{\w+\} - Braced format: ${VAR_NAME}\w+ - Simple format: $VAR_NAMEg - Global flag for all matchesPattern Matching Examples:
"$API_URL".match(pattern); // ["$API_URL"]
"${API_URL}".match(pattern); // ["${API_URL}"]
"\\$ESCAPED".match(pattern); // null (escaped)
"$VAR1 and $VAR2".match(pattern); // ["$VAR1", "$VAR2"]The resolveEnvFilePath function handles home directory expansion across platforms:
const home = homedir() as string | undefined;
if (home != null) {
userPath = userPath.replace(/^~($|\/|\\)/, `${home}$1`);
}Platform Support:
~ expands to /home/username~ expands to C:\Users\username~ remains unchangedThe regex pattern handles both Unix (/) and Windows (\) path separators:
/^~($|\/|\\)/ // Matches ~, ~/, or ~\