config-parser.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Logger } from '../logger.js';
  2. import { withDefaultConfig } from '../utils/defaults.js';
  3. import { getConfigFilePath, getRuntimePaths } from '../utils/path.js';
  4. import { overwriteMerge } from '../utils/merge.js';
  5. import { loadJSON } from '../utils/file.js';
  6. export class ConfigParser {
  7. /**
  8. * Get runtime config
  9. * @param runtimePaths
  10. * @returns
  11. */
  12. async getRuntimeConfig(runtimePaths) {
  13. const exportMarkerConfig = await loadJSON(runtimePaths.EXPORT_MARKER, false).catch((err) => {
  14. Logger.noExportMarker();
  15. throw err;
  16. });
  17. return {
  18. trailingSlash: exportMarkerConfig?.exportTrailingSlash,
  19. };
  20. }
  21. /**
  22. * Update existing config with runtime config
  23. * @param config
  24. * @param runtimePaths
  25. * @returns
  26. */
  27. async withRuntimeConfig(config, runtimePaths) {
  28. // Runtime configs
  29. const runtimeConfig = await this.getRuntimeConfig(runtimePaths);
  30. // Prioritize `trailingSlash` value from `next-sitemap.js`
  31. const trailingSlashConfig = {};
  32. if ('trailingSlash' in config) {
  33. trailingSlashConfig.trailingSlash = config?.trailingSlash;
  34. }
  35. return overwriteMerge(config, runtimeConfig, trailingSlashConfig);
  36. }
  37. /**
  38. * Load next-sitemap.config.js as module
  39. * @returns
  40. */
  41. async loadBaseConfig() {
  42. // Get config file path
  43. const path = await getConfigFilePath();
  44. // Config loading message
  45. Logger.log('✨', `Loading next-sitemap config:`, path);
  46. // Load base config
  47. const baseConfig = await import(path);
  48. if (!baseConfig.default) {
  49. throw new Error('Unable to next-sitemap config file');
  50. }
  51. return withDefaultConfig(baseConfig.default);
  52. }
  53. /**
  54. * Load full config
  55. * @returns
  56. */
  57. async loadConfig() {
  58. // Load base config
  59. const baseConfig = await this.loadBaseConfig();
  60. // Find the runtime paths using base config
  61. const runtimePaths = getRuntimePaths(baseConfig);
  62. // Update base config with runtime config
  63. const config = await this.withRuntimeConfig(baseConfig, runtimePaths);
  64. // Return full result
  65. return {
  66. config,
  67. runtimePaths,
  68. };
  69. }
  70. }