vendure-config-ref.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import fs from 'fs-extra';
  2. import path from 'node:path';
  3. import {
  4. Node,
  5. ObjectLiteralExpression,
  6. Project,
  7. SourceFile,
  8. SyntaxKind,
  9. VariableDeclaration,
  10. } from 'ts-morph';
  11. export class VendureConfigRef {
  12. readonly sourceFile: SourceFile;
  13. readonly configObject: ObjectLiteralExpression;
  14. constructor(
  15. private project: Project,
  16. configFilePath?: string,
  17. ) {
  18. if (configFilePath) {
  19. const sourceFile = project.getSourceFile(sf => sf.getFilePath().endsWith(configFilePath));
  20. if (!sourceFile) {
  21. throw new Error(`Could not find a config file at "${configFilePath}"`);
  22. }
  23. this.sourceFile = sourceFile;
  24. } else {
  25. const sourceFiles = project
  26. .getSourceFiles()
  27. .filter(sf => this.isVendureConfigFile(sf, { checkFileName: false }));
  28. if (sourceFiles.length > 1) {
  29. throw new Error(
  30. `Multiple Vendure config files found. Please specify which one to use with the --config flag:\n` +
  31. sourceFiles.map(sf => ` - ${sf.getFilePath()}`).join('\n'),
  32. );
  33. }
  34. if (sourceFiles.length === 0) {
  35. throw new Error('Could not find the VendureConfig declaration in your project.');
  36. }
  37. this.sourceFile = sourceFiles[0];
  38. }
  39. this.configObject = this.sourceFile
  40. .getVariableDeclarations()
  41. .find(v => this.isVendureConfigVariableDeclaration(v))
  42. ?.getChildren()
  43. .find(Node.isObjectLiteralExpression) as ObjectLiteralExpression;
  44. }
  45. getPathRelativeToProjectRoot() {
  46. return path.relative(
  47. this.project.getRootDirectories()[0]?.getPath() ?? '',
  48. this.sourceFile.getFilePath(),
  49. );
  50. }
  51. getConfigObjectVariableName() {
  52. return this.sourceFile
  53. ?.getVariableDeclarations()
  54. .find(v => this.isVendureConfigVariableDeclaration(v))
  55. ?.getName();
  56. }
  57. getPluginsArray() {
  58. return this.configObject
  59. .getProperty('plugins')
  60. ?.getFirstChildByKind(SyntaxKind.ArrayLiteralExpression);
  61. }
  62. addToPluginsArray(text: string) {
  63. this.getPluginsArray()?.addElement(text).formatText();
  64. }
  65. private isVendureConfigFile(
  66. sourceFile: SourceFile,
  67. options: { checkFileName?: boolean } = {},
  68. ): boolean {
  69. const checkFileName = options.checkFileName ?? true;
  70. return (
  71. (checkFileName ? sourceFile.getFilePath().endsWith('vendure-config.ts') : true) &&
  72. !!sourceFile.getVariableDeclarations().find(v => this.isVendureConfigVariableDeclaration(v))
  73. );
  74. }
  75. private isVendureConfigVariableDeclaration(v: VariableDeclaration) {
  76. return v.getType().getText(v) === 'VendureConfig';
  77. }
  78. }