compileAbilitiesConfig.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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?: any[]
  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): any {
  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(process.cwd(), 'config/abilities/config-precompiled.ts')
  31. console.log('Starting abilities config compilation...')
  32. // Read all YAML files from the pages directory
  33. const yamlFiles = fs.readdirSync(configDir).filter(file => file.endsWith('.yaml'))
  34. const compiledAbilities: CompiledAbilities = {}
  35. yamlFiles.forEach(file => {
  36. const filePath = path.join(configDir, file)
  37. console.log(`Processing ${file}...`)
  38. const config = loadYamlFile(filePath)
  39. // Merge all abilities from this file into the compiled config
  40. Object.assign(compiledAbilities, config)
  41. })
  42. // Generate TypeScript content
  43. const header = `/**
  44. * AUTO-GENERATED FILE - DO NOT MODIFY MANUALLY
  45. *
  46. * This file is automatically generated from YAML configuration files
  47. * in config/abilities/pages/ directory.
  48. *
  49. * To make changes, edit the source YAML files and run the compilation script:
  50. * npm run compile:abilities
  51. *
  52. * Generated on: ${new Date().toISOString()}
  53. */
  54. `
  55. const tsContent = `${header}export default ${JSON.stringify(compiledAbilities, null, 2)} as const
  56. `
  57. // Write the compiled TypeScript file
  58. fs.writeFileSync(outputPath, tsContent, 'utf8')
  59. console.log(`✓ Abilities config compiled successfully to ${outputPath}`)
  60. console.log(`✓ Processed ${yamlFiles.length} YAML files`)
  61. console.log(`✓ Generated ${Object.keys(compiledAbilities).length} ability definitions`)
  62. }
  63. // Run the compilation
  64. compileAbilitiesConfig()