plugin.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import { MiddlewareConsumer, NestModule, OnApplicationBootstrap, OnModuleDestroy } from '@nestjs/common';
  2. import { DEFAULT_AUTH_TOKEN_HEADER_KEY } from '@vendure/common/lib/shared-constants';
  3. import {
  4. AdminUiAppConfig,
  5. AdminUiAppDevModeConfig,
  6. AdminUiConfig,
  7. Type,
  8. } from '@vendure/common/lib/shared-types';
  9. import {
  10. ConfigService,
  11. createProxyHandler,
  12. Logger,
  13. PluginCommonModule,
  14. registerPluginStartupMessage,
  15. VendurePlugin,
  16. } from '@vendure/core';
  17. import express from 'express';
  18. import fs from 'fs-extra';
  19. import path from 'path';
  20. import { defaultAvailableLanguages, defaultLanguage, DEFAULT_APP_PATH, loggerCtx } from './constants';
  21. /**
  22. * @description
  23. * Configuration options for the {@link AdminUiPlugin}.
  24. *
  25. * @docsCategory AdminUiPlugin
  26. */
  27. export interface AdminUiPluginOptions {
  28. /**
  29. * @description
  30. * The route to the admin ui.
  31. */
  32. route: string;
  33. /**
  34. * @description
  35. * The port on which the server will listen. If not
  36. */
  37. port: number;
  38. /**
  39. * @description
  40. * The hostname of the server serving the static admin ui files.
  41. *
  42. * @default 'localhost'
  43. */
  44. hostname?: string;
  45. /**
  46. * @description
  47. * By default, the AdminUiPlugin comes bundles with a pre-built version of the
  48. * Admin UI. This option can be used to override this default build with a different
  49. * version, e.g. one pre-compiled with one or more ui extensions.
  50. */
  51. app?: AdminUiAppConfig | AdminUiAppDevModeConfig;
  52. /**
  53. * @description
  54. * Allows the contents of the `vendure-ui-config.json` file to be set, e.g.
  55. * for specifying the Vendure GraphQL API host, available UI languages, etc.
  56. */
  57. adminUiConfig?: Partial<AdminUiConfig>;
  58. }
  59. /**
  60. * @description
  61. * This plugin starts a static server for the Admin UI app, and proxies it via the `/admin/` path of the main Vendure server.
  62. *
  63. * The Admin UI allows you to administer all aspects of your store, from inventory management to order tracking. It is the tool used by
  64. * store administrators on a day-to-day basis for the management of the store.
  65. *
  66. * ## Installation
  67. *
  68. * `yarn add \@vendure/admin-ui-plugin`
  69. *
  70. * or
  71. *
  72. * `npm install \@vendure/admin-ui-plugin`
  73. *
  74. * @example
  75. * ```ts
  76. * import { AdminUiPlugin } from '\@vendure/admin-ui-plugin';
  77. *
  78. * const config: VendureConfig = {
  79. * // Add an instance of the plugin to the plugins array
  80. * plugins: [
  81. * AdminUiPlugin.init({ port: 3002 }),
  82. * ],
  83. * };
  84. * ```
  85. *
  86. * @docsCategory AdminUiPlugin
  87. */
  88. @VendurePlugin({
  89. imports: [PluginCommonModule],
  90. providers: [],
  91. })
  92. export class AdminUiPlugin implements NestModule {
  93. private static options: AdminUiPluginOptions;
  94. constructor(private configService: ConfigService) {}
  95. /**
  96. * @description
  97. * Set the plugin options
  98. */
  99. static init(options: AdminUiPluginOptions): Type<AdminUiPlugin> {
  100. this.options = options;
  101. return AdminUiPlugin;
  102. }
  103. async configure(consumer: MiddlewareConsumer) {
  104. const { app, hostname, route, adminUiConfig } = AdminUiPlugin.options;
  105. const adminUiAppPath = AdminUiPlugin.isDevModeApp(app)
  106. ? path.join(app.sourcePath, 'src')
  107. : (app && app.path) || DEFAULT_APP_PATH;
  108. const adminUiConfigPath = path.join(adminUiAppPath, 'vendure-ui-config.json');
  109. const overwriteConfig = () => {
  110. const uiConfig = this.getAdminUiConfig(adminUiConfig);
  111. return this.overwriteAdminUiConfig(adminUiConfigPath, uiConfig);
  112. };
  113. let port: number;
  114. if (AdminUiPlugin.isDevModeApp(app)) {
  115. port = app.port;
  116. } else {
  117. port = AdminUiPlugin.options.port;
  118. }
  119. if (AdminUiPlugin.isDevModeApp(app)) {
  120. Logger.info('Creating admin ui middleware (dev mode)', loggerCtx);
  121. consumer
  122. .apply(
  123. createProxyHandler({
  124. hostname,
  125. port,
  126. route,
  127. label: 'Admin UI',
  128. basePath: route,
  129. }),
  130. )
  131. .forRoutes(route);
  132. consumer
  133. .apply(
  134. createProxyHandler({
  135. hostname,
  136. port,
  137. route: 'sockjs-node',
  138. label: 'Admin UI live reload',
  139. basePath: 'sockjs-node',
  140. }),
  141. )
  142. .forRoutes('sockjs-node');
  143. Logger.info(`Compiling Admin UI app in development mode`, loggerCtx);
  144. app.compile().then(
  145. () => {
  146. Logger.info(`Admin UI compiling and watching for changes...`, loggerCtx);
  147. },
  148. (err: any) => {
  149. Logger.error(`Failed to compile: ${err}`, loggerCtx, err.stack);
  150. },
  151. );
  152. await overwriteConfig();
  153. } else {
  154. Logger.info('Creating admin ui middleware (prod mode)', loggerCtx);
  155. consumer.apply(await this.createStaticServer(app)).forRoutes(route);
  156. if (app && typeof app.compile === 'function') {
  157. Logger.info(`Compiling Admin UI app in production mode...`, loggerCtx);
  158. app.compile()
  159. .then(overwriteConfig)
  160. .then(
  161. () => {
  162. Logger.info(`Admin UI successfully compiled`, loggerCtx);
  163. },
  164. (err: any) => {
  165. Logger.error(`Failed to compile: ${err}`, loggerCtx, err.stack);
  166. },
  167. );
  168. } else {
  169. await overwriteConfig();
  170. }
  171. }
  172. registerPluginStartupMessage('Admin UI', route);
  173. }
  174. private async createStaticServer(app?: AdminUiAppConfig) {
  175. const adminUiAppPath = (app && app.path) || DEFAULT_APP_PATH;
  176. const adminUiServer = express.Router();
  177. adminUiServer.use(express.static(adminUiAppPath));
  178. adminUiServer.use((req, res) => {
  179. res.sendFile(path.join(adminUiAppPath, 'index.html'));
  180. });
  181. return adminUiServer;
  182. }
  183. /**
  184. * Takes an optional AdminUiConfig provided in the plugin options, and returns a complete
  185. * config object for writing to disk.
  186. */
  187. private getAdminUiConfig(partialConfig?: Partial<AdminUiConfig>): AdminUiConfig {
  188. const { authOptions } = this.configService;
  189. const propOrDefault = <Prop extends keyof AdminUiConfig>(
  190. prop: Prop,
  191. defaultVal: AdminUiConfig[Prop],
  192. ): AdminUiConfig[Prop] => {
  193. return partialConfig ? (partialConfig as AdminUiConfig)[prop] || defaultVal : defaultVal;
  194. };
  195. return {
  196. adminApiPath: propOrDefault('adminApiPath', this.configService.apiOptions.adminApiPath),
  197. apiHost: propOrDefault('apiHost', 'auto'),
  198. apiPort: propOrDefault('apiPort', 'auto'),
  199. tokenMethod: propOrDefault(
  200. 'tokenMethod',
  201. authOptions.tokenMethod === 'bearer' ? 'bearer' : 'cookie',
  202. ),
  203. authTokenHeaderKey: propOrDefault(
  204. 'authTokenHeaderKey',
  205. authOptions.authTokenHeaderKey || DEFAULT_AUTH_TOKEN_HEADER_KEY,
  206. ),
  207. defaultLanguage: propOrDefault('defaultLanguage', defaultLanguage),
  208. availableLanguages: propOrDefault('availableLanguages', defaultAvailableLanguages),
  209. loginUrl: AdminUiPlugin.options.adminUiConfig?.loginUrl,
  210. brand: AdminUiPlugin.options.adminUiConfig?.brand,
  211. hideVendureBranding: propOrDefault(
  212. 'hideVendureBranding',
  213. AdminUiPlugin.options.adminUiConfig?.hideVendureBranding || false,
  214. ),
  215. hideVersion: propOrDefault(
  216. 'hideVersion',
  217. AdminUiPlugin.options.adminUiConfig?.hideVersion || false,
  218. ),
  219. };
  220. }
  221. /**
  222. * Overwrites the parts of the admin-ui app's `vendure-ui-config.json` file relating to connecting to
  223. * the server admin API.
  224. */
  225. private async overwriteAdminUiConfig(adminUiConfigPath: string, config: AdminUiConfig) {
  226. try {
  227. const content = await this.pollForConfigFile(adminUiConfigPath);
  228. } catch (e) {
  229. Logger.error(e.message, loggerCtx);
  230. throw e;
  231. }
  232. try {
  233. await fs.writeFile(adminUiConfigPath, JSON.stringify(config, null, 2));
  234. } catch (e) {
  235. throw new Error('[AdminUiPlugin] Could not write vendure-ui-config.json file:\n' + e.message);
  236. }
  237. Logger.verbose(`Applied configuration to vendure-ui-config.json file`, loggerCtx);
  238. }
  239. /**
  240. * It might be that the ui-devkit compiler has not yet copied the config
  241. * file to the expected location (particularly when running in watch mode),
  242. * so polling is used to check multiple times with a delay.
  243. */
  244. private async pollForConfigFile(adminUiConfigPath: string) {
  245. const maxRetries = 10;
  246. const retryDelay = 200;
  247. let attempts = 0;
  248. const pause = () => new Promise(resolve => setTimeout(resolve, retryDelay));
  249. while (attempts < maxRetries) {
  250. try {
  251. Logger.verbose(`Checking for config file: ${adminUiConfigPath}`, loggerCtx);
  252. const configFileContent = await fs.readFile(adminUiConfigPath, 'utf-8');
  253. return configFileContent;
  254. } catch (e) {
  255. attempts++;
  256. Logger.verbose(
  257. `Unable to locate config file: ${adminUiConfigPath} (attempt ${attempts})`,
  258. loggerCtx,
  259. );
  260. }
  261. await pause();
  262. }
  263. throw new Error(`Unable to locate config file: ${adminUiConfigPath}`);
  264. }
  265. private static isDevModeApp(
  266. app?: AdminUiAppConfig | AdminUiAppDevModeConfig,
  267. ): app is AdminUiAppDevModeConfig {
  268. if (!app) {
  269. return false;
  270. }
  271. return !!(app as AdminUiAppDevModeConfig).sourcePath;
  272. }
  273. }