### Basic Setup Example in Browser Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/browser-support.md A complete example demonstrating how to define a configuration type, load it from an API endpoint with fallback defaults, and then use the loaded configuration in the browser. ```typescript import { loadConfig } from 'bunfig/browser' // Define your configuration type interface AppConfig { theme: 'light' | 'dark' language: string features: { newUI: boolean beta: boolean } } // Load configuration from an API endpoint const config = await loadConfig({ name: 'my-app', endpoint: '/api/config', // Your API endpoint defaultConfig: { // Fallback values if API request fails theme: 'light', language: 'en', features: { newUI: false, beta: false, }, }, }) // Use the configuration document.body.classList.add(`theme-${config.theme}`) ``` -------------------------------- ### List Output Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Example output from the list command. ```bash Configuration Files: ├── app (./config/app.config.ts) ├── database (./config/database.config.ts) ├── auth (./config/auth.config.ts) ├── logging (./config/logging.config.ts) ├── payments (./config/features/payments.config.ts) └── notifications (./config/features/notifications.config.ts) Total: 6 configurations ``` -------------------------------- ### Example Home Configuration File Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/home-directory.md This is a basic example of a global configuration file that can be used across multiple projects. It sets default values for theme, port, features, and user preferences. ```typescript // ~/.config/my-tool/config.ts export default { theme: 'dark', defaultPort: 8080, globalFeatures: ['feature1', 'feature2'], userPreferences: { notifications: true, autoSave: true, }, } ``` -------------------------------- ### Environment Variable Management Examples Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/environments.md Illustrates typical environment variable setups for development, staging, and production using a .env file format. These variables are commonly used to configure database connections, API keys, logging levels, and other environment-specific settings. ```bash # .env.development NODE_ENV=development DATABASE_URL=postgresql://localhost:5432/myapp_dev REDIS_URL=redis://localhost:6379/0 LOG_LEVEL=debug # .env.staging NODE_ENV=staging DATABASE_URL=postgresql://staging-db.example.com:5432/myapp REDIS_URL=redis://staging-redis.example.com:6379 LOG_LEVEL=info SESSION_SECRET=staging-secret-key # .env.production NODE_ENV=production DATABASE_URL=postgresql://prod-db.example.com:5432/myapp REDIS_URL=redis://prod-redis.example.com:6379 SESSION_SECRET=super-secure-production-secret SENDGRID_API_KEY=your-sendgrid-key S3_BUCKET=your-s3-bucket AWS_REGION=us-east-1 DATADOG_API_KEY=your-datadog-key ``` -------------------------------- ### CLI Command: init Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Initializes a new bunfig configuration setup in the project. ```APIDOC ## CLI Command: init ### Description Initialize a new bunfig configuration setup. ### Usage `bunfig init [options]` ### Options - **--config-dir** (string) - Optional - Configuration directory (default: ./config) - **--template** (string) - Optional - Template to use: basic|advanced|monorepo - **--typescript** (boolean) - Optional - Generate TypeScript configuration files - **--examples** (boolean) - Optional - Include example configurations ``` -------------------------------- ### bunfig Info Output Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Example output from the `bunfig info` command, detailing the configuration name, discovered files, resolution order (including primary, home, and package sources), type, and fields. ```bash Configuration: app ├── Name: app ├── Files Found: │ ├── ./config/app.config.ts (primary) │ ├── ~/.config/my-app/config.ts (home) │ └── package.json:app (package) ├── Resolution Order: │ 1. ./config/app.config.ts │ 2. ~/.config/my-app/config.ts │ 3. Environment variables (MY_APP_*) │ 4. Default configuration ├── Type: AppConfig └── Fields: port, host, features, database ``` -------------------------------- ### Merge Output Examples Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Examples of merged configuration output, including a version with source tracking. ```json { "port": 3000, "host": "localhost", "database": { "url": "postgresql://localhost:5432/myapp", "pool": 10 }, "features": ["auth", "logging"] } ``` ```json { "port": { "value": 3000, "source": "./config/app.config.ts" }, "host": { "value": "localhost", "source": "environment:MY_APP_HOST" }, "database": { "url": { "value": "postgresql://localhost:5432/myapp", "source": "./config/app.config.ts" }, "pool": { "value": 10, "source": "default" } } } ``` -------------------------------- ### Install bunfig Source: https://github.com/stacksjs/bunfig/blob/main/packages/bunfig/README.md Install the package using your preferred package manager. ```bash bun add bunfig ``` ```bash npm install bunfig ``` -------------------------------- ### Load and Test Server Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/web-server.md Use `config` to load test configurations and `Bun.serve` to start a test server. Ensure the server starts with a valid port and handles CORS requests correctly. ```typescript // server.test.ts import { afterAll, beforeAll, describe, expect, it } from 'bun:test' import { config } from 'bunfig' describe('Server Configuration', () => { let server: any beforeAll(async () => { // Load test configuration const testConfig = await config({ name: 'server', defaultConfig: { http: { port: 0, host: 'localhost' }, // Use random port cors: { enabled: true, origins: ['http://localhost:3000'] }, rateLimit: { enabled: false } } }) // Start test server server = Bun.serve({ port: testConfig.http.port, fetch: () => new Response('OK') }) }) afterAll(() => { server?.stop() }) it('should start server with configuration', () => { expect(server.port).toBeGreaterThan(0) }) it('should handle CORS requests', async () => { const response = await fetch(`http://localhost:${server.port}`, { method: 'OPTIONS', headers: { Origin: 'http://localhost:3000' } }) expect(response.headers.get('Access-Control-Allow-Origin')).toBe('http://localhost:3000') }) }) ``` -------------------------------- ### Configuration File Format Examples Source: https://github.com/stacksjs/bunfig/blob/main/docs/usage.md Illustrates the structure of configuration files in TypeScript, both locally and globally. ```APIDOC ## Configuration File Format Your configuration file can be in any of the supported formats. Here's an example using TypeScript: ```ts // my-app.config.ts (local) export default { port: 4000, host: 'localhost', features: { auth: true, api: true, }, } ``` Or in your home directory: ```ts // ~/.config/my-app/config.ts (global) export default { port: 8080, host: 'production.example.com', features: { auth: true, api: true, }, } ``` The configuration file's values will be deeply merged with your default configuration, with file values taking precedence. ``` -------------------------------- ### Dynamic Configuration Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/index.md Shows how to create configurations that adapt based on the environment, such as setting database URLs or enabling features dynamically using environment variables. ```typescript // config/dynamic.config.ts export default { // Configuration that changes based on environment database: { url: process.env.NODE_ENV === 'test' ? 'postgresql://localhost:5432/test' : process.env.DATABASE_URL, pool: process.env.NODE_ENV === 'production' ? 20 : 5 }, // Feature flags based on environment features: { enableMetrics: process.env.NODE_ENV === 'production', debugMode: process.env.NODE_ENV === 'development', betaFeatures: process.env.ENABLE_BETA === 'true' } } ``` -------------------------------- ### Example Sanitized Configuration File Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/troubleshooting.md An example of a configuration object, demonstrating how to redact sensitive information before sharing. ```typescript // Remove sensitive information before sharing export default { port: 3000, host: 'localhost', // database: 'REDACTED' } ``` -------------------------------- ### Home Directory Configuration Example Source: https://github.com/stacksjs/bunfig/blob/main/README.md Illustrates how to set up global configurations in the home directory using the XDG Base Directory specification. Project-specific configurations can override these global settings. ```typescript // ~/.config/my-app/config.ts (global configuration) export default { theme: 'dark', defaultPort: 8080, globalFeatures: ['feature1', 'feature2'], } // ./my-app.config.ts (project-specific override) export default { defaultPort: 3000, // Override global setting for this project projectSpecific: true, } ``` -------------------------------- ### Configuration Composition Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/index.md Demonstrates how to compose configurations by extending a base configuration with environment-specific settings. Useful for managing shared and environment-specific options. ```typescript // Base configuration that other configs extend // config/base.config.ts // Environment-specific configuration // config/production.config.ts import base from './base.config' export default { app: { name: 'MyApp', version: '1.0.0' }, logging: { level: 'info', enableConsole: true } } export default { ...base, logging: { ...base.logging, level: 'error', enableFile: true, file: '/var/log/app.log' }, database: { url: process.env.DATABASE_URL, pool: 20 } } ``` -------------------------------- ### Define Default Configuration Options Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/environment-variables.md Example of a default configuration object structure. ```ts const options = { name: 'my-app', defaultConfig: { port: 3000, host: 'localhost', database: { url: 'postgres://localhost:5432', user: 'admin', }, features: { logging: { enabled: true, level: 'info', }, }, }, } ``` -------------------------------- ### Basic bunfig Configuration Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/migration.md Demonstrates a simple configuration file using bunfig with default port and host settings. This configuration can be automatically loaded from common file locations. ```typescript // Any of these work automatically: // - myapp.config.ts // - .myapp.config.ts // - myapp.config.js // - package.json (with "myapp" field) // myapp.config.ts // app.ts import { config } from 'bunfig' export default { port: 3000, host: 'localhost' } const appConfig = await config({ name: 'myapp' }) ``` -------------------------------- ### Dockerfile for Bun Server Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/web-server.md Defines the Docker image for a Bun server, including installing dependencies, copying code, exposing ports, setting up health checks, and starting the server. ```dockerfile # Dockerfile FROM oven/bun:latest WORKDIR /app # Copy package files COPY package.json bun.lock ./ RUN bun install # Copy source code COPY . . # Create SSL directory (if using HTTPS) RUN mkdir -p ssl # Expose ports EXPOSE 3000 3443 # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 # Start server CMD ["bun", "run", "server.ts"] ``` -------------------------------- ### Define Environment Variables for Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/environment-variables.md Environment variables mapped to the example configuration structure. ```bash # Top-level properties MY_APP_PORT=8080 MY_APP_HOST=example.com # Nested properties MY_APP_DATABASE_URL=postgres://production:5432 MY_APP_DATABASE_USER=prod_user MY_APP_FEATURES_LOGGING_ENABLED=false MY_APP_FEATURES_LOGGING_LEVEL=error ``` -------------------------------- ### Install bunfig Source: https://github.com/stacksjs/bunfig/blob/main/docs/migration.md Commands to remove old configuration dependencies and install bunfig using the bun package manager. ```bash # Remove old dependencies bun remove dotenv config rc cosmiconfig # Install bunfig bun add bunfig ``` -------------------------------- ### Feature-Based Configuration Examples Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/index.md Illustrates how to structure configurations for different features, such as authentication and caching. Each feature can have its own enabled status and specific settings. ```typescript // config/features/auth.config.ts export default { enabled: true, providers: ['google', 'github'], jwt: { secret: process.env.JWT_SECRET, expiry: '24h' }, session: { cookieName: 'session', secure: true, httpOnly: true } } ``` ```typescript // config/features/cache.config.ts export default { enabled: true, provider: 'redis', ttl: 3600, redis: { url: process.env.REDIS_URL, db: 0 } } ``` -------------------------------- ### Basic Configuration Loading Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/configuration-loading.md Standard usage examples for loading configuration objects and retrieving detailed results including metrics. ```ts // Import both functions from bunfig import { loadConfig, loadConfigWithResult } from 'bunfig' // Standard usage - returns just the config const config = await loadConfig({ name: 'app', defaultConfig: { port: 3000, host: 'localhost' } }) const result = await loadConfigWithResult({ name: 'app', defaultConfig: { port: 3000 }, cache: { enabled: true }, performance: { enabled: true } }) console.log(result.config) // Loaded configuration console.log(result.source) // Source information console.log(result.metrics) // Performance metrics ``` -------------------------------- ### Package.json Configuration Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md This JSON structure shows how to define configuration within the package.json file for a specific application name. ```json { "my-app": { "port": 4000, "host": "example.com" } } ``` -------------------------------- ### Bunfig Dynamic Configuration Example (JavaScript) Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/typescript-plugin.md For dynamic configurations, the plugin infers the return type of the default export. This example shows a configuration object with properties derived from environment variables. ```javascript // config/dynamic.ts export default { port: Number(process.env.PORT) || 3000, host: process.env.HOST || 'localhost', debug: process.env.NODE_ENV === 'development', } // Plugin extracts: { port: number; host: string; debug: boolean } ``` -------------------------------- ### Install bunfig with Bun Source: https://github.com/stacksjs/bunfig/blob/main/docs/install.md Use these commands to add bunfig as a development dependency in a Bun project. ```sh bun install --dev bunfig # bun add --dev bunfig # bun i -d bunfig ``` -------------------------------- ### Sensible Defaults for Development Server Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/home-directory.md This example demonstrates using home directory configuration to set sensible default values for a development server, such as preferred port, host, and HTTPS settings. ```typescript // ~/.config/dev-server/config.ts export default { port: 4000, // Your preferred default port host: '0.0.0.0', // Allow external connections https: false, // Your security preference } ``` -------------------------------- ### Install Bunfig with Bun Source: https://github.com/stacksjs/bunfig/blob/main/README.md Use this command to add bunfig to your project dependencies. ```bash bun add bunfig ``` -------------------------------- ### Docker Multi-Environment Setup Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/environments.md Dockerfile and docker-compose configuration for managing development, staging, and production environments. ```dockerfile # Dockerfile FROM oven/bun:latest WORKDIR /app # Copy package files COPY package.json bun.lock ./ RUN bun install # Copy source code COPY . . # Set default environment ENV NODE_ENV=production # Build application RUN bun run build # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:${PORT:-3000}/health || exit 1 # Start application CMD ["bun", "run", "start"] ``` ```yaml # docker-compose.yml version: '3.8' services: app-dev: build: . environment: - NODE_ENV=development env_file: - .env.development ports: - '3000:3000' volumes: - .:/app - /app/node_modules app-staging: build: . environment: - NODE_ENV=staging env_file: - .env.staging ports: - '3001:3000' app-prod: build: . environment: - NODE_ENV=production env_file: - .env.production ports: - '3002:3000' restart: unless-stopped ``` -------------------------------- ### Install bunfig Globally Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Install bunfig globally using your preferred package manager (Bun, npm, yarn, pnpm) to access its CLI commands. ```bash bun install -g bunfig ``` ```bash npm install -g bunfig ``` ```bash yarn global add bunfig ``` ```bash pnpm install -g bunfig ``` -------------------------------- ### Environment Variable Mapping Example Source: https://github.com/stacksjs/bunfig/blob/main/README.md Demonstrates how nested configuration properties map to environment variable keys. ```ts // With a config name of "my-app" const options = { name: 'my-app', defaultConfig: { port: 3000, host: 'localhost', database: { url: 'postgres://localhost:5432', user: 'admin', }, }, } // These environment variables would be automatically used if set: // MY_APP_PORT=8080 // MY_APP_HOST=example.com // MY_APP_DATABASE_URL=postgres://production:5432 // MY_APP_DATABASE_USER=prod_user ``` -------------------------------- ### CI/CD Integration Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Example GitHub Actions workflow for validating configurations in CI. ```yaml # .github/workflows/config-validation.yml name: Validate Configurations on: [push, pull_request] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: oven-sh/setup-bun@v1 - run: bun install - run: bunx bunfig validate --strict - run: bunx bunfig doctor ``` -------------------------------- ### Get Environment Information Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/troubleshooting.md Displays version information for Bun, Node.js, and checks for Bunfig in package.json. ```bash bun --version node --version cat package.json | grep bunfig ``` -------------------------------- ### Define local configuration file Source: https://github.com/stacksjs/bunfig/blob/main/docs/usage.md Example of a local configuration file using TypeScript. ```ts // my-app.config.ts (local) export default { port: 4000, host: 'localhost', features: { auth: true, api: true, }, } ``` -------------------------------- ### Automate Migration with Shell Script Source: https://github.com/stacksjs/bunfig/blob/main/docs/migration.md Use a shell script to automate the installation of Bunfig and the conversion of existing configuration files. ```bash #!/bin/bash # migrate-to-bunfig.sh echo "🔄 Migrating to bunfig..." # Backup existing configuration mkdir -p migration-backup cp -r config migration-backup/ 2>/dev/null || true cp .env* migration-backup/ 2>/dev/null || true # Install bunfig echo "📦 Installing bunfig..." bun add bunfig # Convert .env to config file if [ -f .env ]; then echo "🔧 Converting .env to app.config.ts..." node migration-scripts/convert-env.js fi # Convert rc files for file in .*rc; do if [ -f "$file" ]; then echo "🔧 Converting $file..." node migration-scripts/convert-rc.js "$file" fi done echo "✅ Migration complete! Check your new configuration files." echo "🧪 Run tests to verify the migration." ``` -------------------------------- ### Merged Configuration Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/home-directory.md Illustrates the final merged configuration object after applying both home directory and local project configurations. Local settings override home settings where conflicts exist. ```typescript { theme: 'dark' // From home config defaultPort: 3000 globalFeatures: ['feature1', 'feature2'] // From home config userPreferences: { notifications: true // From home config autoSave: false // From local config (overridden) } projectSpecific: true // From local config (added) } ``` -------------------------------- ### Multi-Environment Configuration Setup Source: https://github.com/stacksjs/bunfig/blob/main/docs/index.md Define different configuration objects for development and production environments. Load the appropriate configuration based on the NODE_ENV environment variable. ```typescript // config/development.config.ts export default { database: { url: 'postgresql://localhost:5432/dev' }, logging: { level: 'debug' } } // config/production.config.ts export default { database: { url: process.env.DATABASE_URL }, logging: { level: 'error' } } // Load environment-specific config const env = process.env.NODE_ENV || 'development' const config = await loadConfig({ name: env, cwd: './config' }) ``` -------------------------------- ### TypeScript Configuration File Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/type-safety.md Best practice: Define your configuration directly in TypeScript files (e.g., `my-app.config.ts`). This allows TypeScript to check the configuration against your defined interfaces. ```typescript // my-app.config.ts import type { MyConfig } from './types' const config: MyConfig = { // TypeScript checks this matches MyConfig } export default config ``` -------------------------------- ### Global TypeScript Configuration File Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md Example of a global TypeScript configuration file (`~/.config/my-app/config.ts`) for settings that apply across projects. ```typescript // ~/.config/my-app/config.ts (global) export default { port: 8080, host: 'production.example.com', } ``` -------------------------------- ### Web Server Configuration Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/index.md Define web server specific configurations like port, host, CORS settings, and rate limiting. Environment variables can override these settings. ```typescript // server.config.ts export default { http: { port: 3000, host: 'localhost' }, cors: { enabled: true, origins: ['http://localhost:3000'] }, rateLimit: { enabled: true, maxRequests: 100 } } // Automatically uses environment variables: // SERVER_HTTP_PORT=8080 // SERVER_CORS_ORIGINS=https://myapp.com,https://api.myapp.com ``` -------------------------------- ### Home Directory Global Configuration Example Source: https://context7.com/stacksjs/bunfig/llms.txt Set global configuration defaults in `~/.config//config.ts`. Project-specific configuration files (e.g., `./my-app.config.ts`) can override these global settings. ```typescript // ~/.config/my-app/config.ts export default { // Global defaults for all projects theme: 'dark', editor: { tabSize: 2, formatOnSave: true, }, telemetry: false, } // Project-specific override: ./my-app.config.ts export default { // Override global settings for this project theme: 'light', projectSpecific: { buildDir: './dist', }, } ``` -------------------------------- ### Environment Variable Patterns Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/index.md Provides examples of environment variable naming conventions for server, database, and authentication configurations. This aids in managing sensitive information and environment-specific settings. ```bash # Server configuration SERVER_PORT=8080 SERVER_HOST=0.0.0.0 SERVER_CORS_ENABLED=true # Database configuration DATABASE_URL=postgresql://localhost:5432/myapp DATABASE_POOL=10 DATABASE_SSL=true # Authentication configuration AUTH_JWT_SECRET=your-secret-key AUTH_JWT_EXPIRY=24h AUTH_PROVIDERS=google,github ``` -------------------------------- ### Get Bunfig Version Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/troubleshooting.md Prints the installed version of Bunfig to the console. ```bash bunfig --version ``` -------------------------------- ### Create and Use Custom Templates Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Sets up a custom template directory and initializes a project using it. ```bash # Create template directory mkdir -p ~/.bunfig/templates/my-template # Add template files cat > ~/.bunfig/templates/my-template/app.config.ts << 'EOF' export default { name: '{{PROJECT_NAME}}', version: '{{VERSION}}', port: 3000, } EOF # Use custom template bunfig init --template my-template ``` -------------------------------- ### Install Bunfig Plugin in Bun Build Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/build-plugin.md Integrate the bunfigPlugin into your Bun build process by adding it to the plugins array. Specify the directory containing your configuration files using the `configDir` option. ```typescript import { bunfigPlugin } from 'bunfig' await Bun.build({ entrypoints: ['src/index.ts'], outdir: './dist', target: 'bun', plugins: [ bunfigPlugin({ configDir: './config', }), ], }) ``` -------------------------------- ### Validation Error Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/quick-start.md Example of the error output when configuration validation fails. ```typescript // If port is invalid (e.g., -1) // ValidationError: Validation failed // ❌ port: must be >= 1 ``` -------------------------------- ### Global Preferences for CLI Tools Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/home-directory.md Example of a home directory configuration file for a command-line interface (CLI) tool. It defines global preferences like output format, logging verbosity, and preferred editor. ```typescript // ~/.config/my-cli/config.ts export default { outputFormat: 'json', verboseLogging: false, colorOutput: true, editor: 'vscode', } ``` -------------------------------- ### Demonstrate Configuration Priority Flow Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/environment-variables.md Shows how defaults, environment variables, and config files interact to produce a final configuration. ```ts // 1. Default configuration in code const defaultConfig = { port: 3000, debug: false, api: { url: 'https://api.example.com', timeout: 5000, }, } // 2. Environment variables can override defaults // MY_APP_PORT=8080 // MY_APP_API_URL=https://staging-api.example.com // 3. Config file has highest priority (my-app.config.ts) export default { debug: true, api: { timeout: 10000, }, } // Final resolved configuration: // { // port: 8080, // From environment variable // debug: true, // From config file // api: { // url: 'https://staging-api.example.com', // From environment variable // timeout: 10000, // From config file // }, // } ``` -------------------------------- ### Create bunfig Configuration Files Source: https://github.com/stacksjs/bunfig/blob/main/docs/migration.md Demonstrates how to create new configuration files for bunfig, either a single main file or organized by feature into separate files. ```bash # Create your first config file touch app.config.ts # Or organize by feature mkdir config touch config/server.config.ts touch config/database.config.ts ``` -------------------------------- ### bunfig Validation Schema Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/migration.md Provides an example of defining a JSON schema within the bunfig configuration to enforce data types and constraints for application settings. ```typescript const appConfig = await config({ name: 'app', schema: { type: 'object', properties: { server: { type: 'object', properties: { port: { type: 'number', minimum: 1, maximum: 65535 } }, required: ['port'] } } } }) ``` -------------------------------- ### Create Global Configuration Directory Source: https://github.com/stacksjs/bunfig/blob/main/docs/quick-start.md Initialize the directory for global bunfig settings. ```bash mkdir -p ~/.config/bunfig ``` -------------------------------- ### Environment Variable Mapping Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/index.md bunfig intelligently maps environment variables to nested configuration properties. For example, `APP_DATABASE_POOL_SIZE` is converted to a number and assigned to `config.database.pool.size`. ```bash # Set an environment variable export APP_DATABASE_POOL_SIZE=20 # bunfig automatically maps it to config.database.pool.size = 20 // (as a number!) ``` -------------------------------- ### Run Application Source: https://github.com/stacksjs/bunfig/blob/main/docs/quick-start.md Execute your application using the Bun runtime. ```bash bun run server.ts ``` -------------------------------- ### Environment Configuration (.env.development) Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/web-server.md Sets up development environment variables for the server, including port, host, CORS, and logging settings. ```bash # .env.development SERVER_HTTP_PORT=3000 SERVER_HTTP_HOST=localhost SERVER_CORS_ENABLED=true SERVER_CORS_ORIGINS=http://localhost:3000,http://localhost:3001 SERVER_LOGGING_REQUESTS=true SERVER_LOGGING_LEVEL=debug ``` -------------------------------- ### bunfig Doctor Output Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Example output from the `bunfig doctor` command, listing diagnosed issues such as duplicate files, missing type annotations, and naming inconsistencies, along with recommendations and the possibility of automatic fixes. ```bash 🔍 Diagnosing bunfig configuration... Issues Found: ❌ Duplicate configuration files - app.config.ts and app.ts both exist - Recommendation: Remove app.ts to avoid conflicts ⚠️ Missing type annotations - database.config.ts lacks explicit types - Recommendation: Add interface definitions ⚠️ Inconsistent naming - Found both camelCase and kebab-case config names - Recommendation: Use consistent naming convention ✅ All other checks passed Run with --fix to automatically resolve fixable issues. ``` -------------------------------- ### Initialize Bunfig Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Use the init command to scaffold a new configuration directory with optional templates and TypeScript support. ```bash bunfig init [options] Options: --config-dir Configuration directory (default: ./config) --template Template to use: basic|advanced|monorepo --typescript Generate TypeScript configuration files --examples Include example configurations Examples: bunfig init bunfig init --template advanced bunfig init --config-dir ./settings --typescript bunfig init --examples ``` -------------------------------- ### Implement Real-World Application Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/browser-support.md Demonstrates advanced patterns including environment-based endpoints, internal caching, and runtime configuration refreshing. ```ts // app.ts import { isBrowser, loadConfig } from 'bunfig/browser' // Configuration type with environment support interface EnvironmentConfig { production: boolean apiUrl: string features: string[] } class App { private config: EnvironmentConfig private configCache = new Map() async initialize() { this.config = await this.loadEnvironmentConfig() await this.setupServices() } private async loadEnvironmentConfig(): Promise { // Get environment from build time or environment variable const env = process.env.NODE_ENV || 'development' const cacheKey = `config:${env}` // Check cache first if (this.configCache.has(cacheKey)) return this.configCache.get(cacheKey) // Load configuration based on environment const config = await loadConfig({ name: 'app', // Load from different endpoints based on environment endpoint: `/api/config/${env}`, defaultConfig: { production: env === 'production', apiUrl: 'http://localhost:3000', features: [], }, headers: { // Add environment-specific headers 'X-Environment': env, 'X-Client-Version': APP_VERSION, }, }) // Cache the configuration this.configCache.set(cacheKey, config) return config } private async setupServices() { if (this.config.production) { // Setup production services await this.setupAnalytics() await this.setupErrorReporting() } // Setup API client await this.setupAPIClient(this.config.apiUrl) // Enable features this.config.features.forEach((feature) => { this.enableFeature(feature) }) } // Example of runtime configuration updates public async refreshConfig() { // Clear cache this.configCache.clear() // Reload configuration this.config = await this.loadEnvironmentConfig() // Re-initialize services with new config await this.setupServices() // Emit configuration change event this.emit('configUpdated', this.config) } } // Initialize application const app = new App() app.initialize().catch((error) => { console.error('Failed to initialize app:', error) }) ``` -------------------------------- ### Load configuration with bunfig Source: https://github.com/stacksjs/bunfig/blob/main/docs/usage.md Demonstrates basic configuration loading using the config function with names, explicit options, and aliases. ```typescript import { config } from 'bunfig' interface MyConfig { port: number host: string } // Load config using a name const myConfig = await config('my-app') // Or with explicit options const myConfig = await config({ name: 'my-app', defaultConfig: { port: 3000, host: 'localhost', }, }) // Using an alias for alternative config file names const myConfig = await config({ name: 'my-app', alias: 'app', defaultConfig: { port: 3000, host: 'localhost', }, }) ``` -------------------------------- ### CLI Command: list Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Lists all discovered configuration files in the project. ```APIDOC ## CLI Command: list ### Description List all discovered configuration files. ### Usage `bunfig list [options]` ### Options - **--config-dir** (string) - Optional - Configuration directory (default: ./config) - **--format** (string) - Optional - Output format: text|json|yaml (default: text) - **--show-path** (boolean) - Optional - Show full file paths - **--show-types** (boolean) - Optional - Show type information ``` -------------------------------- ### Local TypeScript Configuration File Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md Example of a local TypeScript configuration file (`my-app.config.ts`) used for project-specific settings. ```typescript // my-app.config.ts (local) export default { port: 3000, host: 'localhost', } ``` -------------------------------- ### Run bunfig Directly with bunx Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Execute bunfig commands directly without global installation using `bunx`. ```bash bunx bunfig --help ``` -------------------------------- ### List Configuration Files Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md List discovered configuration files with options to format output or show paths and types. ```bash bunfig list [options] Options: --config-dir Configuration directory (default: ./config) --format Output format: text|json|yaml (default: text) --show-path Show full file paths --show-types Show type information Examples: bunfig list bunfig list --show-path --format json bunfig list --show-types ``` -------------------------------- ### Load and Use Application Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/index.md Import and load the application configuration using bunfig. Destructure the port and host properties from the loaded configuration. ```typescript import { config } from 'bunfig' const { port, host } = await config({ name: 'app' }) ``` -------------------------------- ### Handle Multiple Configuration Directories Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/build-plugin.md Uses multiple plugin instances to manage configurations from different directories. ```ts // build.ts import { bunfigPlugin } from 'bunfig' // Multiple plugins for different config directories const plugins = [ bunfigPlugin({ configDir: './config/app', virtualModuleName: 'virtual:app-configs', }), bunfigPlugin({ configDir: './config/features', virtualModuleName: 'virtual:feature-configs', }), ] await Bun.build({ entrypoints: ['src/index.ts'], outdir: './dist', target: 'bun', plugins, }) ``` -------------------------------- ### Loading Configuration with `loadConfig` Source: https://github.com/stacksjs/bunfig/blob/main/docs/usage.md Demonstrates how to load configuration using the `loadConfig` function, specifying the configuration name and providing default values. ```APIDOC ## `loadConfig`(options) Low-level configuration loader with more options. Options: - `name`: The name of your configuration - `alias`: An alternative name to check for config files (optional) - `cwd?`: Working directory to search for config files (defaults to process.cwd()) - `defaultConfig`: Default configuration values ### Request Example ```ts import type { ConfigOf } from 'bunfig' import { loadConfig } from 'bunfig' const cfg = await loadConfig>({ name: 'app', defaultConfig: { /* ... defaults ... */ } as ConfigOf<'app'>, }) ``` ### Response #### Success Response (200) - `T` (object) - The loaded configuration object. #### Response Example ```json { "port": 4000, "host": "localhost", "features": { "auth": true, "api": true } } ``` ``` -------------------------------- ### Managing Gradual Deprecation Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/aliases.md Follow a phased approach to rename configurations, starting with alias support and ending with the removal of the legacy name. ```ts // Phase 1: Introduce new name with alias support const config = await loadConfig({ name: 'new-name', alias: 'old-name', defaultConfig: { /* ... */ }, }) // Phase 2: Warn about deprecated usage const config = await loadConfig({ name: 'new-name', alias: 'old-name', defaultConfig: { /* ... */ }, }) // Add deprecation warning if old-name config is found // Phase 3: Remove alias support const config = await loadConfig({ name: 'new-name', // alias removed defaultConfig: { /* ... */ }, }) ``` -------------------------------- ### Optimize Configuration Bundles with Bun Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/build-plugin.md Optimize configuration bundles using Bun.build with the bunfigPlugin, enabling code splitting for efficient module loading. ```typescript // build.ts await Bun.build({ entrypoints: ['src/index.ts'], outdir: './dist', target: 'bun', plugins: [bunfigPlugin({ configDir: './config' })], splitting: true, // Enable code splitting format: 'esm', }) ``` -------------------------------- ### Create a Configuration File Source: https://github.com/stacksjs/bunfig/blob/main/docs/index.md Create a TypeScript configuration file for your application, defining properties like port and host. ```typescript // app.config.ts export default { port: 3000, host: 'localhost' } ``` -------------------------------- ### Get Bunfig Info on Configuration Resolution Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/troubleshooting.md Retrieves detailed information about how a specific configuration is resolved, including search paths and content. ```bash bunfig info app --show-content --show-types ``` -------------------------------- ### Run Tests with Bun Source: https://github.com/stacksjs/bunfig/blob/main/docs/intro.md Execute the test suite using the Bun runtime. ```bash bun test ``` -------------------------------- ### Configure CORS Headers for Configuration API Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/troubleshooting.md Example of how to configure CORS headers on an API endpoint to allow cross-origin requests for configuration data. ```typescript // Configure CORS headers on your API endpoint app.get('/api/config/:name', (req, res) => { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Headers', 'Content-Type') // ... return configuration }) // Or use browser config with proper endpoint const config = await loadConfig({ name: 'app', endpoint: '/api/config', // Same-origin request defaultConfig: {}, }) ``` -------------------------------- ### bunfig Validation Output Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/cli.md Example output from the `bunfig validate` command, indicating the status of each configuration file and a summary of valid and errored files. ```bash ✅ app.config.ts - Valid ✅ database.config.ts - Valid ❌ auth.config.ts - Error: Missing required field 'secret' ❌ logging.config.ts - Error: Invalid type for 'level' (expected string, got number) Summary: 2 valid, 2 errors ``` -------------------------------- ### ConfigNames Type Example Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md Illustrates the `ConfigNames` type, which resolves to a string-literal union of configuration names when the build plugin is active, or `string` otherwise. ```typescript // With plugin: type could be 'app' | 'auth' | 'database' // Without plugin: type is string ``` -------------------------------- ### Minimal Reproduction Case for Bunfig Issue Source: https://github.com/stacksjs/bunfig/blob/main/docs/advanced/troubleshooting.md A minimal code example to reproduce an issue with Bunfig's loadConfig function. Useful for reporting bugs. ```typescript // Simplest possible code that reproduces the issue import { loadConfig } from 'bunfig' const config = await loadConfig({ name: 'test', defaultConfig: {}, }) ``` -------------------------------- ### Initialize Application with Typed Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/quick-start.md Load and validate configuration using the bunfig library with TypeScript interfaces and JSON schemas. ```ts // app.ts import { config } from 'bunfig' interface AppConfig { server: { port: number host: string cors: { enabled: boolean origins: string[] } } database: { url: string pool: number ssl: boolean } redis: { url: string db: number } auth: { jwtSecret: string tokenExpiry: string } features: { enableMetrics: boolean enableCaching: boolean debugMode: boolean } } const appConfig = await config({ name: 'app', // Provide sensible defaults defaultConfig: { server: { port: 3000, host: 'localhost', cors: { enabled: false, origins: [] } }, database: { url: 'postgresql://localhost:5432/defaultdb', pool: 5, ssl: false }, redis: { url: 'redis://localhost:6379', db: 0 }, auth: { jwtSecret: 'dev-secret', tokenExpiry: '1h' }, features: { enableMetrics: false, enableCaching: false, debugMode: true } }, // Add validation schema: { type: 'object', properties: { server: { type: 'object', properties: { port: { type: 'number', minimum: 1, maximum: 65535 }, host: { type: 'string', minLength: 1 } }, required: ['port', 'host'] }, database: { type: 'object', properties: { url: { type: 'string', pattern: '^postgresql://' }, pool: { type: 'number', minimum: 1, maximum: 50 } }, required: ['url'] }, auth: { type: 'object', properties: { jwtSecret: { type: 'string', minLength: 10 }, tokenExpiry: { type: 'string', pattern: '^\\d+[hmd]$' } }, required: ['jwtSecret'] } }, required: ['server', 'database', 'auth'] } }) // Initialize services with configuration const server = Bun.serve({ port: appConfig.server.port, hostname: appConfig.server.host, async fetch(req) { // Use configuration throughout your app if (appConfig.features.debugMode) { console.log(`Request: ${req.method} ${req.url}`) } return new Response('Hello World!') } }) console.log(`🚀 Server running at http://${server.hostname}:${server.port}`) console.log(`📊 Metrics enabled: ${appConfig.features.enableMetrics}`) console.log(`🗄️ Caching enabled: ${appConfig.features.enableCaching}`) ``` -------------------------------- ### Project-Specific Local Configuration Override Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md Example of a local configuration file (`./my-tool.config.ts`) that overrides global settings for a specific project. This allows for project-specific adjustments. ```typescript // ./my-tool.config.ts - overrides global settings for this project export default { defaultTheme: 'light', // Override global setting projectSpecific: true, } ``` -------------------------------- ### Load Configuration with Aliases Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/configuration-loading.md Demonstrates loading configuration with an alias. bunfig checks for both the primary name and the alias name in configuration files. ```typescript const config = await loadConfig({ name: 'tlsx', alias: 'tls', defaultConfig: { domain: 'example.com', port: 443, }, }) ``` -------------------------------- ### Explicitly Reference Fallback Types Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md Shows how to explicitly reference bunfig's fallback types in your TypeScript setup using a triple-slash directive or tsconfig.json. ```typescript /// ``` -------------------------------- ### Documenting Migration Paths Source: https://github.com/stacksjs/bunfig/blob/main/docs/features/aliases.md Use aliases to maintain backward compatibility during configuration transitions. Support for legacy names should be clearly documented with removal timelines. ```ts /** * Configuration loader with backward compatibility. * * Migration path: 'legacy-config' → 'modern-config' * Support for 'legacy-config' will be removed in v3.0 */ const config = await loadConfig({ name: 'modern-config', alias: 'legacy-config', defaultConfig: { /* ... */ }, }) ``` -------------------------------- ### Configuration Validation Schemas Source: https://github.com/stacksjs/bunfig/blob/main/docs/recipes/index.md Provides example JSON schemas for validating server and database configurations. Ensures that configuration values meet specified types and constraints. ```typescript // Common validation schemas export const serverSchema = { type: 'object', properties: { port: { type: 'number', minimum: 1, maximum: 65535 }, host: { type: 'string', minLength: 1 }, cors: { type: 'object', properties: { enabled: { type: 'boolean' }, origins: { type: 'array', items: { type: 'string' } } } } }, required: ['port', 'host'] } export const databaseSchema = { type: 'object', properties: { url: { type: 'string', pattern: '^(postgresql|mysql|sqlite)://' }, pool: { type: 'number', minimum: 1, maximum: 100 }, ssl: { type: 'boolean' }, timeout: { type: 'number', minimum: 0 } }, required: ['url'] } ``` -------------------------------- ### Global Home Directory Configuration Source: https://github.com/stacksjs/bunfig/blob/main/docs/api.md Example of a global configuration file located in the home directory (`~/.config/my-tool/config.ts`) for settings that apply across all projects using 'my-tool'. ```typescript // ~/.config/my-tool/config.ts - applies to all projects using 'my-tool' export default { globalSettings: true, defaultTheme: 'dark', } ```