### Basic Setup Example for Browser Configuration Source: https://bunfig.netlify.app/advanced/browser-support A complete example demonstrating how to define a configuration interface, load it from an API endpoint using `loadConfig` in the browser, and apply it to the DOM. ```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}`) ``` -------------------------------- ### Bunfig Build Plugin Installation and Usage Source: https://bunfig.netlify.app/advanced/build-plugin This snippet demonstrates how to install and configure the bunfigPlugin within your Bun build process. It shows the basic setup for integrating the plugin and specifies the configuration directory. ```APIDOC ## Bunfig Build Plugin Installation ### Description This section shows how to integrate the `bunfigPlugin` into your Bun build process. ### Method `Bun.build` with `plugins` option ### Endpoint N/A (Build process integration) ### Parameters #### Plugin Options - **configDir** (string) - Optional - Directory to scan for configuration files. Defaults to './config'. - **extensions** (string[]) - Optional - File extensions to include. Defaults to ['.ts', '.js', '.mjs', '.cjs', '.json']. - **exclude** (string[]) - Optional - Patterns to exclude from scanning. Defaults to ['**/*.test.*', '**/*.spec.*', '**/node_modules/**']. - **virtualModuleName** (string) - Optional - Custom virtual module name. Defaults to 'virtual:bunfig-types'. - **generateTypes** (boolean) - Optional - Generate physical type files alongside virtual modules. Defaults to `false`. - **typesOutputDir** (string) - Optional - Output directory for generated type files. Defaults to './src/generated'. ### Request Example ```typescript // build.ts import { bunfigPlugin } from 'bunfig' await Bun.build({ entrypoints: ['src/index.ts'], outdir: './dist', target: 'bun', plugins: [ bunfigPlugin({ configDir: './config', }), ], }) ``` ### Response N/A (Build process output) ### Default Configuration ```typescript const defaultConfig = { configDir: './config', extensions: ['.ts', '.js', '.mjs', '.cjs', '.json'], exclude: ['**/*.test.*', '**/*.spec.*', '**/node_modules/**'], virtualModuleName: 'virtual:bunfig-types', generateTypes: false, typesOutputDir: './src/generated' } ``` ``` -------------------------------- ### Full Web Application Configuration Example Source: https://bunfig.netlify.app/quick-start A comprehensive example demonstrating how to configure a full web application using Bunfig, including server, database, Redis, authentication, and feature flags. This example also includes schema validation and default configurations. ```typescript // config/app.config.ts export default { server: { port: 3000, host: 'localhost', cors: { enabled: true, origins: ['http://localhost:3000'] } }, database: { url: 'postgresql://localhost:5432/myapp', pool: 10, ssl: false }, redis: { url: 'redis://localhost:6379', db: 0 }, auth: { jwtSecret: 'your-secret-key', tokenExpiry: '24h' }, features: { enableMetrics: true, enableCaching: true, debugMode: false } } ``` ```typescript // 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}`) ``` -------------------------------- ### Installation Source: https://bunfig.netlify.app/advanced/cli Instructions on how to install the bunfig CLI globally using different package managers or directly via bunx. ```APIDOC ## Installation Install bunfig globally to use the CLI: ```bash # Using Bun bun install -g bunfig # Using npm npm install -g bunfig # Using yarn yarn global add bunfig # Using pnpm pnpm install -g bunfig ``` Or run directly with `bunx`: ```bash bunx bunfig --help ``` ``` -------------------------------- ### Initialize Configuration (`init`) Source: https://bunfig.netlify.app/advanced/cli Initializes a new Bunfig configuration setup. You can specify options like the configuration directory, template, and whether to use TypeScript or include examples. ```APIDOC ## `init` Initialize a new bunfig configuration setup. ### Usage 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 ```bash bunfig init bunfig init --template advanced bunfig init --config-dir ./settings --typescript bunfig init --examples ``` ### Init Templates **Basic Template:** ``` config/ ├── app.config.ts └── database.config.ts ``` **Advanced Template:** ``` config/ ├── app.config.ts ├── database.config.ts ├── auth.config.ts ├── logging.config.ts ├── features/ │ ├── payments.config.ts │ └── notifications.config.ts └── environments/ ├── development.config.ts ├── production.config.ts └── test.config.ts ``` ``` -------------------------------- ### Bunfig List Output Example Source: https://bunfig.netlify.app/advanced/cli This example shows the default text output format for 'bunfig list', displaying configuration names and their corresponding file paths. ```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 ``` -------------------------------- ### Install bunfig CLI Source: https://bunfig.netlify.app/advanced/cli Global installation commands for various package managers. ```bash # Using Bun bun install -g bunfig # Using npm npm install -g bunfig # Using yarn yarn global add bunfig # Using pnpm pnpm install -g bunfig ``` -------------------------------- ### Complete Integration Example Source: https://bunfig.netlify.app/advanced/browser-support Demonstrates a typed configuration loader with environment-aware strategies and error handling. ```typescript import type { Config } from 'bunfig' // config/browser.ts import { isBrowser, loadConfig } from 'bunfig/browser' // Define your configuration interface interface AppConfig { api: { url: string timeout: number } ui: { theme: 'light' | 'dark' animations: boolean } features: { [key: string]: boolean } } // Create a typed configuration loader async function loadAppConfig(): Promise { // Default configuration const defaults: AppConfig = { api: { url: 'https://api.example.com', timeout: 5000, }, ui: { theme: 'light', animations: true, }, features: { newDashboard: false, betaFeatures: false, }, } // Different loading strategies for browser/node if (isBrowser()) { return await loadConfig({ name: 'my-app', endpoint: '/api/config', defaultConfig: defaults, // Add custom headers if needed headers: { Authorization: `Bearer ${getAuthToken()}`, }, }) } // Fallback for non-browser environments return defaults } // Example usage with error handling async function initializeApp() { try { const config = await loadAppConfig() // Apply configuration setupAPI(config.api) applyTheme(config.ui.theme) toggleFeatures(config.features) return config } catch (error) { console.error('Failed to load configuration:', error) // Handle error appropriately } } // Helper functions function setupAPI({ url, timeout }: AppConfig['api']) { // Configure API client axios.defaults.baseURL = url axios.defaults.timeout = timeout } function applyTheme(theme: AppConfig['ui']['theme']) { document.documentElement.setAttribute('data-theme', theme) } function toggleFeatures(features: AppConfig['features']) { Object.entries(features).forEach(([feature, enabled]) => { if (enabled) enableFeature(feature) else disableFeature(feature) }) } ``` -------------------------------- ### Configuration File Discovery Structure Source: https://bunfig.netlify.app/advanced/build-plugin Example directory structure showing how the plugin discovers and processes configuration files. ```text config/ ├── app.ts # → ConfigNames includes 'app' ├── database.config.ts # → ConfigNames includes 'database' ├── auth.mjs # → ConfigNames includes 'auth' ├── logging.json # → ConfigNames includes 'logging' ├── features/ │ ├── payments.ts # → ConfigNames includes 'payments' │ └── notifications.ts # → ConfigNames includes 'notifications' └── _internal.ts # → ignored (underscore prefix) ``` -------------------------------- ### Example Directory Structure for Custom Configuration Source: https://bunfig.netlify.app/features/multiple-formats Shows a typical file structure when using a custom configuration directory. ```plaintext settings/ ├── my-app.ts ├── my-app.config.ts └── other-configs.ts ``` -------------------------------- ### Installation and Configuration Source: https://bunfig.netlify.app/advanced/typescript-plugin Instructions on how to add the bunfig TypeScript plugin to your tsconfig.json and configure its options. ```APIDOC ## Installation Add the plugin to your `tsconfig.json`: ```json { "compilerOptions": { "types": ["bunfig"] }, "plugins": [ { "name": "bunfig/ts-plugin", "configDir": "./config" } ] } ``` ### Plugin Options Option| Type| Default| Description ---|---|---|--- `configDir`| `string`| `"./config"`| Directory to scan for configuration files `extensions`| `string[]`| `[".ts", ".js", ".mjs", ".cjs", ".json"]`| File extensions to include `exclude`| `string[]`| `[]`| Patterns to exclude from scanning ``` -------------------------------- ### Install bunfig as a dev dependency Source: https://bunfig.netlify.app/install Use this command to install bunfig for development. It is recommended to install it as a dev dependency. ```bash bun install --dev bunfig ``` ```bash # bun add --dev bunfig ``` ```bash # bun i -d bunfig ``` -------------------------------- ### Define Local and Global Configuration Files Source: https://bunfig.netlify.app/api Examples of configuration files for local project overrides and global home directory settings. ```typescript // my-app.config.ts (local) export default { port: 3000, host: 'localhost', } // ~/.config/my-app/config.ts (global) export default { port: 8080, host: 'production.example.com', } ``` -------------------------------- ### Real-World Application Example Source: https://bunfig.netlify.app/advanced/browser-support Shows an object-oriented approach to configuration management, including caching and runtime refreshes. ```typescript // 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) }) ``` -------------------------------- ### Home Directory Alias Structure Source: https://bunfig.netlify.app/features/aliases Example file structure for primary and alias configurations within the home directory. ```bash # Primary configuration ~/.config/new-tool/config.ts # Alias configuration (fallback) ~/.config/old-tool/config.ts ``` -------------------------------- ### Install Bunfig via CLI Source: https://bunfig.netlify.app/ Use the Bun package manager to add the library to your project dependencies. ```bash bun add bunfig ``` -------------------------------- ### Search Pattern Example Source: https://bunfig.netlify.app/features/aliases Visual representation of the search order for primary and alias configuration files. ```text Project directories: ├── tlsx.config.ts (primary name) ├── .tlsx.config.ts ├── tlsx.ts ├── .tlsx.ts ├── tlsx.tls.config.ts (primary.alias pattern) ├── .tlsx.tls.config.ts ├── tls.config.ts (alias name) ├── .tls.config.ts ├── tls.ts └── .tls.ts Home directory: ├── ~/.config/tlsx/config.ts ├── ~/.config/tlsx/tlsx.config.ts ├── ~/.config/tlsx/tls.config.ts (alias in primary dir) ├── ~/.config/tls/config.ts (alias directory) ├── ~/.config/tls/tls.config.ts └── ~/.config/tls/tlsx.config.ts (primary in alias dir) Package.json: ├── "tlsx": { ... } (primary section) └── "tls": { ... } (alias section) ``` -------------------------------- ### Basic Home Configuration Example Source: https://bunfig.netlify.app/features/home-directory Define global defaults for a tool named 'my-tool' in `~/.config/my-tool/config.ts`. These settings will be used by all projects unless overridden locally. ```typescript // ~/.config/my-tool/config.ts export default { theme: 'dark', defaultPort: 8080, globalFeatures: ['feature1', 'feature2'], userPreferences: { notifications: true, autoSave: true, }, } ``` -------------------------------- ### Consistent Naming Convention Example (TypeScript) Source: https://bunfig.netlify.app/features/multiple-formats Demonstrates a good practice for consistent naming patterns across configuration files within a project. ```typescript // Good - consistent pattern my - app.config.ts my - api.config.ts my - cli.config.ts // Avoid - mixed patterns my - app.config.ts api - config.js cli.json ``` -------------------------------- ### Initialize Bunfig Configuration Source: https://bunfig.netlify.app/advanced/cli Use 'bunfig init' to set up a new bunfig configuration. Options allow specifying a configuration directory, a template (basic, advanced, monorepo), enabling TypeScript, or including example configurations. ```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 ``` -------------------------------- ### Validation output example Source: https://bunfig.netlify.app/advanced/cli Sample output from the validate command. ```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 ``` -------------------------------- ### Alias Naming Best Practices Source: https://bunfig.netlify.app/features/aliases Examples of descriptive naming conventions for primary and alias configurations. ```typescript // Good const config1 = { name: 'bundler-v2', alias: 'bundler-v1' } // Better const config2 = { name: 'esbuild-config', alias: 'webpack-config' } ``` -------------------------------- ### Define Server Configuration Rules Source: https://bunfig.netlify.app/features/validation Example rule set for validating server-related configuration properties. ```typescript const serverRules = [ { path: 'port', required: true, type: 'number', min: 1, max: 65535 }, { path: 'host', required: true, type: 'string', min: 1 }, { path: 'ssl', type: 'boolean' }, { path: 'cors.enabled', type: 'boolean' }, { path: 'cors.origins', type: 'array' } ] ``` -------------------------------- ### Run bunfig directly Source: https://bunfig.netlify.app/advanced/cli Execute the CLI without global installation using bunx. ```bash bunx bunfig --help ``` -------------------------------- ### Define Database Configuration Rules Source: https://bunfig.netlify.app/features/validation Example rule set for validating database connection settings. ```typescript const databaseRules = [ { path: 'url', required: true, type: 'string', pattern: /^(postgresql|mysql|sqlite):\/\//, message: 'Database URL must use a supported protocol' }, { path: 'pool', type: 'number', min: 1, max: 100 }, { path: 'timeout', type: 'number', min: 0 }, { path: 'ssl', type: 'boolean' } ] ``` -------------------------------- ### Define global configuration file Source: https://bunfig.netlify.app/usage Example of a global configuration file located in the user's home directory. ```typescript // ~/.config/my-app/config.ts (global) export default { port: 8080, host: 'production.example.com', features: { auth: true, api: true, }, } ``` -------------------------------- ### Merged Configuration Example Source: https://bunfig.netlify.app/features/home-directory Illustrates the final merged configuration object after applying local overrides to the global home directory configuration. Shows which settings are inherited and which are modified. ```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) } ``` -------------------------------- ### Bunfig Merge Output with Source Information Source: https://bunfig.netlify.app/advanced/cli This example demonstrates the output of 'bunfig merge --show-sources', indicating the origin of each configuration value, whether from a file or environment variable. ```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" } } } ``` -------------------------------- ### Define Package.json Configuration Source: https://bunfig.netlify.app/api Example structure for defining configuration directly within the package.json file when no external configuration files are present. ```json { "my-app": { "port": 4000, "host": "example.com" } } ``` -------------------------------- ### Define Default Configuration Source: https://bunfig.netlify.app/features/environment-variables Example of a default configuration object structure for a Bunfig application. ```typescript const options = { name: 'my-app', defaultConfig: { port: 3000, host: 'localhost', database: { url: 'postgres://localhost:5432', user: 'admin', }, features: { logging: { enabled: true, level: 'info', }, }, }, } ``` -------------------------------- ### Environment Variable Mapping Source: https://bunfig.netlify.app/features/environment-variables Example environment variables that map to the nested properties of the default configuration. ```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 ``` -------------------------------- ### Development vs. Production Configuration Loading Source: https://bunfig.netlify.app/ Load configuration dynamically based on the environment. This example shows loading from a specific file for development and using environment variables for production. ```typescript // Development: loads from app.config.ts const config = await loadConfig({ name: 'app' }) // Production: automatically uses environment variables // APP_DATABASE_URL, APP_SERVER_PORT, etc. ``` -------------------------------- ### Tool-Specific Home Configuration Source: https://bunfig.netlify.app/features/home-directory Example of setting up personalized global configurations for development tools, such as a bundler, in `~/.config/bundler/config.ts`. This allows for consistent tool behavior across projects. ```typescript // ~/.config/bundler/config.ts export default { outputDir: 'dist', minify: true, sourceMaps: true, target: 'es2020', personalDefaults: { watchMode: true, openBrowser: false, }, } ``` -------------------------------- ### ConfigByName Mapping Example Source: https://bunfig.netlify.app/advanced/typescript-plugin Access the complete mapping of configuration names to their types using ConfigByName. This allows you to reference specific configuration types by name. ```typescript import type { ConfigByName } from 'bunfig' // ConfigByName is a mapping like: // { // 'app': AppConfigType, // 'database': DatabaseConfigType, // 'auth': AuthConfigType // } type AppConfigType = ConfigByName['app'] type DatabaseConfigType = ConfigByName['database'] ``` -------------------------------- ### Bunfig CLI Default Configuration (.bunfigrc.json) Source: https://bunfig.netlify.app/advanced/cli Configure default CLI options by creating a .bunfigrc.json file in your project root. This example sets the configuration directory, output directory, default format, and file extensions to process. ```json { "configDir": "./config", "outputDir": "./src/generated", "format": "typescript", "verbose": false, "watch": false, "extensions": [".ts", ".js", ".mjs", ".cjs", ".json"], "exclude": ["**/*.test.*", "**/*.spec.*"] } ``` -------------------------------- ### Global Preferences for CLI Tools Source: https://bunfig.netlify.app/features/home-directory Example of a home directory configuration file (`~/.config/my-cli/config.ts`) for a command-line interface tool, specifying global preferences like output format and logging verbosity. ```typescript // ~/.config/my-cli/config.ts export default { outputFormat: 'json', verboseLogging: false, colorOutput: true, editor: 'vscode', } ``` -------------------------------- ### Bunfig CLI Configuration via Environment Variables Source: https://bunfig.netlify.app/advanced/cli Control Bunfig CLI behavior using environment variables. This example shows how to set the configuration directory, output directory, default format, and enable verbose or debug logging. ```bash # Configuration directory export BUNFIG_CONFIG_DIR=./settings # Output directory for generated files export BUNFIG_OUTPUT_DIR=./types # Default format export BUNFIG_FORMAT=typescript # Enable verbose logging export BUNFIG_VERBOSE=true # Enable debug mode export BUNFIG_DEBUG=true ``` -------------------------------- ### Type-Safe Configuration Loading Source: https://bunfig.netlify.app/advanced/typescript-plugin Shows how to use `ConfigOf` to get type-safe access to specific configuration types, with type-checking against your actual config files. ```APIDOC ### Type-Safe Configuration Loading Use `ConfigOf` to get type-safe access to specific configuration types: ```typescript import type { ConfigOf } from 'bunfig' import { loadConfig } from 'bunfig' // Get the type of your 'app' configuration const appConfig = await loadConfig>({ name: 'app', defaultConfig: { // This will be type-checked against your config/app.ts file port: 3000, host: 'localhost', } as ConfigOf<'app'>, }) // appConfig is now fully typed based on your actual config file console.log(appConfig.port) // TypeScript knows this is a number ``` ``` -------------------------------- ### Web Server Configuration Example Source: https://bunfig.netlify.app/ Define configuration for HTTP server settings, CORS, and rate limiting. Environment variables can override specific nested properties like `SERVER_HTTP_PORT`. ```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 ``` -------------------------------- ### Sanitize and Share Bunfig Configuration Source: https://bunfig.netlify.app/advanced/troubleshooting Prepare configuration files for sharing by removing sensitive information. This example shows how to redact database credentials or other private data. ```typescript // Remove sensitive information before sharing export default { port: 3000, host: 'localhost', // database: 'REDACTED' } ``` -------------------------------- ### Get Detailed Bunfig Info Source: https://bunfig.netlify.app/advanced/troubleshooting Use the `bunfig info` command to retrieve detailed information about configuration resolution, including search paths, found files, resolution order, type information, and configuration content. Use flags like `--show-content` and `--show-types` for more details. ```bash bunfig info app --show-content --show-types ``` -------------------------------- ### Create and use custom templates Source: https://bunfig.netlify.app/advanced/cli 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 ``` -------------------------------- ### Get Bunfig Version Source: https://bunfig.netlify.app/advanced/troubleshooting Display the installed Bunfig version using the `bunfig --version` command. This is useful for reporting issues or checking compatibility. ```bash bunfig --version ``` -------------------------------- ### Reference configuration types Source: https://bunfig.netlify.app/api Examples for referencing bunfig types in TypeScript projects. ```typescript // With plugin: type could be 'app' | 'auth' | 'database' // Without plugin: type is string ``` ```typescript /// ``` ```json { "compilerOptions": { "types": ["bunfig"] } } ``` ```typescript import type { ConfigOf } from 'bunfig' const cfg = await loadConfig>({ name: 'app', defaultConfig: { /* ... */ } as ConfigOf<'app'> }) ``` -------------------------------- ### Configuration info output Source: https://bunfig.netlify.app/advanced/cli Sample output showing resolution order and file locations. ```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 ``` -------------------------------- ### Generated configuration types Source: https://bunfig.netlify.app/advanced/cli Example of the TypeScript interfaces generated by the bunfig generate command. ```ts // src/generated/config-types.ts export type ConfigNames = 'app' | 'database' | 'auth' export interface ConfigByName { app: AppConfig database: DatabaseConfig auth: AuthConfig } export interface AppConfig { port: number host: string features: string[] } export interface DatabaseConfig { url: string pool: number ssl: boolean } export interface AuthConfig { secret: string tokenExpiry: number providers: string[] } export type ConfigOf = ConfigByName[T] ``` -------------------------------- ### Check Home Directory Path and Structure Source: https://bunfig.netlify.app/advanced/troubleshooting Verify the correct path to your home directory and ensure the global configuration directory (`~/.config/`) has the expected structure. ```bash echo $HOME ls -la ~/.config/ ``` -------------------------------- ### Basic Usage of Bunfig Source: https://bunfig.netlify.app/usage Demonstrates the simplest way to use the `config` function to load application configuration with optional type safety. ```APIDOC ## Basic Usage of `config` function This section shows how to load configuration using the `config` function from `bunfig`. ### Method `config(name: string | { name: string, alias?: string, defaultConfig?: object })` ### Parameters - **name** (string | object) - Required - The name of the configuration to load, or an object with configuration options. - **name** (string) - Required - The base name for the configuration file or package.json section. - **alias** (string) - Optional - An alternative name to look for if the primary name is not found. - **defaultConfig** (object) - Optional - Default configuration values to use if no configuration is found. ### Request Example ```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 myConfigWithOptions = await config({ name: 'my-app', defaultConfig: { port: 3000, host: 'localhost', }, }) // Using an alias for alternative config file names const myConfigWithAlias = await config({ name: 'my-app', alias: 'app', defaultConfig: { port: 3000, host: 'localhost', }, }) ``` ### Response #### Success Response (200) - **config** (object) - The loaded configuration object matching the specified interface. ``` -------------------------------- ### Run Application Source: https://bunfig.netlify.app/quick-start Execute your application using the 'bun run' command to see bunfig in action. ```bash bun run server.ts ``` -------------------------------- ### Define local configuration file Source: https://bunfig.netlify.app/usage Example of a local TypeScript configuration file exported as a default object. ```typescript // my-app.config.ts (local) export default { port: 4000, host: 'localhost', features: { auth: true, api: true, }, } ``` -------------------------------- ### Define API Configuration Rules Source: https://bunfig.netlify.app/features/validation Example rule set for validating API client or server settings. ```typescript const apiRules = [ { path: 'baseUrl', required: true, type: 'string', pattern: /^https?:\/\//, message: 'Base URL must be a valid HTTP/HTTPS URL' }, { path: 'timeout', type: 'number', min: 0 }, { path: 'retries', type: 'number', min: 0, max: 10 }, { path: 'rateLimit.enabled', type: 'boolean' }, { path: 'rateLimit.requests', type: 'number', min: 1 } ] ``` -------------------------------- ### Complete Configuration Flow Source: https://bunfig.netlify.app/features/environment-variables Demonstrates the priority order between default values, environment variables, and config files. ```typescript // 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 // }, // } ``` -------------------------------- ### Provide Meaningful Default Configuration Values Source: https://bunfig.netlify.app/features/error-handling Illustrates how to provide sensible default values for configuration options, ensuring the application can run even if certain configuration settings are missing. ```typescript // ✅ Always provide sensible defaults const config = await loadConfig({ name: 'app', defaultConfig: { port: 3000, host: 'localhost', timeout: 30000, retries: 3 } }) ``` -------------------------------- ### Loading Configuration with Aliases Source: https://bunfig.netlify.app/features/home-directory Demonstrates how to load configuration using an alias, which extends the search path to include configuration files associated with the alias name. This is useful for migrating configurations. ```typescript const config = await loadConfig({ name: 'new-tool', alias: 'old-tool', defaultConfig: { /* ... */ }, }) ``` -------------------------------- ### Display configuration info Source: https://bunfig.netlify.app/advanced/cli Commands to inspect configuration resolution order and file details. ```bash bunfig info [config-name] [options] Options: --config-dir Configuration directory (default: ./config) --show-content Show configuration file contents --show-types Show type information --format Output format: text|json|yaml (default: text) Examples: bunfig info # Show info for all configs bunfig info app # Show info for specific config bunfig info --show-content bunfig info --show-types --format json ``` -------------------------------- ### Install Bunfig Plugin in tsconfig.json Source: https://bunfig.netlify.app/advanced/typescript-plugin Add the Bunfig plugin to your tsconfig.json to enable dynamic type generation and type-safe configuration loading. ```json { "compilerOptions": { "types": ["bunfig"] }, "plugins": [ { "name": "bunfig/ts-plugin", "configDir": "./config" } ] } ``` -------------------------------- ### Global CLI Options Source: https://bunfig.netlify.app/advanced/cli Standard options available for all bunfig commands. ```bash bunfig [command] [options] Options: -h, --help Show help -v, --version Show version --config-dir Configuration directory (default: ./config) --verbose Enable verbose logging --silent Suppress output ``` -------------------------------- ### Run tests with Bun Source: https://bunfig.netlify.app/intro Execute the test suite using the Bun runtime. ```bash bun test ``` -------------------------------- ### List Configuration Files (`list`) Source: https://bunfig.netlify.app/advanced/cli Lists all discovered configuration files. Options include specifying the configuration directory, output format (text, JSON, YAML), and whether to show full paths or type information. ```APIDOC ## `list` List all discovered configuration files. ### Usage 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 ```bash bunfig list bunfig list --show-path --format json bunfig list --show-types ``` ### List Output ```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 ``` ``` -------------------------------- ### Environment Variable Mapping Source: https://bunfig.netlify.app/quick-start Demonstrates how to map configuration properties to environment variables using the {NAME}_{PATH} pattern. ```bash # For config name 'app' and property path 'server.port' export APP_SERVER_PORT=8080 # For nested properties use underscores export APP_DATABASE_POOL_SIZE=20 ``` -------------------------------- ### Configuration File (`.bunfigrc.json`) Source: https://bunfig.netlify.app/advanced/cli Configure Bunfig CLI defaults by creating a `.bunfigrc.json` file in your project root. This allows setting options like `configDir`, `outputDir`, `format`, and more. ```APIDOC ## Configuration File Create a `.bunfigrc.json` file in your project root to configure CLI defaults: ```json { "configDir": "./config", "outputDir": "./src/generated", "format": "typescript", "verbose": false, "watch": false, "extensions": [".ts", ".js", ".mjs", ".cjs", ".json"], "exclude": ["**/*.test.*", "**/*.spec.*"] } ``` ### Configuration Options | Option| Type| Default| Description ---|---|---|--- `configDir`| `string`| `"./config"`| Configuration directory `outputDir`| `string`| `"./src/generated"`| Output directory for generated files `format`| `string`| `"typescript"`| Default output format `verbose`| `boolean`| `false`| Enable verbose logging `watch`| `boolean`| `false`| Watch for changes `extensions`| `string[]`| `[".ts", ".js", ...]`| File extensions to process `exclude`| `string[]`| `["**/*.test.*", ...]`| Patterns to exclude ``` -------------------------------- ### List Discovered Configuration Files Source: https://bunfig.netlify.app/advanced/cli Use 'bunfig list' to display all configuration files found. Options include specifying the configuration directory, output format (text, json, yaml), and showing full paths or type information. ```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 ``` -------------------------------- ### Type-Safe Configuration Loading with ConfigOf Source: https://bunfig.netlify.app/advanced/typescript-plugin Use ConfigOf to get type-safe access to specific configuration types. The defaultConfig will be type-checked against your actual config file. ```typescript import type { ConfigOf } from 'bunfig' import { loadConfig } from 'bunfig' // Get the type of your 'app' configuration const appConfig = await loadConfig>({ name: 'app', defaultConfig: { // This will be type-checked against your config/app.ts file port: 3000, host: 'localhost', } as ConfigOf<'app'>, }) // appConfig is now fully typed based on your actual config file console.log(appConfig.port) // TypeScript knows this is a number ``` -------------------------------- ### Implement Namespace Support Source: https://bunfig.netlify.app/advanced/typescript-plugin Organizes configurations into namespaces and utilizes ConfigOf for type-safe access. ```typescript // config/api.ts // Usage with type safety import type { ConfigOf } from 'bunfig' export default { server: { port: 3000, host: 'localhost', }, cors: { origins: ['http://localhost:3000'], methods: ['GET', 'POST'], }, rateLimit: { windowMs: 15 * 60 * 1000, max: 100, }, } type ApiConfig = ConfigOf<'api'> // TypeScript knows: { server: {...}, cors: {...}, rateLimit: {...} } const config = await loadConfig({ name: 'api', defaultConfig: {} as ApiConfig, }) // Full autocompletion available config.server.port // number config.cors.origins // string[] config.rateLimit.max // number ``` -------------------------------- ### Using Common Rules Source: https://bunfig.netlify.app/features/validation Demonstrates how to create and use pre-built common validation rules provided by Bunfig. ```APIDOC ## Using Common Rules bunfig provides pre-built validation rules for common patterns: ```typescript import { ConfigValidator } from 'bunfig' const commonRules = ConfigValidator.createCommonRules() // Use server rules const serverResult = await validator.validateConfiguration( serverConfig, commonRules.server ) // Use database rules const dbResult = await validator.validateConfiguration( databaseConfig, commonRules.database ) // Use API rules const apiResult = await validator.validateConfiguration( apiConfig, commonRules.api ) ``` ``` -------------------------------- ### Environment Variable to Configuration Mapping Source: https://bunfig.netlify.app/ bunfig intelligently maps environment variables to nested configuration properties. For example, `APP_DATABASE_POOL_SIZE` is automatically converted to `config.database.pool.size` as a number. ```bash # Set an environment variable export APP_DATABASE_POOL_SIZE=20 # bunfig automatically maps it to config.database.pool.size = 20 // (as a number!) ``` -------------------------------- ### Generated Types and Usage Source: https://bunfig.netlify.app/advanced/build-plugin This section details the structure of the virtual module generated by bunfig and provides examples of how to use these types in your application code for type-safe configuration loading. ```APIDOC ## Generated Types ### Description The plugin generates a virtual module that exports type information about your configuration files, enabling type-safe access to configuration values. ### Virtual Module Structure The generated virtual module (default name: `virtual:bunfig-types`) exports the following types: - **ConfigNames**: A union type of all discovered configuration file names (without extensions). - **ConfigByName**: An interface mapping each `ConfigName` to its corresponding extracted TypeScript type. - **ConfigOf**: A utility type that resolves to the specific configuration type for a given `ConfigName`. ```typescript // virtual:bunfig-types (generated) export type ConfigNames = 'app' | 'database' | 'auth' | 'logging' export interface ConfigByName { app: AppConfigType database: DatabaseConfigType auth: AuthConfigType logging: LoggingConfigType } export type ConfigOf = ConfigByName[T] ``` ### Usage in Your Code Import the generated types into your application to leverage type safety when loading configurations. ```typescript // src/config-loader.ts import type { ConfigNames, ConfigOf } from 'virtual:bunfig-types' import { loadConfig } from 'bunfig' // Type-safe configuration loading function export async function loadAppConfig( name: T ): Promise> { return loadConfig>({ name, defaultConfig: {} as ConfigOf, }) } // Usage with full type safety const appConfig = await loadAppConfig('app') // Typed as AppConfigType const dbConfig = await loadAppConfig('database') // Typed as DatabaseConfigType ``` ```