or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cli-interface.mdcore-execution.mdenvironment-loading.mdfile-formats.mdindex.mdutilities.md
tile.json

file-formats.mddocs/

File Format Support

Comprehensive support for multiple environment file formats including standard .env files, JSON configuration, JavaScript modules, TypeScript files, and multi-environment RC files. Each format provides specific advantages for different use cases.

Capabilities

Environment File Parsing

Core function for parsing individual environment files with automatic format detection.

/**
 * Gets the environment vars from an env file
 * @param envFilePath - Path to the environment file  
 * @returns Promise resolving to parsed environment variables
 */
function getEnvFileVars(envFilePath: string): Promise<Environment>;

Supported Extensions:

const IMPORT_HOOK_EXTENSIONS = [
  '.json',
  '.js',
  '.cjs', 
  '.mjs',
  '.ts',
  '.mts',
  '.cts',
  '.tsx',
];

RC File Parsing

Function for parsing multi-environment configuration files.

/**
 * Gets the env vars from the rc file and rc environments
 * @param options - RC file configuration with environments
 * @returns Promise resolving to merged environment variables
 */
function getRCFileVars(
  { environments, filePath }: { environments: string[], filePath: string },
): Promise<Environment>;

File Format Details

Standard .env Files

Traditional dotenv format with key=value pairs and comment support.

Format:

# This is a comment
NODE_ENV=development
API_URL=http://localhost:3000
DATABASE_URL=postgresql://user:pass@localhost/db

# Multiline values with quotes
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQ..."

# Variable references (processed with --recursive)
FULL_URL=$API_URL/api/v1

Features:

  • Comments with #
  • Quoted values for spaces and special characters
  • No export statements needed
  • Compatible with standard dotenv libraries

JSON Environment Files

JSON format for structured environment configuration.

Format (.env.json):

{
  "NODE_ENV": "development",
  "API_URL": "http://localhost:3000",
  "DATABASE_URL": "postgresql://user:pass@localhost/db",
  "PORT": "3000",
  "FEATURE_FLAGS": "{\"newUI\": true, \"beta\": false}"
}

Features:

  • Structured JSON format
  • All values must be strings
  • Proper JSON validation
  • No comments allowed

JavaScript Environment Files

JavaScript modules that export environment objects.

Format (.env.js, .env.mjs, .env.cjs):

// .env.js - ES Module
export default {
  NODE_ENV: 'development',
  API_URL: process.env.NODE_ENV === 'production' 
    ? 'https://api.production.com'
    : 'http://localhost:3000',
  BUILD_TIME: new Date().toISOString(),
  VERSION: require('./package.json').version
};

// .env.cjs - CommonJS  
module.exports = {
  NODE_ENV: 'development',
  API_URL: 'http://localhost:3000'
};

Features:

  • Dynamic value computation
  • Conditional logic based on environment
  • Access to Node.js APIs and modules
  • Can import other files and packages

TypeScript Environment Files

TypeScript modules with type safety for environment configuration.

Format (.env.ts, .env.mts, .env.cts):

interface EnvironmentConfig {
  NODE_ENV: 'development' | 'production' | 'test';
  API_URL: string;
  PORT: string;
  DATABASE_URL: string;
}

const config: EnvironmentConfig = {
  NODE_ENV: 'development',
  API_URL: 'http://localhost:3000',
  PORT: '3000',
  DATABASE_URL: 'postgresql://localhost/myapp_dev'
};

export default config;

Features:

  • Full TypeScript type checking
  • Interface definitions for environment structure
  • Compile-time validation
  • IDE autocompletion and error checking
  • Requires tsx loader for execution

RC Configuration Files

Multi-environment configuration files supporting environment-specific settings.

Format (.env-cmdrc, .env-cmdrc.json):

{
  "development": {
    "NODE_ENV": "development",
    "API_URL": "http://localhost:3000",
    "DEBUG": "true"
  },
  "staging": {
    "NODE_ENV": "staging", 
    "API_URL": "https://api-staging.example.com",
    "DEBUG": "false"
  },
  "production": {
    "NODE_ENV": "production",
    "API_URL": "https://api.example.com",
    "DEBUG": "false"
  }
}

JavaScript RC Format (.env-cmdrc.js):

const environments = {
  development: {
    NODE_ENV: 'development',
    API_URL: 'http://localhost:3000'
  },
  production: {
    NODE_ENV: 'production',
    API_URL: 'https://api.example.com'
  }
};

export default environments;

Features:

  • Multiple environments in single file
  • Environment inheritance and merging
  • Shared configuration patterns
  • Support for JSON and JavaScript formats

File Loading Process

Format Detection

Files are processed based on their extension:

const ext = extname(absolutePath).toLowerCase();

if (IMPORT_HOOK_EXTENSIONS.includes(ext)) {
  // Dynamic import for JS/TS/JSON files
  const res = await import(pathToFileURL(absolutePath).href);
  return res.default || res;
} else {
  // Parse as .env format
  return parseEnvFile(absolutePath);
}

Import Handling

Different import strategies based on file type:

JSON Files:

const attributeTypes = ext === '.json' 
  ? { with: { type: 'json' } } 
  : {};
const res = await import(pathToFileURL(absolutePath).href, attributeTypes);

TypeScript Files:

if (/tsx?$/.test(ext)) {
  checkIfTypescriptSupported(); // Validates tsx loader availability
}

Module Resolution:

// Handle both default and named exports
const env = res.default || res;

// Support for promise-returning modules
if (isPromise(env)) {
  return await env;
}

Error Handling

File-Specific Errors

PathError: File not found or inaccessible

if (!existsSync(absolutePath)) {
  const pathError = new Error(`Invalid env file path (${envFilePath}).`);
  pathError.name = 'PathError';
  throw pathError;
}

ParseError: File parsing failures

try {
  const parsedVars = parseEnvFormat(content);
  return parsedVars;
} catch (e) {
  const parseError = new Error(`Failed to parse env file: ${e.message}`);
  parseError.name = 'ParseError';
  throw parseError;
}

LoaderError: Module loading failures

function isLoaderError(error: unknown): error is Error {
  return (
    error instanceof Error &&
    'code' in error &&
    error.code === 'ERR_UNKNOWN_FILE_EXTENSION'
  );
}

RC File Environment Errors

EnvironmentError: Requested environment not found in RC file

const envError = new Error(`Failed to find environment "${environment}" in RC file`);
envError.name = 'EnvironmentError';
throw envError;

TypeScript Loader Support

For TypeScript file support, env-cmd checks for tsx loader availability:

/**
 * Check if TypeScript is supported in the current environment
 * @throws Error if TypeScript files cannot be loaded
 */
function checkIfTypescriptSupported(): void;

Loader Detection:

  • Checks for tsx loader in module resolution
  • Validates TypeScript compilation support
  • Provides helpful error messages for missing loaders

Low-Level Parsing Functions

Direct parsing functions for working with environment file content at a granular level.

/**
 * Parse out all env vars from a given env file string and return an object
 * @param envFileString - Raw environment file content
 * @returns Parsed environment variables object
 */
function parseEnvString(envFileString: string): Environment;

/**
 * Parse out all env vars from an env file string
 * @param envString - Environment string content  
 * @returns Environment variables object
 */
function parseEnvVars(envString: string): Environment;

/**
 * Strips out comments from env file string
 * @param envString - Environment file content with comments
 * @returns Content with comments removed
 */
function stripComments(envString: string): string;

/**
 * Strips out newlines from env file string  
 * @param envString - Environment file content with empty lines
 * @returns Content with empty lines removed
 */
function stripEmptyLines(envString: string): string;

/**
 * Normalize imported objects to environment variable format
 * @param input - Raw imported object from JS/TS modules
 * @param absolutePath - File path for error reporting
 * @returns Normalized environment variables with string values
 */
function normalizeEnvObject(input: unknown, absolutePath: string): Environment;

Usage Examples:

import { parseEnvString, stripComments } from "env-cmd/dist/parse-env-file.js";

// Parse raw .env content
const envContent = `
# Database configuration
DB_HOST=localhost
DB_PORT=5432
DB_NAME=myapp
`;

const parsed = parseEnvString(envContent);
// Result: { DB_HOST: 'localhost', DB_PORT: '5432', DB_NAME: 'myapp' }

// Remove comments from content
const cleaned = stripComments(envContent);
// Result: Content without comment lines

Parsing Process:

  1. Comment Removal: stripComments() removes lines starting with #
  2. Empty Line Removal: stripEmptyLines() removes blank lines
  3. Variable Parsing: parseEnvVars() extracts key=value pairs
  4. Quote Handling: Supports both single and double quoted values
  5. Inline Comments: Removes comments from unquoted values

TypeScript Support

TypeScript Loader Validation

Function for validating TypeScript file loading support in the current environment.

/**
 * Check if TypeScript is supported in the current environment
 * @throws Error if TypeScript files cannot be loaded
 */
function checkIfTypescriptSupported(): void;

Usage:

import { checkIfTypescriptSupported } from "env-cmd/dist/loaders/typescript.js";

try {
  checkIfTypescriptSupported();
  // TypeScript files can be loaded
} catch (error) {
  console.error("TypeScript support not available:", error.message);
}

Validation Process:

  • Checks for tsx loader availability
  • Validates TypeScript compilation support
  • Throws descriptive errors for missing loaders

Path Resolution

All file paths undergo resolution processing:

/**
 * A simple function for resolving the path the user entered
 * @param userPath - User-provided file path
 * @returns Absolute resolved path
 */
function resolveEnvFilePath(userPath: string): string;

Resolution Features:

  • Home directory expansion: ~/.env/home/user/.env
  • Relative path resolution: ./config/.env/current/dir/config/.env
  • Current working directory context: config/.env/current/dir/config/.env