{"id":43325036,"url":"https://github.com/northern/yaml-loader","last_synced_at":"2026-02-01T23:05:49.789Z","repository":{"id":334322617,"uuid":"1140973868","full_name":"northern/yaml-loader","owner":"northern","description":"Load YAML files from fragmented sources","archived":false,"fork":false,"pushed_at":"2026-01-24T05:48:17.000Z","size":61,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-01-24T14:32:25.572Z","etag":null,"topics":["yaml","yaml-files","yaml-parser"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@northern/yaml-loader","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/northern.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-01-24T02:43:28.000Z","updated_at":"2026-01-24T05:48:05.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/northern/yaml-loader","commit_stats":null,"previous_names":["northern/yaml-loader"],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/northern/yaml-loader","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/northern%2Fyaml-loader","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/northern%2Fyaml-loader/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/northern%2Fyaml-loader/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/northern%2Fyaml-loader/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/northern","download_url":"https://codeload.github.com/northern/yaml-loader/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/northern%2Fyaml-loader/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28993851,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-01T22:01:47.507Z","status":"ssl_error","status_checked_at":"2026-02-01T21:58:37.335Z","response_time":56,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["yaml","yaml-files","yaml-parser"],"created_at":"2026-02-01T23:05:48.861Z","updated_at":"2026-02-01T23:05:49.783Z","avatar_url":"https://github.com/northern.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# YAML Loader\n\nA comprehensive utility for loading and parsing YAML/JSON files with advanced `$ref` resolution, type safety, and performance optimizations.\n\n## Install\n\nInstall with NPM:\n\n    npm install @northern/di\n\nor Yarn:\n\n    yarn add @northern/di\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Installation](#installation)\n- [Basic Usage](#basic-usage)\n- [Type Safety](#type-safety)\n- [Reference Resolution](#reference-resolution)\n- [Configuration Options](#configuration-options)\n- [Error Handling](#error-handling)\n- [Performance Features](#performance-features)\n- [Security Features](#security-features)\n- [Advanced Usage](#advanced-usage)\n- [API Reference](#api-reference)\n- [Migration Guide](#migration-guide)\n- [Troubleshooting](#troubleshooting)\n\n## Overview\n\nThe YAML loader module provides:\n\n- **Multi-format support**: YAML and JSON file parsing\n- **Advanced reference resolution**: Internal and external `$ref` resolution with circular detection\n- **Type safety**: Full TypeScript generic support\n- **Performance**: LRU caching and optimized algorithms\n- **Security**: Configurable access controls and path validation\n- **Debugging**: Comprehensive debug information and error reporting\n- **Extensibility**: Custom resolver plugin system\n\n## Basic Usage\n\n```typescript\nimport loadYaml from '@northern/yaml-loader';\n```\n\n### Simple YAML Loading\n\n```typescript\n// Basic usage - returns any type\nconst config = loadYaml('config.yaml');\nconsole.log(config.name); // Access properties with basic autocomplete\n```\n\n### Loading JSON Files\n\n```typescript\n// JSON files are supported automatically\nconst data = loadYaml('data.json');\n```\n\n### Loading Nested Structures\n\n```typescript\n// Complex nested YAML structures\nconst app = loadYaml('app.yaml');\n\n// Access nested properties\nconst serverConfig = app.server;\nconst dbConfig = app.database;\n```\n\n## Type Safety\n\n### Generic Types\n\n```typescript\ninterface AppConfig {\n  name: string;\n  version: number;\n  server: {\n    host: string;\n    port: number;\n    ssl?: boolean;\n  };\n  database: {\n    url: string;\n    pool: {\n      min: number;\n      max: number;\n    };\n  };\n  features: string[];\n}\n\n// Full type inference and compile-time checking\nconst config = loadYaml\u003cAppConfig\u003e('app.yaml');\n\n// TypeScript will catch type errors\nconst host: string = config.server.host; // ✅ Valid\nconst port: string = config.server.port; // ❌ TypeScript error: Type 'number' is not assignable to 'string'\nconfig.invalidProperty; // ❌ TypeScript error: Property does not exist\n```\n\n### Complex Nested Types\n\n```typescript\ninterface User {\n  id: number;\n  name: string;\n  profile: {\n    email: string;\n    avatar?: string;\n  };\n  roles: Array\u003c{\n    name: string;\n    permissions: string[];\n  }\u003e;\n}\n\ninterface UsersConfig {\n  users: User[];\n  metadata: {\n    created: Date;\n    version: string;\n    tags: string[];\n  };\n}\n\nconst usersConfig = loadYaml\u003cUsersConfig\u003e('users.yaml');\n\n// Full type safety throughout\nusersConfig.users.forEach(user =\u003e {\n  console.log(user.profile.email); // ✅ Type-safe access\n  user.roles.forEach(role =\u003e {\n    console.log(role.permissions.join(', ')); // ✅ Type-safe array operations\n  });\n});\n```\n\n### Union Types and Discriminated Unions\n\n```typescript\ntype DatabaseConfig = \n  | { type: 'postgres'; host: string; port: number; database: string; }\n  | { type: 'mongodb'; url: string; collection: string; };\n\ninterface ServiceConfig {\n  name: string;\n  database: DatabaseConfig;\n}\n\nconst config = loadYaml\u003cServiceConfig\u003e('service.yaml');\n\n// TypeScript will help you handle different database types\nif (config.database.type === 'postgres') {\n  console.log(config.database.host); // ✅ TypeScript knows this is postgres config\n  // config.database.url; // ❌ TypeScript error: Property 'url' does not exist\n}\n```\n\n## Reference Resolution\n\n### Internal References\n\n```yaml\n# config.yaml\ndefinitions:\n  server:\n    host: localhost\n    port: 3000\n  database:\n    url: postgresql://localhost:5432/mydb\n    \nservices:\n  api:\n    # Internal reference to definitions\n    $ref: \"#/definitions/server\"\n  database:\n    $ref: \"#/definitions/database\"\n```\n\n```typescript\nconst config = loadYaml('config.yaml');\n// Result will have fully resolved structure\n// {\n//   definitions: { server: {...}, database: {...} },\n//   services: {\n//     api: { host: 'localhost', port: 3000 },\n//     database: { url: 'postgresql://localhost:5432/mydb' }\n//   }\n// }\n```\n\n### External File References\n\n```yaml\n# shared/database.yaml\nurl: postgresql://localhost:5432/mydb\npool:\n  min: 5\n  max: 20\n\n# config.yaml\ndatabase:\n  $ref: \"./shared/database.yaml\"\n  \napi:\n  version: v1\n  port: 8080\n```\n\n### Combined External and Pointer References\n\n```yaml\n# schemas/user.yaml\ndefinitions:\n  User:\n    type: object\n    properties:\n      id:\n        type: integer\n      name:\n        type: string\n      email:\n        type: string\n        format: email\n\n# api.yaml\nuserSchema:\n  $ref: \"./schemas/user.yaml#/definitions/User\"\n  \nendpoints:\n  - path: /users\n    schema:\n      $ref: \"./schemas/user.yaml#/definitions/User\"\n```\n\n### Nested Reference Chains\n\n```yaml\n# level3.yaml\nfinalValue: \"Deeply nested reference resolved\"\n\n# level2.yaml\ndata:\n  $ref: \"./level3.yaml\"\n\n# level1.yaml\nnested:\n  $ref: \"./level2.yaml\"\n\n# main.yaml\nresult:\n  $ref: \"./level1.yaml\"\n```\n\n### Array References\n\n```yaml\n# item.yaml\ntype: shared-item\nproperties:\n  name: string\n  value: number\n\n# main.yaml\nitems:\n  - name: inline1\n    type: local\n  - $ref: \"./item.yaml\"\n  - name: inline2\n    type: local\n  - $ref: \"./item.yaml\"\n```\n\n### JSON Pointer Features\n\n```yaml\n# data.yaml\n\"a/b path\":\n  value: \"path with slash\"\n\"a~b\":\n  value: \"path with tilde\"\nitems:\n  - first\n  - second\n  - third\n\n# ref.yaml\n# Reference with escaped characters\nslashExample:\n  $ref: \"./data.yaml#/a~1b path\"\ntildeExample:\n  $ref: \"./data.yaml#/a~0b\"\narrayItem:\n  $ref: \"./data.yaml#/items/1\"\n```\n\n## Configuration Options\n\n### Basic Configuration\n\n```typescript\nimport { YamlLoaderOptions } from './yaml-loader';\n\nconst options: YamlLoaderOptions = {\n  maxCacheSize: 50,\n  allowExternalAccess: false,\n  strictMode: true\n};\n\nconst config = loadYaml('config.yaml', options);\n```\n\n### Cache Configuration\n\n```typescript\n// Large cache for enterprise applications\nconst enterpriseOptions: YamlLoaderOptions = {\n  maxCacheSize: 500 // Cache up to 500 files\n};\n\n// Small cache for simple applications\nconst simpleOptions: YamlLoaderOptions = {\n  maxCacheSize: 10 // Cache only 10 files\n};\n```\n\n### Security Configuration\n\n```typescript\n// Default: prevent directory traversal\nconst secureOptions: YamlLoaderOptions = {\n  allowExternalAccess: false\n};\n\n// Allow external access for trusted environments\nconst openOptions: YamlLoaderOptions = {\n  allowExternalAccess: true\n};\n```\n\n### Strict Mode\n\n```typescript\n// Enable strict validation\nconst strictOptions: YamlLoaderOptions = {\n  strictMode: true\n};\n\n// Disable for legacy compatibility\nconst lenientOptions: YamlLoaderOptions = {\n  strictMode: false\n};\n```\n\n## Error Handling\n\n### Basic Error Handling\n\n```typescript\nimport { YamlLoaderError } from './yaml-loader';\n\ntry {\n  const config = loadYaml('config.yaml');\n  console.log('Loaded successfully:', config);\n} catch (error) {\n  if (error instanceof YamlLoaderError) {\n    console.error(`YAML Error (${error.type}): ${error.message}`);\n    if (error.path) {\n      console.error('Path:', error.path);\n    }\n    if (error.refChain) {\n      console.error('Reference chain:', error.refChain.join(' -\u003e '));\n    }\n  } else {\n    console.error('Unexpected error:', error);\n  }\n}\n```\n\n### Error Types\n\n```typescript\n// Circular reference error\ntry {\n  loadYaml('circular.yaml');\n} catch (error) {\n  if (error instanceof YamlLoaderError \u0026\u0026 error.type === 'circular_ref') {\n    console.log('Circular reference detected');\n    console.log('Chain:', error.refChain);\n  }\n}\n\n// File not found error\ntry {\n  loadYaml('missing.yaml');\n} catch (error) {\n  if (error instanceof YamlLoaderError \u0026\u0026 error.type === 'file_not_found') {\n    console.log('File not found:', error.path);\n  }\n}\n\n// Invalid JSON pointer\ntry {\n  loadYaml('invalid-pointer.yaml');\n} catch (error) {\n  if (error instanceof YamlLoaderError \u0026\u0026 error.type === 'invalid_pointer') {\n    console.log('Invalid pointer path:', error.path);\n  }\n}\n\n// Parse error\ntry {\n  loadYaml('invalid.yaml');\n} catch (error) {\n  if (error instanceof YamlLoaderError \u0026\u0026 error.type === 'parse_error') {\n    console.log('Parse error:', error.message);\n  }\n}\n```\n\n### Validation Mode\n\n```typescript\nimport { validateYamlReferences } from './yaml-loader';\n\n// Validate without full resolution\nconst validation = validateYamlReferences('config.yaml');\n\nif (validation.isValid) {\n  console.log('All references are valid');\n  const config = loadYaml('config.yaml');\n} else {\n  console.log('Validation failed:');\n  validation.errors.forEach(error =\u003e {\n    console.error(`- ${error.type}: ${error.message}`);\n  });\n  validation.warnings.forEach(warning =\u003e {\n    console.warn(`Warning: ${warning}`);\n  });\n}\n```\n\n## Performance Features\n\n### LRU Cache\n\n```typescript\n// Configure cache size based on application needs\nconst options: YamlLoaderOptions = {\n  maxCacheSize: 100 // Default: 100 files\n};\n\n// Cache automatically handles:\n// - Most recently used files stay in memory\n// - Least recently used files are evicted when limit reached\n// - Multiple references to same file use cached version\n\nconst config = loadYaml('main.yaml', options);\n// If main.yaml references shared.yaml multiple times, it's loaded once\n```\n\n### Debug Mode\n\n```typescript\nimport { loadYamlWithDebug } from './yaml-loader';\n\nconst { result, debug } = loadYamlWithDebug('complex.yaml');\n\nconsole.log(`Resolution completed in ${debug.resolutionTime}ms`);\nconsole.log(`Processed ${debug.refChain.length} references`);\nconsole.log(`Cached ${debug.fileCache.size} files`);\n\n// Analyze cache contents\nfor (const [file, type] of debug.fileCache) {\n  console.log(`${file}: ${type}`);\n}\n```\n\n### Performance Monitoring\n\n```typescript\n// Create a performance wrapper\nfunction loadWithMetrics\u003cT = any\u003e(filename: string): T {\n  const start = Date.now();\n  const { result, debug } = loadYamlWithDebug(filename);\n  const duration = Date.now() - start;\n  \n  console.log(`Load time: ${duration}ms`);\n  console.log(`Cache hits: ${debug.fileCache.size}`);\n  console.log(`References resolved: ${debug.refChain.length}`);\n  \n  return result;\n}\n\nconst config = loadWithMetrics('config.yaml');\n```\n\n## Security Features\n\n### Directory Traversal Protection\n\n```typescript\n// Default: prevents access outside base directory\nconst secureConfig = loadYaml('config.yaml');\n// This will fail if config.yaml contains: $ref: \"../secret.yaml\"\n```\n\n### Allow External Access\n\n```typescript\n// Enable external access for trusted environments\nconst options: YamlLoaderOptions = {\n  allowExternalAccess: true\n};\n\nconst config = loadYaml('config.yaml', options);\n// Now allows: $ref: \"../shared/config.yaml\"\n```\n\n### Path Validation\n\n```typescript\n// Custom path validation\nfunction loadWithValidation(filename: string, allowedPaths: string[]) {\n  try {\n    return loadYaml(filename, { allowExternalAccess: true });\n  } catch (error) {\n    if (error instanceof YamlLoaderError \u0026\u0026 error.type === 'file_not_found') {\n      // Check if path is in allowed list\n      const isAllowed = allowedPaths.some(path =\u003e \n        error.path?.includes(path)\n      );\n      if (!isAllowed) {\n        throw new Error('Access denied to external file');\n      }\n    }\n    throw error;\n  }\n}\n```\n\n## Advanced Usage\n\n### Builder Pattern\n\n```typescript\nimport { YamlLoaderBuilder } from './yaml-loader';\n\n// Simple builder\nconst loader = new YamlLoaderBuilder()\n  .withCache(50)\n  .withStrictMode(true)\n  .withExternalAccess(false)\n  .build();\n\nconst config = loader('config.yaml');\n\n// Generic builder with type safety\ninterface AppConfig {\n  name: string;\n  version: number;\n}\n\nconst typedLoader = new YamlLoaderBuilder()\n  .withCache(25)\n  .buildGeneric\u003cAppConfig\u003e();\n\nconst appConfig = typedLoader('app.yaml');\n// Full type inference with AppConfig interface\n```\n\n### Custom Resolvers\n\n```typescript\nimport { YamlLoaderBuilder } from './yaml-loader';\n\n// Environment variable resolver\nconst loader = new YamlLoaderBuilder()\n  .withCustomResolver('env:', (ref) =\u003e {\n    const varName = ref.replace('env:', '');\n    return process.env[varName] || '';\n  })\n  .build();\n\n// Usage in YAML:\n# config.yaml\ndatabase:\n  url: env:DATABASE_URL\n  password: env:DB_PASSWORD\n\nconst config = loader('config.yaml');\n// config.database.url will contain the environment variable value\n```\n\n### HTTP Resolver\n\n```typescript\nimport axios from 'axios';\n\n// HTTP-based resolver for remote schemas\nconst httpLoader = new YamlLoaderBuilder()\n  .withCustomResolver('http:', async (ref) =\u003e {\n    const response = await axios.get(ref);\n    return response.data;\n  })\n  .withCustomResolver('https:', async (ref) =\u003e {\n    const response = await axios.get(ref);\n    return response.data;\n  })\n  .build();\n\n// Usage in YAML:\n# config.yaml\nschema:\n  $ref: \"https://example.com/schemas/user.json\"\n```\n\n### Template Resolver\n\n```typescript\n// Template-based resolver for dynamic values\nconst templateLoader = new YamlLoaderBuilder()\n  .withCustomResolver('template:', (ref) =\u003e {\n    const templateName = ref.replace('template:', '');\n    const templates = {\n      'user-service': {\n        port: 3000,\n        endpoints: ['/users', '/users/{id}']\n      },\n      'auth-service': {\n        port: 3001,\n        endpoints: ['/login', '/logout', '/refresh']\n      }\n    };\n    return templates[templateName];\n  })\n  .build();\n\n// Usage in YAML:\n# config.yaml\nuserService:\n  $ref: \"template:user-service\"\nauthService:\n  $ref: \"template:auth-service\"\n```\n\n### Conditional Loading\n\n```typescript\nfunction loadConfig(configPath: string, isProduction: boolean) {\n  const options: YamlLoaderOptions = {\n    maxCacheSize: isProduction ? 500 : 50,\n    allowExternalAccess: !isProduction,\n    strictMode: isProduction\n  };\n  \n  return loadYaml(configPath, options);\n}\n\nconst devConfig = loadConfig('config.yaml', false);\nconst prodConfig = loadConfig('config.yaml', true);\n```\n\n### Plugin System\n\n```typescript\n// Create a plugin loader\ninterface Plugin {\n  name: string;\n  resolver: (ref: string) =\u003e any;\n}\n\nclass ExtensibleYamlLoader {\n  private builder = new YamlLoaderBuilder();\n  \n  addPlugin(plugin: Plugin): this {\n    this.builder.withCustomResolver(`${plugin.name}:`, plugin.resolver);\n    return this;\n  }\n  \n  build\u003cT = any\u003e() {\n    return this.builder.buildGeneric\u003cT\u003e();\n  }\n}\n\n// Usage\nconst loader = new ExtensibleYamlLoader()\n  .addPlugin({\n    name: 'env',\n    resolver: (ref) =\u003e process.env[ref.replace('env:', '')] || ''\n  })\n  .addPlugin({\n    name: 'secret',\n    resolver: (ref) =\u003e {\n      // Load from secret manager\n      return getSecret(ref.replace('secret:', ''));\n    }\n  })\n  .build();\n```\n\n## API Reference\n\n### Core Functions\n\n#### `loadYaml\u003cT\u003e(filename: string, options?: YamlLoaderOptions): T`\n\nLoads and parses a YAML file with reference resolution.\n\n**Parameters:**\n- `filename: string` - Absolute path to the YAML/JSON file\n- `options?: YamlLoaderOptions` - Configuration options (optional)\n\n**Returns:**\n- `T` - Parsed and resolved content with type inference\n\n**Example:**\n```typescript\nconst config = loadYaml\u003cConfig\u003e('config.yaml');\n```\n\n#### `loadYamlWithDebug\u003cT\u003e(filename: string, options?: YamlLoaderOptions): { result: T; debug: DebugInfo }`\n\nLoads YAML with debug information for troubleshooting.\n\n**Returns:**\n- `result: T` - The loaded configuration\n- `debug: DebugInfo` - Debug information including cache stats and timing\n\n#### `validateYamlReferences(filename: string, options?: YamlLoaderOptions): ValidationResult`\n\nValidates references without full resolution.\n\n**Returns:**\n- `isValid: boolean` - Whether all references are valid\n- `errors: YamlLoaderError[]` - List of validation errors\n- `warnings: string[]` - List of warnings\n\n### Classes\n\n#### `YamlLoaderBuilder`\n\nBuilder pattern for creating configured loaders.\n\n**Methods:**\n- `withCache(size: number): this` - Set cache size\n- `withStrictMode(enabled: boolean): this` - Enable/disable strict mode\n- `withExternalAccess(enabled: boolean): this` - Allow/deny external access\n- `withCustomResolver(prefix: string, resolver: (ref: string) =\u003e any): this` - Add custom resolver\n- `build(): (filename: string) =\u003e any` - Build configured loader\n- `buildGeneric\u003cT\u003e(): (filename: string) =\u003e T` - Build typed loader\n\n#### `YamlLoaderError`\n\nEnhanced error class for YAML loading issues.\n\n**Properties:**\n- `type: 'circular_ref' | 'file_not_found' | 'invalid_pointer' | 'parse_error'` - Error category\n- `path?: string` - File path or reference path\n- `refChain?: string[]` - Chain of references that led to the error\n\n### Interfaces\n\n#### `YamlLoaderOptions`\n\nConfiguration options for YAML loading.\n\n```typescript\ninterface YamlLoaderOptions {\n  maxCacheSize?: number;        // Maximum files to cache (default: 100)\n  allowExternalAccess?: boolean; // Allow directory traversal (default: false)\n  customResolvers?: Map\u003cstring, (ref: string) =\u003e any\u003e; // Custom resolvers\n  strictMode?: boolean;         // Enable strict validation (default: false)\n}\n```\n\n#### `DebugInfo`\n\nDebug information from `loadYamlWithDebug`.\n\n```typescript\ninterface DebugInfo {\n  refChain: string[];                    // Reference resolution chain\n  fileCache: Map\u003cstring, string\u003e;        // Cached files and their types\n  resolutionTime: number;                 // Time in milliseconds\n}\n```\n\n## Migration Guide\n\n### From Basic Usage\n\n**Before:**\n```typescript\nconst yamlLoader = require('./yaml-loader');\nconst config = yamlLoader('config.yaml');\n```\n\n**After:**\n```typescript\nimport { loadYaml } from './yaml-loader';\nconst config = loadYaml('config.yaml');\n```\n\n### Adding Type Safety\n\n**Before:**\n```typescript\nconst config = loadYaml('config.yaml');\n// No type checking\nconst port = config.port; // Could be anything\n```\n\n**After:**\n```typescript\ninterface Config {\n  port: number;\n  host: string;\n}\nconst config = loadYaml\u003cConfig\u003e('config.yaml');\nconst port = config.port; // TypeScript knows it's a number\n```\n\n### Adding Configuration\n\n**Before:**\n```typescript\nconst config = loadYaml('config.yaml');\n```\n\n**After:**\n```typescript\nconst config = loadYaml('config.yaml', {\n  maxCacheSize: 50,\n  allowExternalAccess: true,\n  strictMode: false\n});\n```\n\n### Using Builder Pattern\n\n**Before:**\n```typescript\nconst config = loadYaml('config.yaml');\n```\n\n**After:**\n```typescript\nconst loader = new YamlLoaderBuilder()\n  .withCache(50)\n  .withStrictMode(true)\n  .build();\n\nconst config = loader('config.yaml');\n```\n\n## Troubleshooting\n\n### Common Issues\n\n#### Circular References\n\n**Error:** `Circular reference detected: A -\u003e B -\u003e A`\n\n**Solution:**\n- Check reference chains in YAML files\n- Use `validateYamlReferences()` to detect issues early\n- Consider restructuring to avoid circular dependencies\n\n#### File Not Found\n\n**Error:** `Failed to load file: /path/to/missing.yaml`\n\n**Solutions:**\n- Verify file paths are correct\n- Check if `allowExternalAccess: true` is needed for external files\n- Use absolute paths for reliable resolution\n\n#### Type Errors\n\n**Error:** TypeScript compilation errors\n\n**Solutions:**\n- Define proper interfaces for your YAML structure\n- Use generic type parameter: `loadYaml\u003cMyInterface\u003e()`\n- Check for optional properties with `?` in interfaces\n\n#### Performance Issues\n\n**Symptoms:** Slow loading times\n\n**Solutions:**\n- Increase cache size with `maxCacheSize`\n- Use debug mode to identify bottlenecks\n- Consider simplifying reference chains\n\n### Debug Techniques\n\n#### Using Debug Mode\n\n```typescript\nconst { result, debug } = loadYamlWithDebug('complex.yaml');\n\nconsole.log('Performance Analysis:');\nconsole.log(`- Total time: ${debug.resolutionTime}ms`);\nconsole.log(`- References: ${debug.refChain.length}`);\nconsole.log(`- Cache size: ${debug.fileCache.size}`);\n\nconsole.log('Reference Chain:');\ndebug.refChain.forEach((ref, index) =\u003e {\n  console.log(`${index + 1}. ${ref}`);\n});\n```\n\n#### Validation Before Loading\n\n```typescript\nconst validation = validateYamlReferences('config.yaml');\nif (!validation.isValid) {\n  console.log('Issues found:');\n  validation.errors.forEach(error =\u003e {\n    console.error(`- ${error.type}: ${error.message}`);\n  });\n  return;\n}\n\n// Only load if validation passes\nconst config = loadYaml('config.yaml');\n```\n\n#### File Analysis\n\n```typescript\n// Create a file usage analyzer\nfunction analyzeFileUsage(filename: string) {\n  const { debug } = loadYamlWithDebug(filename);\n  \n  const fileUsage = new Map\u003cstring, number\u003e();\n  \n  // Count file usage from reference chain\n  debug.refChain.forEach(ref =\u003e {\n    const filePath = ref.split('#')[0];\n    fileUsage.set(filePath, (fileUsage.get(filePath) || 0) + 1);\n  });\n  \n  console.log('File Usage:');\n  for (const [file, count] of fileUsage) {\n    console.log(`${file}: ${count} references`);\n  }\n}\n\nanalyzeFileUsage('config.yaml');\n```\n\n### Performance Optimization\n\n#### Cache Tuning\n\n```typescript\n// For small applications\nconst smallAppOptions = { maxCacheSize: 10 };\n\n// For medium applications\nconst mediumAppOptions = { maxCacheSize: 50 };\n\n// For large applications\nconst largeAppOptions = { maxCacheSize: 200 };\n```\n\n#### Reference Optimization\n\n```yaml\n# Instead of many small references\napi:\n  user:\n    $ref: \"./schemas/user.yaml\"\n  product:\n    $ref: \"./schemas/product.yaml\"\n  order:\n    $ref: \"./schemas/order.yaml\"\n\n# Consider consolidating\napi:\n  schemas:\n    $ref: \"./schemas/all.yaml\"\n```\n\n#### Lazy Loading\n\n```typescript\n// Load only what you need\nfunction loadSection\u003cT\u003e(filename: string, pointer: string): T {\n  const fullPath = `${filename}#${pointer}`;\n  return loadYaml\u003cT\u003e(fullPath);\n}\n\nconst userConfig = loadSection('config.yaml', '#/services/user');\nconst dbConfig = loadSection('config.yaml', '#/database');\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnorthern%2Fyaml-loader","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnorthern%2Fyaml-loader","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnorthern%2Fyaml-loader/lists"}