file-loader.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import fs from 'node:fs';
  2. import yaml from 'js-yaml';
  3. import { prepareConfigFileForRead, resolveConfigFromRaw, type Config } from './config.js';
  4. export type ConfigFileErrorCode =
  5. | 'CONFIG_READ_FAILED'
  6. | 'CONFIG_PARSE_FAILED'
  7. | 'CONFIG_ROOT_INVALID';
  8. export class ConfigFileError extends Error {
  9. readonly code: ConfigFileErrorCode;
  10. readonly configPath: string;
  11. constructor(
  12. code: ConfigFileErrorCode,
  13. configPath: string,
  14. message: string,
  15. options?: ErrorOptions,
  16. ) {
  17. super(message, options);
  18. this.name = 'ConfigFileError';
  19. this.code = code;
  20. this.configPath = configPath;
  21. }
  22. }
  23. export interface LoadConfigFromFileOptions {
  24. dataDir: string;
  25. }
  26. function readConfigDocument(configPath: string): Record<string, unknown> {
  27. let text: string;
  28. try {
  29. text = fs.readFileSync(configPath, 'utf-8');
  30. } catch (cause) {
  31. throw new ConfigFileError(
  32. 'CONFIG_READ_FAILED',
  33. configPath,
  34. `Cannot read config ${configPath}.`,
  35. { cause },
  36. );
  37. }
  38. let parsed: unknown;
  39. try {
  40. parsed = yaml.load(text);
  41. } catch (cause) {
  42. throw new ConfigFileError(
  43. 'CONFIG_PARSE_FAILED',
  44. configPath,
  45. `Config is not valid YAML: ${configPath}`,
  46. { cause },
  47. );
  48. }
  49. if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) {
  50. throw new ConfigFileError(
  51. 'CONFIG_ROOT_INVALID',
  52. configPath,
  53. `Config root must be an object: ${configPath}`,
  54. );
  55. }
  56. return parsed as Record<string, unknown>;
  57. }
  58. export function loadConfigFromFile(configPath: string, options: LoadConfigFromFileOptions): Config {
  59. if (fs.existsSync(configPath)) prepareConfigFileForRead(configPath);
  60. return resolveConfigFromRaw(readConfigDocument(configPath), options.dataDir);
  61. }
  62. export function readExplicitBetaFeatureFromFile(
  63. configPath: string,
  64. feature: keyof Config['beta'],
  65. ): boolean | undefined {
  66. const raw = readConfigDocument(configPath);
  67. if (raw.beta == null || typeof raw.beta !== 'object' || Array.isArray(raw.beta)) {
  68. return undefined;
  69. }
  70. const configured = (raw.beta as Record<string, unknown>)[feature];
  71. return typeof configured === 'boolean' ? configured : undefined;
  72. }