compileAbilitiesConfig.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Precompile the abilities config from Yaml to TS
  3. */
  4. import * as fs from 'fs'
  5. import * as path from 'path'
  6. import * as yaml from 'js-yaml'
  7. interface AbilityCondition {
  8. function: string
  9. parameters?: unknown[]
  10. expectedResult?: boolean
  11. }
  12. interface AbilityConfig {
  13. action: string
  14. conditions: AbilityCondition[]
  15. }
  16. interface CompiledAbilities {
  17. [key: string]: AbilityConfig
  18. }
  19. function loadYamlFile(filePath: string): unknown {
  20. try {
  21. const fileContents = fs.readFileSync(filePath, 'utf8')
  22. return yaml.load(fileContents)
  23. } catch (error) {
  24. console.error(`Error loading YAML file ${filePath}:`, error)
  25. return {}
  26. }
  27. }
  28. function compileAbilitiesConfig(): void {
  29. const configDir = path.join(process.cwd(), 'config/abilities/pages')
  30. const outputPath = path.join(
  31. process.cwd(),
  32. 'config/abilities/config-precompiled.ts',
  33. )
  34. console.log('Starting abilities config compilation...')
  35. // Read all YAML files from the pages directory
  36. const yamlFiles = fs
  37. .readdirSync(configDir)
  38. .filter((file) => file.endsWith('.yaml'))
  39. const compiledAbilities: CompiledAbilities = {}
  40. yamlFiles.forEach((file) => {
  41. const filePath = path.join(configDir, file)
  42. console.log(`Processing ${file}...`)
  43. const config = loadYamlFile(filePath)
  44. // Merge all abilities from this file into the compiled config
  45. Object.assign(compiledAbilities, config)
  46. })
  47. // Generate TypeScript content
  48. const header = `/**
  49. * AUTO-GENERATED FILE - DO NOT MODIFY MANUALLY
  50. *
  51. * This file is automatically generated from YAML configuration files
  52. * in config/abilities/pages/ directory.
  53. *
  54. * To make changes, edit the source YAML files and run the compilation script :
  55. * yarn prepare
  56. *
  57. * Generated on: ${new Date().toISOString()}
  58. */
  59. `
  60. const tsContent = `${header}export default ${JSON.stringify(compiledAbilities, null, 2)} as const
  61. `
  62. // Write the compiled TypeScript file
  63. fs.writeFileSync(outputPath, tsContent, 'utf8')
  64. console.log(`✓ Abilities config compiled successfully to ${outputPath}`)
  65. console.log(`✓ Processed ${yamlFiles.length} YAML files`)
  66. console.log(
  67. `✓ Generated ${Object.keys(compiledAbilities).length} ability definitions`,
  68. )
  69. }
  70. // Run the compilation
  71. compileAbilitiesConfig()